source
stringlengths
3
92
c
stringlengths
26
2.25M
diagmv_x_sky_n.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t ONAME_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT thread_num = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mul(y[i], beta, y[i]); // y[i] *= beta; } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 1; i < m + 1; ++i) { const ALPHA_INT indx = A->pointers[i] - 1; ALPHA_Number tmp; alpha_mul(tmp, A->values[indx], x[i - 1]); alpha_madde(y[i - 1], alpha, tmp); // y[i - 1] += alpha * v * x[i - 1]; } return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return ONAME_omp(alpha, A, x, beta, y); }
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/ASTConcept.h" #include "clang/AST/ASTFwd.h" #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/DiagnosticSema.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenCLOptions.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaConcept.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; // TODO SYCL Integration header approach relies on an assumption that kernel // lambda objects created by the host compiler and any of the device compilers // will be identical wrt to field types, order and offsets. Some verification // mechanism should be developed to enforce that. // TODO FIXME SYCL Support for SYCL in FE should be refactored: // - kernel identification and generation should be made a separate pass over // AST. RecursiveASTVisitor + VisitFunctionTemplateDecl + // FunctionTemplateDecl::getSpecializations() mechanism could be used for that. // - All SYCL stuff on Sema level should be encapsulated into a single Sema // field // - Move SYCL stuff into a separate header // Represents contents of a SYCL integration header file produced by a SYCL // device compiler and used by SYCL host compiler (via forced inclusion into // compiled SYCL source): // - SYCL kernel names // - SYCL kernel parameters and offsets of corresponding actual arguments class SYCLIntegrationHeader { public: // Kind of kernel's parameters as captured by the compiler in the // kernel lambda or function object enum kernel_param_kind_t { kind_first, kind_accessor = kind_first, kind_std_layout, kind_sampler, kind_pointer, kind_last = kind_pointer }; public: SYCLIntegrationHeader(DiagnosticsEngine &Diag, bool UnnamedLambdaSupport, Sema &S); /// Emits contents of the header into given stream. void emit(raw_ostream &Out); /// Emits contents of the header into a file with given name. /// Returns true/false on success/failure. bool emit(const StringRef &MainSrc); /// Signals that subsequent parameter descriptor additions will go to /// the kernel with given name. Starts new kernel invocation descriptor. void startKernel(StringRef KernelName, QualType KernelNameType, StringRef KernelStableName, SourceLocation Loc, bool IsESIMD); /// Adds a kernel parameter descriptor to current kernel invocation /// descriptor. void addParamDesc(kernel_param_kind_t Kind, int Info, unsigned Offset); /// Signals that addition of parameter descriptors to current kernel /// invocation descriptor has finished. void endKernel(); /// Registers a specialization constant to emit info for it into the header. void addSpecConstant(StringRef IDName, QualType IDType); /// Note which free functions (this_id, this_item, etc) are called within the /// kernel void setCallsThisId(bool B); void setCallsThisItem(bool B); void setCallsThisNDItem(bool B); void setCallsThisGroup(bool B); private: // Kernel actual parameter descriptor. struct KernelParamDesc { // Represents a parameter kind. kernel_param_kind_t Kind = kind_last; // If Kind is kind_scalar or kind_struct, then // denotes parameter size in bytes (includes padding for structs) // If Kind is kind_accessor // denotes access target; possible access targets are defined in // access/access.hpp int Info = 0; // Offset of the captured parameter value in the lambda or function object. unsigned Offset = 0; KernelParamDesc() = default; }; // there are four free functions the kernel may call (this_id, this_item, // this_nd_item, this_group) struct KernelCallsSYCLFreeFunction { bool CallsThisId; bool CallsThisItem; bool CallsThisNDItem; bool CallsThisGroup; }; // Kernel invocation descriptor struct KernelDesc { /// Kernel name. std::string Name; /// Kernel name type. QualType NameType; /// Kernel name with stable lambda name mangling std::string StableName; SourceLocation KernelLocation; /// Whether this kernel is an ESIMD one. bool IsESIMDKernel; /// Descriptor of kernel actual parameters. SmallVector<KernelParamDesc, 8> Params; // Whether kernel calls any of the SYCL free functions (this_item(), // this_id(), etc) KernelCallsSYCLFreeFunction FreeFunctionCalls; KernelDesc() = default; }; /// Returns the latest invocation descriptor started by /// SYCLIntegrationHeader::startKernel KernelDesc *getCurKernelDesc() { return KernelDescs.size() > 0 ? &KernelDescs[KernelDescs.size() - 1] : nullptr; } private: /// Keeps invocation descriptors for each kernel invocation started by /// SYCLIntegrationHeader::startKernel SmallVector<KernelDesc, 4> KernelDescs; using SpecConstID = std::pair<QualType, std::string>; /// Keeps specialization constants met in the translation unit. Maps spec /// constant's ID type to generated unique name. Duplicates are removed at /// integration header emission time. llvm::SmallVector<SpecConstID, 4> SpecConsts; /// Whether header is generated with unnamed lambda support bool UnnamedLambdaSupport; Sema &S; }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; /// A key method to reduce duplicate debug info from Sema. virtual void anchor(); ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: /// The maximum alignment, same as in llvm::Value. We duplicate them here /// because that allows us not to duplicate the constants in clang code, /// which we must to since we can't directly use the llvm constants. /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp /// /// This is the greatest alignment value supported by load, store, and alloca /// instructions, and global values. static const unsigned MaxAlignmentExponent = 29; static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions CurFPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; // #pragma pack and align. class AlignPackInfo { public: // `Native` represents default align mode, which may vary based on the // platform. enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { assert(Num == PackNumber && "The pack number has been truncated."); } // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) : PackAttr(false), AlignMode(M), PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} AlignPackInfo() : AlignPackInfo(Native, false) {} // When a AlignPackInfo itself cannot be used, this returns an 32-bit // integer encoding for it. This should only be passed to // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. static uint32_t getRawEncoding(const AlignPackInfo &Info) { std::uint32_t Encoding{}; if (Info.IsXLStack()) Encoding |= IsXLMask; Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; if (Info.IsPackAttr()) Encoding |= PackAttrMask; Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; return Encoding; } static AlignPackInfo getFromRawEncoding(unsigned Encoding) { bool IsXL = static_cast<bool>(Encoding & IsXLMask); AlignPackInfo::Mode M = static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); int PackNumber = (Encoding & PackNumMask) >> 4; if (Encoding & PackAttrMask) return AlignPackInfo(M, PackNumber, IsXL); return AlignPackInfo(M, IsXL); } bool IsPackAttr() const { return PackAttr; } bool IsAlignAttr() const { return !PackAttr; } Mode getAlignMode() const { return AlignMode; } unsigned getPackNumber() const { return PackNumber; } bool IsPackSet() const { // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack // attriute on a decl. return PackNumber != UninitPackVal && PackNumber != 0; } bool IsXLStack() const { return XLStack; } bool operator==(const AlignPackInfo &Info) const { return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, Info.XLStack); } bool operator!=(const AlignPackInfo &Info) const { return !(*this == Info); } private: /// \brief True if this is a pragma pack attribute, /// not a pragma align attribute. bool PackAttr; /// \brief The alignment mode that is in effect. Mode AlignMode; /// \brief The pack number of the stack. unsigned char PackNumber; /// \brief True if it is a XL #pragma align/pack stack. bool XLStack; /// \brief Uninitialized pack value. static constexpr unsigned char UninitPackVal = -1; // Masks to encode and decode an AlignPackInfo. static constexpr uint32_t IsXLMask{0x0000'0001}; static constexpr uint32_t AlignModeMask{0x0000'0006}; static constexpr uint32_t PackAttrMask{0x00000'0008}; static constexpr uint32_t PackNumMask{0x0000'01F0}; }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value) { if (Action == PSK_Reset) { CurrentValue = DefaultValue; CurrentPragmaLocation = PragmaLocation; return; } if (Action & PSK_Push) Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, PragmaLocation); else if (Action & PSK_Pop) { if (!StackSlotLabel.empty()) { // If we've got a label, try to find it and jump there. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); // If we found the label so pop from there. if (I != Stack.rend()) { CurrentValue = I->Value; CurrentPragmaLocation = I->PragmaLocation; Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); } } if (Action & PSK_Set) { CurrentValue = Value; CurrentPragmaLocation = PragmaLocation; } } // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; PragmaStack<AlignPackInfo> AlignPackStack; // The current #pragma align/pack values and locations at each #include. struct AlignPackIncludeState { AlignPackInfo CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // This stack tracks the current state of Sema.CurFPFeatures. PragmaStack<FPOptionsOverride> FpPragmaStack; FPOptionsOverride CurFPFeatureOverrides() { FPOptionsOverride result; if (!FpPragmaStack.hasValue()) { result = FPOptionsOverride(); } else { result = FpPragmaStack.CurrentValue; } return result; } // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, llvm::SmallPtrSet<Expr *, 4>>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; /// The index of the first FunctionScope that corresponds to the current /// context. unsigned FunctionScopesStart = 0; ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, FunctionScopes.end()); } /// Stack containing information needed when in C++2a an 'auto' is encountered /// in a function declaration parameter type specifier in order to invent a /// corresponding template parameter in the enclosing abbreviated function /// template. This information is also present in LambdaScopeInfo, stored in /// the FunctionScopes stack. SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; /// The index of the first InventedParameterInfo that refers to the current /// context. unsigned InventedParameterInfosStart = 0; ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { return llvm::makeArrayRef(InventedParameterInfos.begin() + InventedParameterInfosStart, InventedParameterInfos.end()); } typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; unsigned SavedFunctionScopesStart; unsigned SavedInventedParameterInfosStart; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride), SavedFunctionScopesStart(S.FunctionScopesStart), SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); // Any saved FunctionScopes do not refer to this context. S.FunctionScopesStart = S.FunctionScopes.size(); S.InventedParameterInfosStart = S.InventedParameterInfos.size(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; S.FunctionScopesStart = SavedFunctionScopesStart; S.InventedParameterInfosStart = SavedInventedParameterInfosStart; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Whether the AST is currently being rebuilt to correct immediate /// invocations. Immediate invocation candidates and references to consteval /// functions aren't tracked when this is set. bool RebuildingImmediateInvocation = false; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// Set of candidates for starting an immediate invocation. llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; /// Set of DeclRefExprs referencing a consteval function when used in a /// context not already known to be immediately invoked. llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the CurFPFeatures state on entry/exit of compound /// statements. class FPFeaturesStateRAII { public: FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { OldOverrides = S.FpPragmaStack.CurrentValue; } ~FPFeaturesStateRAII() { S.CurFPFeatures = OldFPFeaturesState; S.FpPragmaStack.CurrentValue = OldOverrides; } FPOptionsOverride getOverrides() { return OldOverrides; } private: Sema& S; FPOptions OldFPFeaturesState; FPOptionsOverride OldOverrides; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getCurFPFeatures() { return CurFPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. ImmediateDiagBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class ImmediateDiagBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op // in that case anwyay. ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; ~ImmediateDiagBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First clear the diagnostic // builder itself so it won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template <typename T> friend const ImmediateDiagBuilder & operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const ImmediateDiagBuilder &operator<<(T &&V) const { const DiagnosticBuilder &BaseDiag = *this; BaseDiag << std::move(V); return *this; } }; /// A generic diagnostic builder for errors which may or may not be deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class SemaDiagnosticBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; ~SemaDiagnosticBuilder(); bool isImmediate() const { return ImmediateDiag.hasValue(); } /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (SemaDiagnosticBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a SemaDiagnosticBuilder yourself. operator bool() const { return isImmediate(); } template <typename T> friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const SemaDiagnosticBuilder &operator<<(T &&V) const { if (ImmediateDiag.hasValue()) *ImmediateDiag << std::move(V); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); return *this; } friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { if (Diag.ImmediateDiag.hasValue()) PD.Emit(*Diag.ImmediateDiag); else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; return Diag; } void AddFixItHint(const FixItHint &Hint) const { if (ImmediateDiag.hasValue()) ImmediateDiag->AddFixItHint(Hint); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); } friend ExprResult ExprError(const SemaDiagnosticBuilder &) { return ExprError(); } friend StmtResult StmtError(const SemaDiagnosticBuilder &) { return StmtError(); } operator ExprResult() const { return ExprError(); } operator StmtResult() const { return StmtError(); } operator TypeResult() const { return TypeError(); } operator DeclResult() const { return DeclResult(true); } operator MemInitResult() const { return MemInitResult(true); } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Is the last error level diagnostic immediate. This is used to determined /// whether the next info diagnostic should be immediate. bool IsLastErrorImmediate = true; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint = false); /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint = false); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h /// Whether uncompilable error has occurred. This includes error happens /// in deferred diagnostics. bool hasUncompilableErrorOccurred() const; bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; /// Invent a new identifier for parameters of abbreviated templates. IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index); void emitAndClearUnusedLocalTypedefWarnings(); private: /// Function or variable declarations to be checked for whether the deferred /// diagnostics should be emitted. SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags; public: // Emit all deferred diagnostics. void emitDeferredDiags(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } /// Called before parsing a function declarator belonging to a function /// declaration. void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth); /// Called after parsing a function declarator belonging to a function /// declaration. void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); SYCLIntelFPGAIVDepAttr * BuildSYCLIntelFPGAIVDepAttr(const AttributeCommonInfo &CI, Expr *Expr1, Expr *Expr2); template <typename FPGALoopAttrT> FPGALoopAttrT *BuildSYCLIntelFPGALoopAttr(const AttributeCommonInfo &A, Expr *E = nullptr); LoopUnrollHintAttr *BuildLoopUnrollHintAttr(const AttributeCommonInfo &A, Expr *E); OpenCLUnrollHintAttr * BuildOpenCLLoopUnrollHintAttr(const AttributeCommonInfo &A, Expr *E); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Stmt *E); /// Determine whether the callee of a particular function call can throw. /// E, D and Loc are all optional. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc = SourceLocation()); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { protected: unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal argument for the /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name /// is invalid for the given declaration. /// /// \p AL is used to provide caret diagnostics in case of a malformed name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync); /// A derivative of BoundTypeDiagnoser for which the diagnostic's type /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. /// For example, a diagnostic with no other parameters would generally have /// the form "...%select{incomplete|sizeless}0 type %1...". template <typename... Ts> class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { public: SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); this->emit(DB, std::index_sequence_for<Ts...>()); DB << T->isSizelessType() << T; } }; enum class CompleteTypeKind { /// Apply the normal rules for complete types. In particular, /// treat all sizeless types as incomplete. Normal, /// Relax the normal rules for complete types so that they include /// sizeless built-in types. AcceptSizeless, // FIXME: Eventually we should flip the default to Normal and opt in // to AcceptSizeless rather than opt out of it. Default = AcceptSizeless }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(const Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); // When loading a non-modular PCH files, this is used to restore module // visibility. void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { VisibleModules.setVisible(Mod, ImportLoc); } /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return D->isUnconditionallyVisible() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind = CompleteTypeKind::Default) { return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, unsigned DiagID); bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); } bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); } template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); } /// Get the type of expression E, triggering instantiation to complete the /// type if necessary -- that is, if the expression refers to a templated /// static data member of incomplete array type. /// /// May still return an incomplete type if instantiation was not possible or /// if the type is incomplete for a different reason. Use /// RequireCompleteExprType instead if a diagnostic is expected for an /// incomplete expression type. QualType getCompletedType(Expr *E); void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as an overload set, and an expression /// representing that overload set has been formed. /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable /// expression referencing the overload set. NC_OverloadSet, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, /// The name was classified as a concept name. NC_Concept, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification OverloadSet(ExprResult E) { NameClassification Result(NC_OverloadSet); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification Concept(TemplateName Name) { NameClassification Result(NC_Concept); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_OverloadSet); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_Concept: return TNK_Concept_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Act on the result of classifying a name as an overload set. ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Enter a template parameter scope, after it's been associated with a particular /// DeclContext. Causes lookup within the scope to chain through enclosing contexts /// in the correct order. void EnterTemplatedContext(Scope *S, DeclContext *DC); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); WebAssemblyImportNameAttr *mergeImportNameAttr( Decl *D, const WebAssemblyImportNameAttr &AL); WebAssemblyImportModuleAttr *mergeImportModuleAttr( Decl *D, const WebAssemblyImportModuleAttr &AL); EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL); SYCLIntelLoopFuseAttr * mergeSYCLIntelLoopFuseAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true, bool ConsiderRequiresClauses = true); enum class AllowedExplicit { /// Allow no explicit functions to be used. None, /// Allow explicit conversion functions but not explicit constructors. Conversions, /// Allow both explicit conversion functions and explicit constructors. All }; ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool IsStringInit(Expr *Init, const ArrayType *AT); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE, NamedDecl *Dest = nullptr); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfSingleOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); void AddOverloadedCallCandidates( LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL = true); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, bool AllowRecovery = false); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up a name following ~ in a destructor name. This is an ordinary /// lookup, but prefers tags to typedefs. LookupDestructorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplatePack, }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, SourceLocation TypoLoc); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit = nullptr); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final = false); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param RecoverUncorrectedTypos If true, when typo correction fails, it /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr( Expr *E, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr( ExprResult ER, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), InitDecl, RecoverUncorrectedTypos, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} /// Attempts to produce a RecoveryExpr after some AST node cannot be created. ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef<Expr *> SubExprs, QualType T = QualType()); ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FunctionDecl *FD); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnAfterCompoundStatementLeadingPragmas(); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); bool CheckRebuiltAttributedStmtAttributes(ArrayRef<const Attr *> Attrs); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Try to convert an expression \p E to type \p Ty. Returns the result of the /// conversion. ExprResult tryConvertExprToType(Expr *E, QualType Ty); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseDependentMemberLookup(LookupResult &R); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE = nullptr); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); ExprResult BuildUniqueStableName(SourceLocation Loc, TypeSourceInfo *Operand); ExprResult BuildUniqueStableName(SourceLocation Loc, Expr *E); ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType Ty); ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, Expr *E); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc); ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef<Expr *> Dims, ArrayRef<SourceRange> Brackets); /// Data structure for iterator expression. struct OMPIteratorData { IdentifierInfo *DeclIdent = nullptr; SourceLocation DeclIdentLoc; ParsedType Type; OMPIteratorExpr::IteratorRange Range; SourceLocation AssignLoc; SourceLocation ColonLoc; SourceLocation SecColonLoc; }; ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef<OMPIteratorData> Data); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth); // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); /// Wrap the expression in a ConstantExpr if it is a potential immediate /// invocation. ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, ExprResult RequiresClause); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, false is returned, and /// PossibleNonPrimary will be set to true if the failure might be due to a /// non-primary expression being used as an atomic constraint. bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), bool *PossibleNonPrimary = nullptr, bool IsTrailingRequiresClause = false); private: /// Caches pairs of template-like decls whose associated constraints were /// checked for subsumption and whether or not the first's constraints did in /// fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; /// Caches the normalized associated constraints of declarations (concepts or /// constrained declarations). If an error occurred while normalizing the /// associated constraints of the template or concept, nullptr will be cached /// here. llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> SatisfactionCache; public: const NormalizedConstraint * getNormalizedAssociatedConstraints( NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// If D1 was not at least as constrained as D2, but would've been if a pair /// of atomic constraints involved had been declared in a concept and not /// repeated in two separate places in code. /// \returns true if such a diagnostic was emitted, false otherwise. bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param Template the template-like entity that triggered the constraints /// check (either a concept or a constrained entity). /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction( const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check whether the given function decl's trailing requires clause is /// satisfied, if any. Returns false and updates Satisfaction with the /// satisfaction verdict if successful, emits a diagnostic and returns true if /// an error occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc = SourceLocation()); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. /// \param First whether this is the first time an unsatisfied constraint is /// diagnosed for this error. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, bool First = true); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's /// destructor is referenced. void MarkVirtualBaseDestructorsReferenced( SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); /// Do semantic checks to allow the complete destructor variant to be emitted /// when the destructor is defined in another translation unit. In the Itanium /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they /// can be emitted in separate TUs. To emit the complete variant, run a subset /// of the checks performed when emitting a regular destructor. void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref<Scope *()> EnterScope); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbiguousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; /// Whether and why a template name is required in this lookup. class RequiredTemplateKind { public: /// Template name is required if TemplateKWLoc is valid. RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) : TemplateKW(TemplateKWLoc) {} /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} SourceLocation getTemplateKeywordLoc() const { return TemplateKW.getValueOr(SourceLocation()); } bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } bool isRequired() const { return TemplateKW != SourceLocation(); } explicit operator bool() const { return isRequired(); } private: llvm::Optional<SourceLocation> TemplateKW; }; enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName( LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate = SourceLocation(), AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation = false); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint); bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool RequireStructuralType(QualType T, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic = false); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); /// Get the specialization of the given variable template corresponding to /// the specified argument list, or a null-but-valid result if the arguments /// are dependent. DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); /// Form a reference to the specialization of the given variable template /// corresponding to the specified argument list, or a null-but-valid result /// if the arguments are dependent. ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, bool DeducedTSTContext = true); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Concepts //===--------------------------------------------------------------------===// Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef<ParmVarDecl *> LocalParameters, Scope *BodyScope); void ActOnFinishRequiresExpr(); concepts::Requirement *ActOnSimpleRequirement(Expr *E); concepts::Requirement *ActOnTypeRequirement( SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); concepts::Requirement *ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc); concepts::Requirement * ActOnCompoundRequirement( Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, unsigned Depth); concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); concepts::ExprRequirement * BuildExprRequirement( Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::ExprRequirement * BuildExprRequirement( concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); concepts::TypeRequirement * BuildTypeRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); concepts::NestedRequirement *BuildNestedRequirement(Expr *E); concepts::NestedRequirement * BuildNestedRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> LocalParameters, ArrayRef<concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression. UPPC_Block, /// A type constraint. UPPC_TypeConstraint, // A requirement in a requires-expression. UPPC_Requirement, // A requires-clause. UPPC_RequiresClause, }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given requirees-expression contains an unexpanded reference to one /// of its own parameter packs, diagnose the error. /// /// \param RE The requiress-expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate( FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2, bool Reversed = false); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are instantiating a requirement of a requires expression. RequirementInstantiation, /// We are checking the satisfaction of a nested requirement of a requires /// expression. NestedRequirementConstraintsCheck, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// We are initializing a structured binding. InitializingStructuredBinding, /// We are marking a class as __dllexport. MarkingClassDllexported, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// \brief Note that we are substituting template arguments into a part of /// a requirement of a requires expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are checking the satisfaction of the constraint /// expression inside of a nested requirement. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::NestedRequirement *Req, ConstraintsCheck, SourceRange InstantiationRange = SourceRange()); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } else { // Template instantiations in the PCH may be delayed until the TU. S.PendingInstantiations.swap(SavedPendingInstantiations); S.PendingInstantiations.insert(S.PendingInstantiations.end(), SavedPendingInstantiations.begin(), SavedPendingInstantiations.end()); } } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); bool CheckInstantiatedFunctionTemplateConstraints( SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef<TemplateArgument> TemplateArgs, ConstraintSatisfaction &Satisfaction); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); void deduceOpenCLAddressSpace(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaAlignPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaAlignPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// Are precise floating point semantics currently enabled? bool isPreciseFPEnabled() { return !CurFPFeatures.getAllowFPReassociate() && !CurFPFeatures.getNoSignedZero() && !CurFPFeatures.getAllowReciprocal() && !CurFPFeatures.getAllowApproxFunc(); } /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); /// Called on well formed /// \#pragma clang fp reassociate void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// Called to set constant rounding mode for floating point operations. void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); /// Called to set exception behavior for floating point operations. void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); template <typename AttrType> bool checkRangedIntegralArgument(Expr *E, const AttrType *TmpAttr, ExprResult &Result); template <typename AttrType> void AddOneConstantValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); template <typename AttrType> void AddOneConstantPowerTwoValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); void AddIntelFPGABankBitsAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size); template <typename AttrType> void addIntelSYCLSingleArgFunctionAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); template <typename AttrType> void addIntelSYCLTripleArgFunctionAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDimExpr, Expr *YDimExpr, Expr *ZDimExpr); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef<Expr *> Args); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addSYCLIntelPipeIOAttr - Adds a pipe I/O attribute to a particular /// declaration. void addSYCLIntelPipeIOAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ID); void addSYCLIntelLoopFuseAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); bool checkAllowedSYCLInitializer(VarDecl *VD, bool CheckValueDependent = false); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); /// Check that the expression co_await promise.final_suspend() shall not be /// potentially-throwing. bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = std::string(Ext); } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. SmallVector<SourceLocation, 4> DeclareTargetNesting; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); /// Helper to keep information about the current `omp begin/end declare /// variant` nesting. struct OMPDeclareVariantScope { /// The associated OpenMP context selector. OMPTraitInfo *TI; /// The associated OpenMP context selector mangling. std::string NameSuffix; OMPDeclareVariantScope(OMPTraitInfo &TI); }; /// Return the OMPTraitInfo for the surrounding scope, if any. OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { return OMPDeclareVariantScopes.empty() ? nullptr : OMPDeclareVariantScopes.back().TI; } /// The current `omp begin/end declare variant` scopes. SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; /// The current `omp begin/end assumes` scopes. SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; /// All `omp assumes` we encountered so far. SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; public: /// The declarator \p D defines a function in the scope \p S which is nested /// in an `omp begin/end declare variant` scope. In this method we create a /// declaration for \p D and rename \p D according to the OpenMP context /// selector of the surrounding scope. Return all base functions in \p Bases. void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl<FunctionDecl *> &Bases); /// Register \p D as specialization of all base functions in \p Bases in the /// current `omp begin/end declare variant` scope. void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); /// Can we exit an OpenMP declare variant scope at the moment. bool isInOpenMPDeclareVariantScope() const { return !OMPDeclareVariantScopes.empty(); } /// Given the potential call expression \p Call, determine if there is a /// specialization via the OpenMP declare variant mechanism available. If /// there is, return the specialized call expression, otherwise return the /// original \p Call. ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig); /// Handle a `omp begin declare variant`. void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); /// Handle a `omp end declare variant`. void ActOnOpenMPEndDeclareVariant(); /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; /// Check if the specified global variable must be captured by outer capture /// regions. /// \param Level Relative level of nested OpenMP construct for that /// the check is performed. bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp [begin] assume[s]'. void ActOnOpenMPAssumesDirective(SourceLocation Loc, OpenMPDirectiveKind DKind, ArrayRef<StringRef> Assumptions, bool SkippedClauses); /// Check if there is an active global `omp begin assumes` directive. bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } /// Check if there is an active global `omp assumes` directive. bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } /// Called on well-formed '#pragma omp end assumes'. void ActOnOpenMPEndAssumesDirective(); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; const ValueDecl *getOpenMPDeclareMapperVarName() const; /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl * lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, NamedDeclSetType &SameDirectiveDecls); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return !DeclareTargetNesting.empty(); } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp depobj'. StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp scan'. StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type, bool IsDeclareSimd = false); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The trait info object representing the match clause. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The context traits associated with the function variant. void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'detach' clause. OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'order' clause. OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acq_rel' clause. OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acquire' clause. OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'release' clause. OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'relaxed' clause. OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'destroy' clause. OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation ExtraModifierLoc, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc); /// Called on well-formed 'inclusive' clause. OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'exclusive' clause. OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause( ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depobj' pseudo clause. OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause * ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'use_device_addr' clause. OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Data for list of allocators. struct UsesAllocatorsData { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; /// Called on well-formed 'uses_allocators' clause. OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<UsesAllocatorsData> Data); /// Called on well-formed 'affinity' clause. OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This function is a no-op if the operand has a function type // or an array type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatibleFunctionPointer - The assignment is between two function /// pointers types that are not compatible, but we accept them as an /// extension. IncompatibleFunctionPointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); /// Type checking for matrix binary operators. QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); bool isValidSveBitcast(QualType srcType, QualType destType); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, NestedQualification = 0x2, Function = 0x4, DerivedToBase = 0x8, ObjC = 0x10, ObjCLifetime = 0x20, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) = 0; virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); virtual ~VerifyICEDiagnoser() {} }; enum AllowFoldKind { NoFold, AllowFold, }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold = NoFold) { return VerifyIntegerConstantExpression(E, nullptr, CanFold); } /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics /// unless \p EmitOnBothSides is true. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD) { return targetDiag(Loc, PD.getDiagID()) << PD; } /// Check if the expression is allowed to be used in expressions for the /// offloading devices. void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); /// May add implicit CUDAConstantAttr attribute to VD, depending on VD /// and current compilation settings. void MaybeAddCUDAConstantAttr(VarDecl *VD); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas by default is host device function unless it has explicit /// host or device attribute. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); /// Trigger code completion for a record of \p BaseType. \p InitExprs are /// expressions in the initializer list seen so far and \p D is the current /// Designation being parsed. void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D); void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteAfterFunctionEquals(Declarator &D); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); void CheckSYCLKernelCall(FunctionDecl *CallerFunc, SourceRange CallLoc, ArrayRef<const Expr *> Args); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, bool WantCDE); bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckIntelFPGARegBuiltinFunctionCall(unsigned BuiltinID, CallExpr *Call); bool CheckIntelFPGAMemBuiltinFunctionCall(CallExpr *Call); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinComplex(CallExpr *TheCall); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc); bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); // Matrix builtin handling. ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, ExprResult CallResult); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckFreeArguments(const CallExpr *E); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(const Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Nullable_result = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; bool isCFError(RecordDecl *D); /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// Determine the number of levels of enclosing template parameters. This is /// only usable while parsing. Note that this does not include dependent /// contexts in which no template parameters have yet been declared, such as /// in a terse function template or generic lambda before the first 'auto' is /// encountered. unsigned getTemplateDepth(Scope *S) const; /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; private: // We store SYCL Kernels here and handle separately -- which is a hack. // FIXME: It would be best to refactor this. llvm::SetVector<Decl *> SyclDeviceDecls; // SYCL integration header instance for current compilation unit this Sema // is associated with. std::unique_ptr<SYCLIntegrationHeader> SyclIntHeader; // Used to suppress diagnostics during kernel construction, since these were // already emitted earlier. Diagnosing during Kernel emissions also skips the // useful notes that shows where the kernel was called. bool DiagnosingSYCLKernel = false; public: void addSyclDeviceDecl(Decl *d) { SyclDeviceDecls.insert(d); } llvm::SetVector<Decl *> &syclDeviceDecls() { return SyclDeviceDecls; } /// Lazily creates and returns SYCL integration header instance. SYCLIntegrationHeader &getSyclIntegrationHeader() { if (SyclIntHeader == nullptr) SyclIntHeader = std::make_unique<SYCLIntegrationHeader>( getDiagnostics(), getLangOpts().SYCLUnnamedLambda, *this); return *SyclIntHeader.get(); } enum SYCLRestrictKind { KernelGlobalVariable, KernelRTTI, KernelNonConstStaticDataVariable, KernelCallVirtualFunction, KernelUseExceptions, KernelCallRecursiveFunction, KernelCallFunctionPointer, KernelAllocateStorage, KernelUseAssembly, KernelCallDllimportFunction, KernelCallVariadicFunction, KernelCallUndefinedFunction, KernelConstStaticVariable }; bool isKnownGoodSYCLDecl(const Decl *D); void checkSYCLDeviceVarDecl(VarDecl *Var); void ConstructOpenCLKernel(FunctionDecl *KernelCallerFunc, MangleContext &MC); void MarkDevice(); /// Emit a diagnostic about the given attribute having a deprecated name, and /// also emit a fixit hint to generate the new attribute name. void DiagnoseDeprecatedAttribute(const ParsedAttr &A, StringRef NewScope, StringRef NewName); /// Diagnoses an attribute in the 'intelfpga' namespace and suggests using /// the attribute in the 'intel' namespace instead. void CheckDeprecatedSYCLAttributeSpelling(const ParsedAttr &A, StringRef NewName = ""); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurLexicalContext is a kernel function or it is known that the /// function will be emitted for the device, emits the diagnostics /// immediately. /// - If CurLexicalContext is a function and we are compiling /// for the device, but we don't know that this function will be codegen'ed /// for devive yet, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// Diagnose __float128 type usage only from SYCL device code if the current /// target doesn't support it /// if (!S.Context.getTargetInfo().hasFloat128Type() && /// S.getLangOpts().SYCLIsDevice) /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed, creates a deferred diagnostic to be emitted if /// and when the caller is codegen'ed, and returns true. /// /// - Otherwise, returns true without emitting any diagnostics. /// /// Adds Callee to DeviceCallGraph if we don't know if its caller will be /// codegen'ed yet. bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); /// Finishes analysis of the deferred functions calls that may be not /// properly declared for device compilation. void finalizeSYCLDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Tells whether given variable is a SYCL explicit SIMD extension's "private /// global" variable - global variable in the private address space. bool isSYCLEsimdPrivateGlobal(VarDecl *VDecl) { return getLangOpts().SYCLIsDevice && getLangOpts().SYCLExplicitSIMD && VDecl->hasGlobalStorage() && (VDecl->getType().getAddressSpace() == LangAS::opencl_private); } }; template <typename AttrType> void Sema::addIntelSYCLSingleArgFunctionAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) { assert(E && "Attribute must have an argument."); if (!E->isInstantiationDependent()) { Optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(getASTContext()); if (!ArgVal) { Diag(E->getExprLoc(), diag::err_attribute_argument_type) << CI.getAttrName() << AANT_ArgumentIntegerConstant << E->getSourceRange(); return; } int32_t ArgInt = ArgVal->getSExtValue(); if (CI.getParsedKind() == ParsedAttr::AT_SYCLIntelNumSimdWorkItems || CI.getParsedKind() == ParsedAttr::AT_IntelReqdSubGroupSize) { if (ArgInt <= 0) { Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer) << CI.getAttrName() << /*positive*/ 0; return; } } if (CI.getParsedKind() == ParsedAttr::AT_SYCLIntelMaxGlobalWorkDim) { if (ArgInt < 0) { Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer) << CI.getAttrName() << /*non-negative*/ 1; return; } if (ArgInt > 3) { Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range) << CI.getAttrName() << 0 << 3 << E->getSourceRange(); return; } } } D->addAttr(::new (Context) AttrType(Context, CI, E)); } template <typename AttrInfo> static bool handleMaxWorkSizeAttrExpr(Sema &S, const AttrInfo &AI, const Expr *E, unsigned &Val, unsigned Idx) { assert(E && "Attribute must have an argument."); if (!E->isInstantiationDependent()) { Optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(S.getASTContext()); if (!ArgVal) { S.Diag(AI.getLocation(), diag::err_attribute_argument_type) << &AI << AANT_ArgumentIntegerConstant << E->getSourceRange(); return false; } if (ArgVal->isNegative()) { S.Diag(E->getExprLoc(), diag::warn_attribute_requires_non_negative_integer_argument) << E->getType() << S.Context.UnsignedLongLongTy << E->getSourceRange(); return true; } Val = ArgVal->getZExtValue(); if (Val == 0) { S.Diag(E->getExprLoc(), diag::err_attribute_argument_is_zero) << &AI << E->getSourceRange(); return false; } } return true; } template <typename AttrType> static bool checkMaxWorkSizeAttrArguments(Sema &S, Expr *XDimExpr, Expr *YDimExpr, Expr *ZDimExpr, const AttrType &Attr) { // Accept template arguments for now as they depend on something else. // We'll get to check them when they eventually get instantiated. if (XDimExpr->isValueDependent() || (YDimExpr && YDimExpr->isValueDependent()) || (ZDimExpr && ZDimExpr->isValueDependent())) return false; unsigned XDim = 0; if (!handleMaxWorkSizeAttrExpr(S, Attr, XDimExpr, XDim, 0)) return true; unsigned YDim = 0; if (YDimExpr && !handleMaxWorkSizeAttrExpr(S, Attr, YDimExpr, YDim, 1)) return true; unsigned ZDim = 0; if (ZDimExpr && !handleMaxWorkSizeAttrExpr(S, Attr, ZDimExpr, ZDim, 2)) return true; return false; } template <typename WorkGroupAttrType> void Sema::addIntelSYCLTripleArgFunctionAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDimExpr, Expr *YDimExpr, Expr *ZDimExpr) { WorkGroupAttrType TmpAttr(Context, CI, XDimExpr, YDimExpr, ZDimExpr); if (checkMaxWorkSizeAttrArguments(*this, XDimExpr, YDimExpr, ZDimExpr, TmpAttr)) return; D->addAttr(::new (Context) WorkGroupAttrType(Context, CI, XDimExpr, YDimExpr, ZDimExpr)); } template <typename AttrType> void Sema::AddOneConstantValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) { AttrType TmpAttr(Context, CI, E); if (!E->isValueDependent()) { ExprResult ICE; if (checkRangedIntegralArgument<AttrType>(E, &TmpAttr, ICE)) return; E = ICE.get(); } if (IntelFPGAPrivateCopiesAttr::classof(&TmpAttr)) { if (!D->hasAttr<IntelFPGAMemoryAttr>()) D->addAttr(IntelFPGAMemoryAttr::CreateImplicit( Context, IntelFPGAMemoryAttr::Default)); } D->addAttr(::new (Context) AttrType(Context, CI, E)); } template <typename AttrType> void Sema::AddOneConstantPowerTwoValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) { AttrType TmpAttr(Context, CI, E); if (!E->isValueDependent()) { ExprResult ICE; if (checkRangedIntegralArgument<AttrType>(E, &TmpAttr, ICE)) return; Expr::EvalResult Result; E->EvaluateAsInt(Result, Context); llvm::APSInt Value = Result.Val.getInt(); if (!Value.isPowerOf2()) { Diag(CI.getLoc(), diag::err_attribute_argument_not_power_of_two) << &TmpAttr; return; } if (IntelFPGANumBanksAttr::classof(&TmpAttr)) { if (auto *BBA = D->getAttr<IntelFPGABankBitsAttr>()) { unsigned NumBankBits = BBA->args_size(); if (NumBankBits != Value.ceilLogBase2()) { Diag(TmpAttr.getLocation(), diag::err_bankbits_numbanks_conflicting); return; } } } E = ICE.get(); } if (!D->hasAttr<IntelFPGAMemoryAttr>()) D->addAttr(IntelFPGAMemoryAttr::CreateImplicit( Context, IntelFPGAMemoryAttr::Default)); // We are adding a user NumBanks, drop any implicit default. if (IntelFPGANumBanksAttr::classof(&TmpAttr)) { if (auto *NBA = D->getAttr<IntelFPGANumBanksAttr>()) if (NBA->isImplicit()) D->dropAttr<IntelFPGANumBanksAttr>(); } D->addAttr(::new (Context) AttrType(Context, CI, E)); } template <typename FPGALoopAttrT> FPGALoopAttrT *Sema::BuildSYCLIntelFPGALoopAttr(const AttributeCommonInfo &A, Expr *E) { if (!E && !(A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGALoopCoalesce)) return nullptr; if (E && !E->isInstantiationDependent()) { Optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(getASTContext()); if (!ArgVal) { Diag(E->getExprLoc(), diag::err_attribute_argument_type) << A.getAttrName() << AANT_ArgumentIntegerConstant << E->getSourceRange(); return nullptr; } int Val = ArgVal->getSExtValue(); if (A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGAInitiationInterval || A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGALoopCoalesce) { if (Val <= 0) { Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer) << A.getAttrName() << /* positive */ 0; return nullptr; } } else if (A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGAMaxConcurrency || A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGAMaxInterleaving || A.getParsedKind() == ParsedAttr::AT_SYCLIntelFPGASpeculatedIterations) { if (Val < 0) { Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer) << A.getAttrName() << /* non-negative */ 1; return nullptr; } } else { llvm_unreachable("unknown sycl fpga loop attr"); } } return new (Context) FPGALoopAttrT(Context, A, E); } /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; template <> void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, AlignPackInfo Value); } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getHashValue()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
GB_unop__ainv_uint16_uint16.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__ainv_uint16_uint16) // op(A') function: GB (_unop_tran__ainv_uint16_uint16) // C type: uint16_t // A type: uint16_t // cast: uint16_t cij = aij // unaryop: cij = -aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_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) \ uint16_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint16_t z = aij ; \ Cx [pC] = -z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__ainv_uint16_uint16) ( uint16_t *Cx, // Cx and Ax may be aliased const uint16_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 ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (uint16_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint16_t aij = Ax [p] ; uint16_t z = aij ; Cx [p] = -z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint16_t aij = Ax [p] ; uint16_t z = aij ; Cx [p] = -z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__ainv_uint16_uint16) ( 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
requires-1.c
#pragma omp requires unified_address #pragma omp requires unified_shared_memory #pragma omp requires unified_shared_memory unified_address #pragma omp requires dynamic_allocators,reverse_offload void foo () { } #pragma omp requires unified_shared_memory unified_address #pragma omp requires atomic_default_mem_order(seq_cst) /* { dg-prune-output "not supported yet" } */
gt.scorereads.c
/* * gt.scorereads.c * * Created on: 8 Jul 2013 * Author: heath */ #define GT_SCOREREADS "gt.scorereads" #define GT_SCOREREADS_VERSION "1.0" #include <getopt.h> #include <ctype.h> #ifdef HAVE_OPENMP #include <omp.h> #endif #include <pthread.h> #include "gem_tools.h" #include "gt_pipe_io.h" #define MAP_THRESHOLD 3 #define AP_BUF_SIZE 16384 #define QUAL_FASTQ 33 #define QUAL_SOLEXA 64 #define SOLEXA_BAD_QUAL 2 #define DEFAULT_QUAL (QUAL_FASTQ) #define MISSING_QUAL 40 // Value to use in alignment score if qualities not available #define INDEL_QUAL 40 // Value to use in alignment score for indels #define MAX_GT_SCORE 0xFFFF #define MAX_QUAL 42 #define ALIGN_NORM 0 #define ALIGN_BS_POS 1 #define ALIGN_BS_NEG 2 #define ALIGN_TYPES 3 #define AL_FORWARD 4 #define AL_REVERSE 8 #define AL_DIRECTIONS ((AL_FORWARD)|(AL_REVERSE)) #define AL_USED 128 #define GT_SCOREREADS_NUM_LINES (GT_IMP_NUM_LINES>>1) #define GT_SCOREREADS_DEFAULT_OUTPUT_FORMAT MAP typedef enum {all, unmapped, poorly_mapped, discordant, trim_maps, one_end_anchored} gt_scorereads_filter; typedef struct { gt_string *name; gt_file_format format; gt_scorereads_filter filter; gt_output_file *output_file; gt_generic_printer_attributes *printer_attr; } output_def; typedef struct { gt_buffered_output_file *buffered_output; gt_output_sam_attributes *sam_attributes; } gt_scorereads_buffered_output; typedef struct { char *input_files[2]; gt_vector *outputs; // output_def* char *dist_file; char* name_reference_file; char* name_gem_index_file; char* sam_header_file; char* read_group_id; bool mmap_input; bool verbose; bool compact_format; // for SAM output /* Control flags */ bool load_index; bool load_index_sequences; bool is_paired; bool output_seq_qual_for_secondary_align; bool realign; bool bisulfite; gt_file_format output_format; gt_output_file_compression compress; gt_generic_printer_attributes *printer_attr; gt_buffered_output_file *buf_output[2]; int num_threads; gt_map_score_attributes map_score_attr; gt_sequence_archive *sequence_archive; } sr_param; typedef struct { int64_t x; uint64_t ct; UT_hash_handle hh; } sr_dist_element; sr_param param = { .input_files={NULL,NULL}, .outputs=NULL, .dist_file=NULL, .name_reference_file=NULL, .name_gem_index_file=NULL, .sam_header_file=NULL, .read_group_id=NULL, .mmap_input=false, .compress=NONE, .verbose=false, .compact_format=false, .load_index=false, .load_index_sequences=false, .is_paired=false, .output_seq_qual_for_secondary_align=false, .bisulfite=false, .num_threads=1, .map_score_attr.indel_penalty=INDEL_QUAL, .map_score_attr.split_penalty=INDEL_QUAL, .map_score_attr.mapping_cutoff=0, .map_score_attr.max_strata_searched=0, .map_score_attr.max_pair_maps=GT_MAP_SCORE_MAX_PAIR_MAPS, .map_score_attr.max_orphan_maps=GT_MAP_SCORE_MAX_ORPHAN_MAPS, .map_score_attr.quality_format=GT_QUALS_OFFSET_33, .map_score_attr.minimum_insert=0, .map_score_attr.maximum_insert=0, .map_score_attr.insert_phred=NULL, .sequence_archive=NULL, }; void usage(const gt_option* const options,char* groups[],const bool print_inactive) { fprintf(stderr, "USE: ./gt_scorereads [ARGS]...\n"); gt_options_fprint_menu(stderr,options,groups,false,print_inactive); } static sr_dist_element *sr_find_insert_counter(sr_dist_element **de,int64_t x) { sr_dist_element *new_de; HASH_FIND(hh,*de,&x,sizeof(int64_t),new_de); if(!new_de) { new_de=gt_alloc(sr_dist_element); new_de->ct=0; new_de->x=x; HASH_ADD(hh,*de,x,sizeof(int64_t),new_de); } return new_de; } static sr_dist_element *sr_increase_insert_count(sr_dist_element **de,int64_t x,uint64_t ct) { sr_dist_element *new_de=sr_find_insert_counter(de,x); new_de->ct+=ct; return new_de; } gt_sequence_archive* gt_open_sequence_archive(const bool load_sequences) { gt_sequence_archive* sequence_archive = NULL; if (param.name_gem_index_file!=NULL) { // Load GEM-IDX sequence_archive = gt_sequence_archive_new(GT_BED_ARCHIVE); gt_gemIdx_load_archive(param.name_gem_index_file,sequence_archive,load_sequences); } else { gt_input_file* const reference_file = gt_input_file_open(param.name_reference_file,false); sequence_archive = gt_sequence_archive_new(GT_CDNA_ARCHIVE); if (gt_input_multifasta_parser_get_archive(reference_file,sequence_archive)!=GT_IFP_OK) { gt_fatal_error_msg("Error parsing reference file '%s'\n",param.name_reference_file); } gt_input_file_close(reference_file); } return sequence_archive; } static gt_status gt_scorereads_get_insert_size(gt_template *template,int64_t *size) { gt_status err=GT_STATUS_FAIL; int j; gt_alignment *al[2]; uint64_t nmap[2]={0,0}; for(j=0;j<2;j++) { al[j]=gt_template_get_block(template,j); uint64_t i,k; k=gt_alignment_get_num_counters(al[j]); for(i=0;i<k;i++) { uint64_t x=gt_alignment_get_counter(al[j],i); if(x) { nmap[j]+=x; } else if(nmap[j]) break; } } if(nmap[0]==1 && nmap[1]==1) { gt_map *mmap[2]; mmap[0]=gt_alignment_get_map(al[0],0); mmap[1]=gt_alignment_get_map(al[1],0); int64_t x=gt_template_get_insert_size(mmap,&err,0,0); if(err==GT_TEMPLATE_INSERT_SIZE_OK) { err=GT_STATUS_OK; *size=x; } } return err; } static void gt_scorereads_free_insert_hash(sr_dist_element *ins) { sr_dist_element *next_elem; while(ins) { next_elem=ins->hh.next; free(ins); ins=next_elem; } } void gt_add_extra_tags(gt_attributes *attributes,uint32_t mcs[],bool paired,gt_map_score_attributes *ms_attr) { char *tag; if(paired) asprintf(&tag,"ms:B:I,%" PRIu32 ",%" PRIu32 " mx:i:%d",mcs[0],mcs[1],ms_attr->mapping_cutoff); else asprintf(&tag,"ms:B:I,%" PRIu32 " mx:i:%d",mcs[0],ms_attr->mapping_cutoff); gt_cond_fatal_error(!tag,MEM_HANDLER); gt_string *extra_string=gt_string_set_new(tag); free(tag); gt_string *old=gt_attributes_get(attributes,GT_ATTR_ID_TAG_EXTRA); if(!old) { gt_attributes_add_string(attributes,GT_ATTR_ID_TAG_EXTRA,extra_string); } else { gt_string_append_char(old,SPACE); gt_string_append_gt_string(old,extra_string); gt_string_delete(extra_string); } } void gt_template_add_mcs_tags(gt_template *template,gt_map_score_attributes *ms_attr) { uint32_t rd,mcs[2]; for(rd=0;rd<2;rd++) { gt_alignment *al=gt_template_get_block(template,rd); mcs[rd]=al?gt_alignment_get_mcs(al):0; if(ms_attr->max_strata_searched) { uint32_t limit=ms_attr->max_strata_searched+1; if(mcs[rd]>limit) mcs[rd]=limit; } } gt_add_extra_tags(template->attributes,mcs,true,ms_attr); } void gt_alignment_add_mcs_tags(gt_alignment *al,gt_map_score_attributes *ms_attr) { uint32_t mcs[2]; mcs[0]=gt_alignment_get_mcs(al); if(ms_attr->max_strata_searched) { uint32_t limit=ms_attr->max_strata_searched+1; if(mcs[0]>limit) mcs[0]=limit; } gt_add_extra_tags(al->attributes,mcs,false,ms_attr); } static int sort_dist_element(void *a,void *b) { return ((sr_dist_element *)a)->x-((sr_dist_element *)b)->x; } int estimate_insert_histogram(sr_dist_element *ins,gt_map_score_attributes *ms_attr) { uint64_t tot=0; sr_dist_element *elem; // Get interquartile range HASH_SORT(ins,sort_dist_element); for(elem=ins;elem;elem=elem->hh.next) tot+=elem->ct; uint64_t k=0,i=(tot+2)>>2; int64_t q1,q3; for(elem=ins;elem;elem=elem->hh.next) { k+=elem->ct; if(k>=i) break; } if(!elem) return GT_STATUS_FAIL; q1=elem->x; i=(tot*3+2)>>2; elem=elem->hh.next; for(;elem;elem=elem->hh.next) { k+=elem->ct; if(k>=i) break; } if(!elem) return GT_STATUS_FAIL; q3=elem->x; // Robust estimate of standard deviation from interquartile range double sd=(q3>q1)?(double)(q3-q1)/1.349:1.0; // Select bandwidth for kde (Silverman's rule of thumb) double h=exp(log(sd)+.2*log(4.0/(3.0*(double)tot))); size_t l=ms_attr->maximum_insert-ms_attr->minimum_insert+1; double *p=gt_malloc(sizeof(double)*2*l); double *cp=p+l; int *ph=gt_malloc(sizeof(int)*l); for(i=0;i<l;i++) p[i]=0.0; for(elem=ins;elem;elem=elem->hh.next) { double x=(double)elem->x; double n=(double)elem->ct; for(i=0;i<l;i++) { double d=(x-(double)(ms_attr->minimum_insert+i))/h; p[i]+=n*exp(-.5*d*d); } } double zmax=0.0,ztot=0.0; for(i=0;i<l;i++) { if(p[i]>zmax) { zmax=p[i]; k=i; } ztot+=p[i]; } cp[0]=p[0]/ztot; for(i=1;i<l;i++) cp[i]=cp[i-1]+p[i]/ztot; for(i=0;i<l;i++) { double z=p[i]/zmax; int phred=255; if(z>1.0e-26) { phred=(int)(log(z)*-10.0/log(10.0)+.5); if(phred>255) phred=255; } ph[i]=phred; } uint64_t i1=0,i2=l; for(i=k;i>0;i--) if(ph[i-1]==255) { i1=i; break; } for(i=k+1;i<l;i++) if(ph[i]==255) { i2=i-1; break; } while(i1 && i2<l && (cp[i2]-cp[i1])<.999) { for(i=i1;i>0;i--) if(ph[i-1]>255) break; if(i) { for(;i>0;i--) if(ph[i-1]==255) { i1=i; break; } } for(i=i2+1;i<l;i++) if(ph[i]>255) break; if(i<l) { for(;i<l;i++) if(ph[i]==255) { i2=i-1; break; } } } ms_attr->maximum_insert=ms_attr->minimum_insert+i2; ms_attr->minimum_insert+=i1; l=i2-i1+1; ms_attr->insert_phred=gt_malloc(l); for(i=i1,k=0;i<=i2;i++) ms_attr->insert_phred[k++]=ph[i]; // for(i=0;i<l;i++) printf("%"PRId64"\t%d\n",ms_attr->minimum_insert+i,ms_attr->ins_phred[i]); free(p); free(ph); return GT_STATUS_OK; } void read_dist_file(sr_param *param) { gt_input_file* file=gt_input_file_open(param->dist_file,false); gt_buffered_input_file* bfile=gt_buffered_input_file_new(file); gt_status nl=0; typedef enum {V1,V2,UNKNOWN} dist_file_type; dist_file_type ftype=UNKNOWN; sr_dist_element *ins_dist=NULL; do { nl=gt_buffered_input_file_get_block(bfile,0); int i; char *cur=(char *)gt_vector_get_mem(bfile->block_buffer,char); for(i=0;i<(int)nl;i++) { char *p=cur; cur=strchr(p,'\n'); assert(cur); while(*p!='\n' && isspace(*p)) p++; if(*p && *p!='n') { char *p1=p+1; while(!isspace(*p1)) p1++; if(*p1!='\n') { *(p1++)=0; while(*p1!='\n' && isspace(*p1)) p1++; if(*p1!='\n') { char *p2=p1+1; while(!isspace(*p2)) p2++; *p2=0; if(ftype==UNKNOWN) { if(!strcmp(p,"Size")) { if(!strcmp(p1,"DS_count")) ftype=V1; else if(!strcmp(p1,"Paired")) ftype=V2; } } else { if(p[1]=='=' && (p[0]=='<' || p[0]=='>')) p+=2; int ef=0; int64_t x=strtoul(p,&p2,10); if(*p2) ef=1; else { int64_t y=strtoul(p1,&p2,10); if(*p2 || y<0) ef=2; else { (void)sr_increase_insert_count(&ins_dist,x,y); } } if(ef) { fprintf(stderr,"Invalid entry in insert distribution file: %s\t%s\n",p,p1); break; } } } } } cur++; } if(i<nl) break; } while(nl); if(ftype==UNKNOWN) fprintf(stderr,"Insert distribution file format not recognized\n"); else estimate_insert_histogram(ins_dist,&param->map_score_attr); gt_scorereads_free_insert_hash(ins_dist); gt_buffered_input_file_close(bfile); gt_input_file_close(file); } gt_output_sam_attributes *gt_scorereads_setup_sam_tags(gt_sam_headers *sam_headers,sr_param *param) { // Set up optional record TAGs // Set out attributes gt_output_sam_attributes *output_sam_attributes = gt_output_sam_attributes_new(); output_sam_attributes->output_seq_qual_for_secondary_align=param->output_seq_qual_for_secondary_align; gt_output_sam_attributes_set_compact_format(output_sam_attributes,param->compact_format); gt_output_sam_attributes_set_qualities_offset(output_sam_attributes,param->map_score_attr.quality_format); gt_output_sam_attributes_set_print_mismatches(output_sam_attributes,false); gt_output_sam_attributes_set_reference_sequence_archive(output_sam_attributes,param->sequence_archive); gt_sam_attributes_add_tag_options(gt_scorereads_attribute_option_list,output_sam_attributes->sam_attributes); if(sam_headers->read_group_id_hash) { gt_sam_header_record *hr=NULL; if (param->read_group_id) { size_t* ix=gt_shash_get_element(sam_headers->read_group_id_hash,param->read_group_id); if(ix) { hr=*(gt_sam_header_record **)gt_vector_get_elm(sam_headers->read_group,*ix,gt_sam_header_record*); } else gt_error(SAM_OUTPUT_UNKNOWN_RG_ID,param->read_group_id); } else { hr=*(gt_sam_header_record **)gt_vector_get_last_elm(sam_headers->read_group,gt_sam_header_record*); } if(hr) { gt_string *id_tag=gt_sam_header_record_get_tag(hr,"ID"); if(!id_tag) gt_fatal_error(PARSE_SAM_HEADER_MISSING_TAG,"RG","ID"); // Should have been detected before, but we check again anyway gt_sam_attributes_add_tag_RG(output_sam_attributes->sam_attributes,id_tag); gt_string *lib_tag=gt_sam_header_record_get_tag(hr,"LB"); if(lib_tag) gt_sam_attributes_add_tag_LB(output_sam_attributes->sam_attributes,lib_tag); } } else if(param->read_group_id) gt_error(SAM_OUTPUT_NO_HEADER_FOR_RG); if(param->bisulfite) gt_sam_attributes_add_tag_XB(output_sam_attributes->sam_attributes); return output_sam_attributes; } void gt_scorereads_print_template(gt_vector *outputs,gt_vector *buffered_outputs,gt_template *template,gt_map_score_attributes *map_score_attr) { gt_scorereads_buffered_output *buf_out=gt_vector_get_mem(buffered_outputs,gt_scorereads_buffered_output); bool added_tags=false,calculated_mapq=false; GT_VECTOR_ITERATE(outputs,odef_p,idx,output_def*) { output_def* odef=*odef_p; gt_status print_code=GT_STATUS_OK; switch(odef->format) { case MAP: if(!added_tags) { gt_template_add_mcs_tags(template,map_score_attr); added_tags=true; } print_code=gt_output_generic_bofprint_template(buf_out->buffered_output,template,odef->printer_attr); break; case SAM: if(!calculated_mapq) { gt_map_calculate_template_mapq_score(template,map_score_attr); calculated_mapq=true; } print_code=gt_output_sam_bofprint_template(buf_out->buffered_output,template,buf_out->sam_attributes); break; case FASTA: case FASTQ: print_code=gt_output_fasta_bofprint_template(buf_out->buffered_output,template,odef->printer_attr->output_fasta_attributes); break; default: gt_fatal_error_msg("Fatal error - unsupported output format"); break; } if(print_code) { gt_error_msg("Error outputting read '"PRIgts"' in %s format\n",PRIgts_content(gt_template_get_string_tag(template)),odef->format==MAP?"MAP":"SAM"); } buf_out++; } } void gt_scorereads_print_alignment(gt_vector *outputs,gt_vector *buffered_outputs,gt_alignment *alignment,gt_map_score_attributes *map_score_attr) { gt_scorereads_buffered_output *buf_out=gt_vector_get_mem(buffered_outputs,gt_scorereads_buffered_output); GT_VECTOR_ITERATE(outputs,odef_p,idx,output_def*) { output_def* odef=*odef_p; gt_status print_code=GT_STATUS_OK; switch(odef->format) { case MAP: gt_alignment_add_mcs_tags(alignment,map_score_attr); print_code=gt_output_generic_bofprint_alignment(buf_out->buffered_output,alignment,odef->printer_attr); break; case SAM: gt_map_calculate_alignment_mapq_score(alignment,map_score_attr); print_code=gt_output_sam_bofprint_alignment(buf_out->buffered_output,alignment,buf_out->sam_attributes); break; case FASTQ: case FASTA: print_code=gt_output_fasta_bofprint_alignment(buf_out->buffered_output,alignment,odef->printer_attr->output_fasta_attributes); break; default: gt_fatal_error_msg("Fatal error - unsupported output format"); break; } if(print_code) { gt_error_msg("Error outputting read '"PRIgts"' in %s format\n",PRIgts_content(gt_alignment_get_string_tag(alignment)),odef->format==MAP?"MAP":"SAM"); } buf_out++; } } gt_vector* gt_scorereads_open_and_attach_buffered_output_files(gt_vector *outputs,gt_buffered_input_file *buffered_input,gt_sam_headers *sam_headers,sr_param *param) { GT_NULL_CHECK(outputs); GT_NULL_CHECK(buffered_input); gt_vector *output_buffers=gt_vector_new(gt_vector_get_used(outputs),sizeof(gt_scorereads_buffered_output)); GT_VECTOR_ITERATE(outputs,odef_p,idx,output_def*) { output_def* odef=*odef_p; gt_scorereads_buffered_output *buf_out=gt_vector_get_free_elm(output_buffers,gt_scorereads_buffered_output); gt_vector_inc_used(output_buffers); buf_out->buffered_output=gt_buffered_output_file_new(odef->output_file); gt_buffered_input_file_attach_buffered_output(buffered_input,buf_out->buffered_output); buf_out->sam_attributes = odef->format==SAM?gt_scorereads_setup_sam_tags(sam_headers,param):NULL; } return output_buffers; } void gt_scorereads_close_buffered_output_files(gt_vector *buffered_outputs) { GT_NULL_CHECK(buffered_outputs); GT_VECTOR_ITERATE(buffered_outputs,buf_out,idx,gt_scorereads_buffered_output) { if(buf_out->sam_attributes) gt_output_sam_attributes_delete(buf_out->sam_attributes); gt_buffered_output_file_close(buf_out->buffered_output); } } gt_sam_headers *gt_scorereads_setup_sam_headers(sr_param *param) { gt_sam_headers* sam_headers = gt_sam_header_new(); if(param->sam_header_file) { gt_input_file* const sam_headers_input_file = gt_input_file_sam_open(param->sam_header_file,false); uint64_t characters_read = 0, lines_read = 0; gt_status error_code=gt_input_file_sam_read_headers((char *)sam_headers_input_file->file_buffer,sam_headers_input_file->buffer_size,sam_headers,&characters_read,&lines_read); if(error_code) gt_error(PARSE_SAM_HEADER_NOT_SAM,sam_headers_input_file->file_name); gt_input_file_close(sam_headers_input_file); } uint64_t xx=0; gt_string *pg_id=gt_string_new(64); gt_sprintf(pg_id,"GToolsLib#%"PRIu64,++xx); gt_string *prev_id=NULL; if(sam_headers->program_id_hash) { gt_sam_header_record* hr=*(gt_sam_header_record **)gt_vector_get_last_elm(sam_headers->program,gt_sam_header_record*); prev_id=gt_sam_header_record_get_tag(hr,"ID"); do { if(!gt_shash_get_element(sam_headers->program_id_hash,gt_string_get_string(pg_id))) break; gt_sprintf(pg_id,"GToolsLib#%"PRIu64,++xx); } while(xx<10000); } if(xx<10000) { gt_sam_header_record *hr=gt_sam_header_record_new(); gt_sam_header_record_add_tag(hr,"ID",pg_id); gt_string *pn_st=gt_string_set_new(GT_SCOREREADS); gt_sam_header_record_add_tag(hr,"PN",pn_st); gt_string *vn_st=gt_string_set_new(GT_SCOREREADS_VERSION); if(prev_id) gt_sam_header_record_add_tag(hr,"PP",prev_id); gt_sam_header_record_add_tag(hr,"VN",vn_st); gt_sam_header_add_program_record(sam_headers,hr); } // Open reference file if (param->load_index) { // param->sequence_archive = gt_open_sequence_archive(param->load_index_sequences); param->sequence_archive = gt_open_sequence_archive(true); gt_sam_header_load_sequence_archive(sam_headers,param->sequence_archive); } return sam_headers; } static void alignment_strip_bisulfite_contig_names(gt_alignment *al) { GT_ALIGNMENT_CHECK(al); GT_ALIGNMENT_ITERATE(al,map) { uint64_t bis_type=GT_BIS_TYPE_NORMAL; bool bt_flag=false; bool strand_misms=false; GT_MAP_ITERATE(map,mapb) { gt_string *seq=mapb->seq_name; uint64_t l=gt_string_get_length(seq); char *p=gt_string_get_string(seq); if(l>4) { if(p[l-4]=='#' || p[l-4]=='_') { if(!strncmp(p+l-3,"C2T",3)) { gt_string_trim_right(seq,4); if(bt_flag==true) { if(bis_type!=GT_BIS_TYPE_C2T) { strand_misms=true; break; } } else { bis_type=GT_BIS_TYPE_C2T; bt_flag=true; } } else if(!strncmp(p+l-3,"G2A",3)) { gt_string_trim_right(seq,4); if(bt_flag==true) { if(bis_type!=GT_BIS_TYPE_G2A) { strand_misms=true; break; } } else { bis_type=GT_BIS_TYPE_G2A; bt_flag=true; } } else { if(bis_type!=GT_BIS_TYPE_NORMAL) { strand_misms=true; break; } bt_flag=true; } } } } if(strand_misms==true) bis_type=GT_BIS_TYPE_MISMATCH; gt_attributes *attr=map->attributes; if(attr==NULL) map->attributes=attr=gt_attributes_new(); gt_attributes_add(attr,GT_ATTR_ID_BIS_TYPE,&bis_type,uint64_t); } } static void template_strip_bisulfite_contig_names(gt_template *tp) { int j; for(j=0;j<2;j++) { gt_alignment *al=gt_template_get_block(tp,j); if(al) alignment_strip_bisulfite_contig_names(al); } } gt_status gt_scorereads_process(sr_param *param) { gt_status err=GT_STATUS_OK; gt_sam_headers* sam_headers = NULL; // SAM headers // Open output file(s) GT_VECTOR_ITERATE(param->outputs,odef_p,idx,output_def*) { output_def* odef = *odef_p; odef->output_file=odef->name?gt_output_file_new_compress(gt_string_get_string(odef->name),UNSORTED_FILE,param->compress): gt_output_stream_new_compress(stdout,UNSORTED_FILE,param->compress); gt_cond_fatal_error(!odef->output_file,FILE_OPEN,odef->name?gt_string_get_string(odef->name):"<STDOUT>"); switch(odef->format) { case MAP: odef->printer_attr=gt_generic_printer_attributes_new(MAP); odef->printer_attr->output_map_attributes->print_casava=true; odef->printer_attr->output_map_attributes->print_extra=true; odef->printer_attr->output_map_attributes->print_scores=true; odef->printer_attr->output_map_attributes->hex_print_scores=true; break; case FASTA: case FASTQ: odef->printer_attr=gt_generic_printer_attributes_new(odef->format); break; case SAM: if(sam_headers == NULL) sam_headers=gt_scorereads_setup_sam_headers(param); // Print SAM headers gt_output_sam_ofprint_headers_sh(odef->output_file,sam_headers); break; default: gt_fatal_error_msg("Fatal error - unsupported output format"); break; } } // Do we have two map files as input (one for each read)? if(param->input_files[1]) { pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; gt_input_file* input_file1=gt_input_file_map_open(param->input_files[0],param->mmap_input); gt_input_file* input_file2=gt_input_file_map_open(param->input_files[1],param->mmap_input); if(input_file1->file_format!=MAP || input_file2->file_format!=MAP) { gt_fatal_error_msg("Fatal error: paired files '%s','%s' are not in MAP format\n",param->input_files[0],param->input_files[1]); } gt_buffered_input_file* buffered_input_a=gt_buffered_input_file_new(input_file1); gt_buffered_input_file* buffered_input_b=gt_buffered_input_file_new(input_file2); // If no insert size file supplied, estimate from the first GT_SCOREREADS_NUM_LINES records if(!param->map_score_attr.insert_phred) { uint64_t nread=0; gt_template *template=gt_template_new(); sr_dist_element *ins_dist=NULL; gt_status error_code; while((error_code=gt_input_map_parser_synch_get_template(buffered_input_a,buffered_input_b,template,&mutex))) { if(error_code!=GT_IMP_OK) continue; int64_t size; error_code=gt_scorereads_get_insert_size(template,&size); if(error_code==GT_STATUS_OK) (void)sr_increase_insert_count(&ins_dist,size,1); if(++nread==GT_SCOREREADS_NUM_LINES) break; } gt_template_delete(template); // Reset input buffers to the beginning of the file buffered_input_a->cursor=gt_vector_get_mem(buffered_input_a->block_buffer,char); buffered_input_a->current_line_num=0; buffered_input_b->cursor=gt_vector_get_mem(buffered_input_b->block_buffer,char); buffered_input_b->current_line_num=0; (void)estimate_insert_histogram(ins_dist,&param->map_score_attr); gt_scorereads_free_insert_hash(ins_dist); } #ifdef HAVE_OPENMP #pragma omp parallel num_threads(param->num_threads) #endif { #ifdef HAVE_OPENMP uint64_t tid=omp_get_thread_num(); #else uint64_t tid=0; #endif gt_buffered_input_file* buffered_input1=tid?gt_buffered_input_file_new(input_file1):buffered_input_a; gt_buffered_input_file* buffered_input2=tid?gt_buffered_input_file_new(input_file2):buffered_input_b; gt_vector *buffered_outputs=gt_scorereads_open_and_attach_buffered_output_files(param->outputs,buffered_input1,sam_headers,param); gt_map_score_tmap_buf *ms_tmap_buf=gt_map_score_new_map_score_tmap_buf(GT_MAX(param->map_score_attr.max_pair_maps,param->map_score_attr.max_orphan_maps)); gt_status error_code; gt_template *template=gt_template_new(); while((error_code=gt_input_map_parser_synch_get_template(buffered_input1,buffered_input2,template,&mutex))) { if(error_code!=GT_IMP_OK) continue; if(param->bisulfite) template_strip_bisulfite_contig_names(template); gt_map_pair_template(template,&param->map_score_attr,ms_tmap_buf); if(param->realign) gt_template_realign_levenshtein(template,param->sequence_archive); gt_scorereads_print_template(param->outputs,buffered_outputs,template,&param->map_score_attr); } gt_template_delete(template); gt_map_score_delete_map_score_tmap_buf(ms_tmap_buf); gt_buffered_input_file_close(buffered_input1); gt_buffered_input_file_close(buffered_input2); gt_scorereads_close_buffered_output_files(buffered_outputs); } gt_input_file_close(input_file1); gt_input_file_close(input_file2); } else { // Single input file gt_input_file* input_file=param->input_files[0]?gt_input_file_map_open(param->input_files[0],param->mmap_input):gt_input_stream_map_open(stdin); gt_buffered_input_file* buffered_input_a=gt_buffered_input_file_new(input_file); gt_map_parser_attributes* input_map_attributes_a = gt_input_map_parser_attributes_new(param->is_paired); if(param->is_paired) { /* * Paired input * * If no insert size file supplied, estimate from the first GT_SCOREREADS_NUM_LINES records * */ if(!param->map_score_attr.insert_phred) { uint64_t nread=0; gt_template *template=gt_template_new(); sr_dist_element *ins_dist=NULL; gt_status error_code; while ((error_code=gt_input_map_parser_get_template(buffered_input_a,template,input_map_attributes_a))) { if(error_code!=GT_IMP_OK) continue; int64_t size; error_code=gt_scorereads_get_insert_size(template,&size); if(error_code==GT_STATUS_OK) (void)sr_increase_insert_count(&ins_dist,size,1); if(++nread==GT_SCOREREADS_NUM_LINES) break; } gt_template_delete(template); // Reset input buffers to the beginning of the file buffered_input_a->cursor=gt_vector_get_mem(buffered_input_a->block_buffer,char); buffered_input_a->current_line_num=0; (void)estimate_insert_histogram(ins_dist,&param->map_score_attr); gt_scorereads_free_insert_hash(ins_dist); } #ifdef HAVE_OPENMP #pragma omp parallel num_threads(param->num_threads) #endif { #ifdef HAVE_OPENMP uint64_t tid=omp_get_thread_num(); #else uint64_t tid=0; #endif gt_buffered_input_file* buffered_input=tid?gt_buffered_input_file_new(input_file):buffered_input_a; gt_vector *buffered_outputs=gt_scorereads_open_and_attach_buffered_output_files(param->outputs,buffered_input,sam_headers,param); gt_map_parser_attributes* input_map_attributes=tid?gt_input_map_parser_attributes_new(param->is_paired):input_map_attributes_a; gt_output_sam_attributes* const output_sam_attributes = param->output_format==SAM?gt_scorereads_setup_sam_tags(sam_headers,param):NULL; gt_map_score_tmap_buf *ms_tmap_buf=gt_map_score_new_map_score_tmap_buf(GT_MAX(param->map_score_attr.max_pair_maps,param->map_score_attr.max_orphan_maps)); gt_status error_code; gt_template *template=gt_template_new(); while ((error_code=gt_input_map_parser_get_template(buffered_input,template,input_map_attributes))) { if (error_code!=GT_IMP_OK) continue; if(param->bisulfite) template_strip_bisulfite_contig_names(template); gt_map_pair_template(template,&param->map_score_attr,ms_tmap_buf); if(param->realign) gt_template_realign_levenshtein(template,param->sequence_archive); gt_scorereads_print_template(param->outputs,buffered_outputs,template,&param->map_score_attr); } // Clean gt_template_delete(template); gt_map_score_delete_map_score_tmap_buf(ms_tmap_buf); gt_input_map_parser_attributes_delete(input_map_attributes); if(output_sam_attributes) gt_output_sam_attributes_delete(output_sam_attributes); gt_buffered_input_file_close(buffered_input); gt_scorereads_close_buffered_output_files(buffered_outputs); } } else { /* * Single end reads */ #ifdef HAVE_OPENMP #pragma omp parallel num_threads(param->num_threads) #endif { #ifdef HAVE_OPENMP uint64_t tid=omp_get_thread_num(); #else uint64_t tid=0; #endif gt_buffered_input_file* buffered_input=tid?gt_buffered_input_file_new(input_file):buffered_input_a; gt_vector *buffered_outputs=gt_scorereads_open_and_attach_buffered_output_files(param->outputs,buffered_input,sam_headers,param); gt_map_parser_attributes* input_map_attributes=tid?gt_input_map_parser_attributes_new(false):input_map_attributes_a; gt_status error_code; gt_template *template=gt_template_new(); while ((error_code=gt_input_map_parser_get_template(buffered_input,template,input_map_attributes))) { if (error_code!=GT_IMP_OK) { gt_error_msg("Error parsing file '%s'\n",param->input_files[0]); continue; } gt_alignment *alignment=gt_template_get_block(template,0); GT_ALIGNMENT_ITERATE(alignment,map) { if(map->gt_score==GT_MAP_NO_GT_SCORE) map->gt_score=gt_map_calculate_gt_score(alignment,map,&param->map_score_attr); map->phred_score=255; } if(param->bisulfite) alignment_strip_bisulfite_contig_names(alignment); if(param->realign) gt_alignment_realign_levenshtein(alignment,param->sequence_archive); gt_scorereads_print_alignment(param->outputs,buffered_outputs,alignment,&param->map_score_attr); } // Clean gt_template_delete(template); gt_input_map_parser_attributes_delete(input_map_attributes); gt_buffered_input_file_close(buffered_input); gt_scorereads_close_buffered_output_files(buffered_outputs); } } gt_input_file_close(input_file); } GT_VECTOR_ITERATE(param->outputs,odef_p1,idx1,output_def*) { output_def* odef = *odef_p1; gt_output_file_close(odef->output_file); if(odef->format==MAP) gt_generic_printer_attributes_delete(odef->printer_attr); } if(param->map_score_attr.insert_phred) free(param->map_score_attr.insert_phred); return err; } output_def *gt_scorereads_new_output_def(char *name,gt_file_format format,gt_scorereads_filter filter) { output_def *od=gt_alloc(output_def); if(name==NULL || !strcmp(name,"-")) od->name=NULL; else od->name=gt_string_set_new(name); od->format=format; od->filter=filter; od->output_file=NULL; od->printer_attr=NULL; return od; } char *gt_scorereads_parse_output_option(char *opt) { char *format_st[]={"MAP","FASTA","SAM","FASTQ",0}; gt_file_format formats[]={MAP,FASTA,SAM,FASTQ}; char *filter_st[]={"ALL","UNMAPPED","POORLY-MAPPED","DISCORDANT","TRIM-MAPS","ONE-END-ANCHORED",0}; gt_scorereads_filter filters[]={all,unmapped,poorly_mapped,discordant,trim_maps,one_end_anchored}; char *p=strchr(opt,','); while(p) { p++; int idx=0; while(format_st[idx] && strncasecmp(p,format_st[idx],strlen(format_st[idx]))) idx++; if(format_st[idx]) { char *p1=p+strlen(format_st[idx]); gt_file_format format=formats[idx]; if(*p1==',') { idx=0; p1++; while(filter_st[idx] && strncasecmp(p1,filter_st[idx],strlen(filter_st[idx]))) idx++; if(filter_st[idx]) { p1+=strlen(format_st[idx]); if(!*p1) { size_t sz=p-opt; char *nm=gt_malloc(sz); strncpy(nm,opt,sz-1); nm[sz-1]=0; gt_vector_insert(param.outputs,gt_scorereads_new_output_def(nm,format,filters[idx]),output_def*); return NULL; } } } else if(!*p1) { size_t sz=p-opt; char *nm=NULL; if(sz!=2 || *opt!='-') { nm=gt_malloc(sz); strncpy(nm,opt,sz-1); nm[sz-1]=0; } gt_vector_insert(param.outputs,gt_scorereads_new_output_def(nm,format,all),output_def*); return NULL; } else p=strchr(p,','); } } return opt; } gt_status parse_arguments(int argc,char** argv) { gt_status err=GT_STATUS_OK; struct option* gt_scorereads_getopt = gt_options_adaptor_getopt(gt_scorereads_options); gt_string* const gt_scorereads_short_getopt = gt_options_adaptor_getopt_short(gt_scorereads_options); int option, option_index; char *p,*output_file=NULL; gt_file_format output_format=GT_SCOREREADS_DEFAULT_OUTPUT_FORMAT; param.outputs=gt_vector_new(2,sizeof(output_def *)); int insert_set[2]={0,0}; while (true) { // Get option & Select case if ((option=getopt_long(argc,argv, gt_string_get_string(gt_scorereads_short_getopt),gt_scorereads_getopt,&option_index))==-1) break; switch (option) { /* I/O */ case 303: param.dist_file = optarg; break; case 'o': output_file = gt_scorereads_parse_output_option(optarg); break; case 'b': param.bisulfite=true; // Intentional fall through case 'R': param.realign=true; break; case 'r': param.name_reference_file = optarg; param.load_index = true; break; case 'I': param.name_gem_index_file = optarg; param.load_index = true; break; case 's': param.sam_header_file = optarg; break; case 300: param.input_files[0] = optarg; break; case 301: param.input_files[1] = optarg; break; case 'p': param.is_paired=true; break; case 'z': #ifdef HAVE_ZLIB param.compress=GZIP; #endif break; case 'j': #ifdef HAVE_BZLIB param.compress=BZIP2; #endif break; case 'Z': param.compress=NONE; break; /* Score function */ case 'q': if (gt_streq(optarg,"offset-64")) { param.map_score_attr.quality_format=GT_QUALS_OFFSET_64; } else if (gt_streq(optarg,"offset-33")) { param.map_score_attr.quality_format=GT_QUALS_OFFSET_33; } else { gt_fatal_error_msg("Quality format not recognized: '%s'",optarg); } break; case 704: // output-format if (gt_streq(optarg,"MAP")) { output_format = MAP; } else if (gt_streq(optarg,"SAM")) { output_format = SAM; } else if (gt_streq(optarg,"FASTA")) { output_format = FASTA; } else if (gt_streq(optarg,"FASTQ")) { output_format = FASTQ; } else { gt_fatal_error_msg("Output format '%s' not recognized",optarg); } break; case 401: param.map_score_attr.minimum_insert=(int)strtol(optarg,&p,10); if(*p || param.map_score_attr.minimum_insert<0) { fprintf(stderr,"Illegal minimum insert size: '%s'\n",optarg); err=-7; } else insert_set[0]=1; break; case 402: param.map_score_attr.maximum_insert=(int)strtol(optarg,&p,10); if(*p || param.map_score_attr.maximum_insert<0) { fprintf(stderr,"Illegal maximum insert size: '%s'\n",optarg); err=-7; } else insert_set[1]=1; break; case 403: param.map_score_attr.indel_penalty=(int)strtol(optarg,&p,10); if(*p || param.map_score_attr.indel_penalty<0) { fprintf(stderr,"Illegal indel penalty: '%s'\n",optarg); err=-7; } break; case 404: param.map_score_attr.max_pair_maps=strtoul(optarg,&p,10); if(*p) { fprintf(stderr,"Illegal max pair maps value: '%s'\n",optarg); err=-7; } break; case 405: param.map_score_attr.max_orphan_maps=strtoul(optarg,&p,10); if(*p) { fprintf(stderr,"Illegal max orphan maps value: '%s'\n",optarg); err=-7; } break; case 500: if(gt_sam_attributes_parse_tag_option_string(gt_scorereads_attribute_option_list,optarg)!=GT_STATUS_OK) { fprintf(stderr,"Unable to parse --tag option '%s'\n",optarg); err=-8; } break; case 'S': param.map_score_attr.split_penalty=(int)strtol(optarg,&p,10); if(*p || param.map_score_attr.split_penalty<0) { fprintf(stderr,"Illegal split penalty score: '%s'\n",optarg); err=-7; } break; case 'M': param.map_score_attr.mapping_cutoff=strtoul(optarg,&p,10); if(*p) { fprintf(stderr,"Illegal mapping cutoff: '%s'\n",optarg); err=-7; } break; case 'm': param.map_score_attr.max_strata_searched=strtoul(optarg,&p,10); if(*p) { fprintf(stderr,"Illegal mismatch limit: '%s'\n",optarg); err=-7; } break; /* Headers */ case 600: // Read-group ID param.read_group_id = optarg; break; /* Format */ case 'c': param.compact_format = true; break; case 700: param.output_seq_qual_for_secondary_align = true; break; /* Misc */ case 'v': param.verbose = true; break; case 't': #ifdef HAVE_OPENMP param.num_threads = atol(optarg); #endif break; case 'h': usage(gt_scorereads_options,gt_scorereads_groups,false); exit(1); break; case 'H': usage(gt_scorereads_options,gt_scorereads_groups,true); exit(1); case 'J': gt_options_fprint_json_menu(stderr,gt_scorereads_options,gt_scorereads_groups,true,false); exit(1); break; case '?': default: usage(gt_scorereads_options,gt_scorereads_groups,false); gt_fatal_error_msg("Option '%c' %d not recognized",option,option); break; } } /* * Parameters check */ if(param.input_files[1] && param.input_files[0]==NULL) { param.input_files[0]=param.input_files[1]; param.input_files[1]=NULL; } if(param.input_files[1]) param.is_paired=true; if(err==GT_STATUS_OK && insert_set[0] && insert_set[1] && param.map_score_attr.minimum_insert>param.map_score_attr.maximum_insert) { fputs("Minimum insert size > maximum insert size\n",stderr); usage(gt_scorereads_options,gt_scorereads_groups,false); err=-15; } else if(param.realign) { if(!param.load_index) { fputs("Index or reference must be supplied for realign or bisulfite option\n",stderr); usage(gt_scorereads_options,gt_scorereads_groups,false); err=-16; } else { param.load_index_sequences=true; } } if(err==GT_STATUS_OK) { // Create output_def for normal (non specified) output using specified format. If no output command at all specified, create a stdout stream if(output_file!=NULL || !gt_vector_get_used(param.outputs)) gt_vector_insert(param.outputs,gt_scorereads_new_output_def(output_file,output_format,all),output_def*); bool use_stdout=false; GT_VECTOR_ITERATE(param.outputs,odef_p,idx,output_def*) { gt_string *com; if((com=(*odef_p)->name)) { uint64_t l=gt_string_get_length(com); switch(param.compress) { case GZIP: if(l<3 || strcmp(gt_string_get_string(com)+l-3,".gz")) gt_string_append_string(com,".gz",3); break; case BZIP2: if(l<4 || strcmp(gt_string_get_string(com)+l-4,".bz2")) gt_string_append_string(com,".bz2",4); break; default: break; } } else { if(use_stdout) { gt_error_msg("Error in output definitions: multiple outputs to stdout stream defined\n"); err=GT_STATUS_FAIL; } else use_stdout=true; } } if(!insert_set[1]) { if(param.map_score_attr.minimum_insert<=1000) param.map_score_attr.maximum_insert=1000; else param.map_score_attr.maximum_insert=param.map_score_attr.minimum_insert+1000; } if(param.is_paired && param.dist_file) read_dist_file(&param); } // Free gt_string_delete(gt_scorereads_short_getopt); return err; } int main(int argc,char *argv[]) { gt_status err=0; // GT error handler gt_handle_error_signals(); // Parsing command-line options err=parse_arguments(argc,argv); if(err==GT_STATUS_OK) err=gt_scorereads_process(&param); return err=GT_STATUS_OK?0:-1; }
kmp_set_dispatch_buf.c
// RUN: %libomp-compile && env KMP_DISP_NUM_BUFFERS=0 %libomp-run // RUN: env KMP_DISP_NUM_BUFFERS=1 %libomp-run && env KMP_DISP_NUM_BUFFERS=3 %libomp-run // RUN: env KMP_DISP_NUM_BUFFERS=4 %libomp-run && env KMP_DISP_NUM_BUFFERS=7 %libomp-run // RUN: %libomp-compile -DMY_SCHEDULE=guided && env KMP_DISP_NUM_BUFFERS=1 %libomp-run // RUN: env KMP_DISP_NUM_BUFFERS=3 %libomp-run && env KMP_DISP_NUM_BUFFERS=4 %libomp-run // RUN: env KMP_DISP_NUM_BUFFERS=7 %libomp-run #include <stdio.h> #include <omp.h> #include <stdlib.h> #include <limits.h> #include "omp_testsuite.h" #define INCR 7 #define MY_MAX 200 #define MY_MIN -200 #define NUM_LOOPS 100 #ifndef MY_SCHEDULE # define MY_SCHEDULE dynamic #endif int a, b, a_known_value, b_known_value; int test_kmp_set_disp_num_buffers() { int success = 1; a = 0; b = 0; // run many small dynamic loops to stress the dispatch buffer system #pragma omp parallel { int i,j; for (j = 0; j < NUM_LOOPS; j++) { #pragma omp for schedule(MY_SCHEDULE) nowait for (i = MY_MIN; i < MY_MAX; i+=INCR) { #pragma omp atomic a++; } #pragma omp for schedule(MY_SCHEDULE) nowait for (i = MY_MAX; i >= MY_MIN; i-=INCR) { #pragma omp atomic b++; } } } // detect failure if (a != a_known_value || b != b_known_value) { success = 0; printf("a = %d (should be %d), b = %d (should be %d)\n", a, a_known_value, b, b_known_value); } return success; } int main(int argc, char** argv) { int i,j; int num_failed=0; // figure out the known values to compare with calculated result a_known_value = 0; b_known_value = 0; for (j = 0; j < NUM_LOOPS; j++) { for (i = MY_MIN; i < MY_MAX; i+=INCR) a_known_value++; for (i = MY_MAX; i >= MY_MIN; i-=INCR) b_known_value++; } for(i = 0; i < REPETITIONS; i++) { if(!test_kmp_set_disp_num_buffers()) { num_failed++; } } return num_failed; }
GB_unop__conj_fc32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__conj_fc32_fc32 // op(A') function: GB_unop_tran__conj_fc32_fc32 // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = conjf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = conjf (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = aij ; \ Cx [pC] = conjf (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_CONJ || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__conj_fc32_fc32 ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = conjf (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = conjf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__conj_fc32_fc32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ZBinDumper_MPI.h
/* * ZBinDumper_MPI.h * Cubism * * Created by Panos Hadjidoukas on 3/20/14. * Copyright 2014 CSE Lab, ETH Zurich. All rights reserved. * */ #pragma once #include <iostream> #include <cstdio> #include <vector> #include <string> #include <cassert> #include <sstream> #include "BlockInfo.h" #include "LosslessCompression.h" CUBISM_NAMESPACE_BEGIN #define MAX_MPI_PROCS (16*1024) // header: 0.25MB* 8 typedef struct _header { long offset[8]; // 1 for single compression, NCHANNELS otherwise long size[8]; } header; // The following requirements for the data TStreamer are required: // TStreamer::NCHANNELS : Number of data elements (1=Scalar, 3=Vector, 9=Tensor) // TStreamer::operate : Data access methods for read and write // TStreamer::getAttributeName : Attribute name of the date ("Scalar", "Vector", "Tensor") template<typename TStreamer, typename TGrid> void DumpZBin_MPI( const TGrid &grid, const int iCounter, const typename TGrid::Real t, const std::string &f_name, const std::string &dump_path = ".", const bool bDummy = false) { typedef typename TGrid::BlockType B; int rank, nranks; // f_name is the base filename without file type extension std::ostringstream filename; filename << dump_path << "/" << f_name; MPI_Status status; MPI_File file_id; MPI_Comm comm = grid.getCartComm(); MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &nranks); int coords[3]; grid.peindex(coords); const unsigned int NX = grid.getResidentBlocksPerDimension(0)*B::sizeX; const unsigned int NY = grid.getResidentBlocksPerDimension(1)*B::sizeY; const unsigned int NZ = grid.getResidentBlocksPerDimension(2)*B::sizeZ; static const unsigned int NCHANNELS = TStreamer::NCHANNELS; if (rank==0) { //Real memsize = (NX * NY * NZ * NCHANNELS * sizeof(Real))/(1024.*1024.*1024.); Real memsize = (NX * NY * NZ * sizeof(Real))/(1024.*1024.*1024.); std::cout << "Allocating " << memsize << " GB of BIN data per rank (" << memsize*nranks << " GB in total)" << std::endl; } // Real * array_all = new Real[NX * NY * NZ * NCHANNELS]; Real * array_all = new Real[NX * NY * NZ]; std::vector<BlockInfo> vInfo_local = grid.getResidentBlocksInfo(); static const unsigned int sX = 0; static const unsigned int sY = 0; static const unsigned int sZ = 0; static const unsigned int eX = B::sizeX; static const unsigned int eY = B::sizeY; static const unsigned int eZ = B::sizeZ; int rc = MPI_File_open( MPI_COMM_SELF, const_cast<char*>( (filename.str()+".zbin").c_str() ), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file_id ); if (rc) { printf("Unable to create ZBIN file\n"); exit(1); } long previous_offset = 0; header tag; // moved here for (unsigned int ichannel = 0; ichannel < NCHANNELS; ichannel++) { #pragma omp parallel for for(unsigned int i=0; i<vInfo_local.size(); i++) { BlockInfo& info = vInfo_local[i]; const unsigned int idx[3] = {info.index[0], info.index[1], info.index[2]}; B & b = *(B*)info.ptrBlock; for(unsigned int ix=sX; ix<eX; ix++) { const unsigned int gx = idx[0]*B::sizeX + ix; for(unsigned int iy=sY; iy<eY; iy++) { const unsigned int gy = idx[1]*B::sizeY + iy; for(unsigned int iz=sZ; iz<eZ; iz++) { const unsigned int gz = idx[2]*B::sizeZ + iz; assert((gz + NZ * (gy + NY * gx)) < NX * NY * NZ); Real * const ptr = array_all + (gz + NZ * (gy + NY * gx)); Real output; TStreamer::operate(b, ix, iy, iz, &output, ichannel); // point -> output, ptr[0] = output; } } } } // long local_count = NX * NY * NZ * NCHANNELS; long local_count = NX * NY * NZ * 1; long local_bytes = local_count * sizeof(Real); long offset; // global offset unsigned int max = local_bytes; // int layout[4] = {NCHANNELS, NX, NY, NZ}; int layout[4] = {NX, NY, NZ, 1}; long compressed_bytes = ZZcompress<typename TGrid::Real>((unsigned char *)array_all, local_bytes, layout, &max); // "in place" #if DBG printf("Writing %ld bytes of Compressed data (cr = %.2f)\n", compressed_bytes, local_bytes*1.0/compressed_bytes); #endif MPI_Exscan( &compressed_bytes, &offset, 1, MPI_LONG, MPI_SUM, comm); if (rank == 0) offset = 0; #if DBG printf("rank %d, offset = %ld, size = %ld\n", rank, offset, compressed_bytes); fflush(0); #endif // header tag; tag.offset[ichannel] = offset + previous_offset; tag.size[ichannel] = compressed_bytes; #if DBG printf("rank %d, offset = %ld, size = %ld\n", rank, tag.offset[ichannel], tag.size[ichannel]); fflush(0); #endif previous_offset = (tag.offset[ichannel] + tag.size[ichannel]); MPI_Bcast(&previous_offset, 1, MPI_LONG, nranks-1, comm); long base = MAX_MPI_PROCS*sizeof(tag); // full Header MPI_File_write_at(file_id, base + tag.offset[ichannel], (char *)array_all, tag.size[ichannel], MPI_CHAR, &status); } /* ichannel */ MPI_File_write_at(file_id, rank*sizeof(tag), &tag, 2*8, MPI_LONG, &status); MPI_File_close(&file_id); delete [] array_all; } template<typename TStreamer, typename TGrid> void ReadZBin_MPI(TGrid &grid, const std::string& f_name, const std::string& read_path=".") { typedef typename TGrid::BlockType B; int rank, nranks; // f_name is the base filename without file type extension std::ostringstream filename; filename << read_path << "/" << f_name; MPI_Status status; MPI_File file_id; MPI_Comm comm = grid.getCartComm(); MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &nranks); int coords[3]; grid.peindex(coords); const int NX = grid.getResidentBlocksPerDimension(0)*B::sizeX; const int NY = grid.getResidentBlocksPerDimension(1)*B::sizeY; const int NZ = grid.getResidentBlocksPerDimension(2)*B::sizeZ; static const int NCHANNELS = TStreamer::NCHANNELS; Real * array_all = new Real[NX * NY * NZ * NCHANNELS]; std::vector<BlockInfo> vInfo_local = grid.getResidentBlocksInfo(); static const int sX = 0; static const int sY = 0; static const int sZ = 0; const int eX = B::sizeX; const int eY = B::sizeY; const int eZ = B::sizeZ; int rc = MPI_File_open( MPI_COMM_SELF, const_cast<char*>( (filename.str()+".zbin").c_str() ), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_id ); if (rc) { printf("Unable to read ZBIN file\n"); exit(1); } // long local_count = NX * NY * NZ * NCHANNELS; long local_count = NX * NY * NZ * 1; long local_bytes = local_count * sizeof(Real); long offset; header tag; MPI_File_read_at(file_id, rank*sizeof(tag), &tag, 2*8, MPI_LONG, &status); #if DBG printf("HEADER(%d):\n", rank); for (int i = 0; i < NCHANNELS; i++) { printf("channel %d: %ld %ld\n", i, tag.offset[i], tag.size[i]); } #endif for (unsigned int ichannel = 0; ichannel < NCHANNELS; ichannel++) { //MPI_File_read_at(file_id, (rank*2+0)*sizeof(long), &offset , 1, MPI_LONG, &status); //MPI_File_read_at(file_id, (rank*2+1)*sizeof(long), &compressed_bytes, 1, MPI_LONG, &status); #if DBG printf("rank %d, offset = %ld, compr. size = %ld\n", rank, tag.offset[ichannel], tag.size[ichannel]); fflush(0); #endif long compressed_bytes = tag.size[ichannel]; #if DBG printf("Reading %ld bytes of Compressed data (cr = %.2f)\n", compressed_bytes, local_bytes*1.0/compressed_bytes); #endif unsigned char *tmp = (unsigned char *) malloc(compressed_bytes+4096); long base = MAX_MPI_PROCS*sizeof(tag); // Header MPI_File_read_at(file_id, base + tag.offset[ichannel], (char *)tmp, compressed_bytes, MPI_CHAR, &status); // int layout[4] = {NCHANNELS, NX, NY, NZ}; int layout[4] = {NX, NY, NZ, 1}; size_t decompressed_bytes = ZZdecompress<typename TGrid::Real>(tmp, compressed_bytes, layout, (unsigned char *)array_all, local_bytes); free(tmp); #if DBG printf("rank %d, offset = %ld, size = %ld (%ld)\n", rank, offset, decompressed_bytes, local_bytes); fflush(0); #endif #pragma omp parallel for for(int i=0; i<vInfo_local.size(); i++) { BlockInfo& info = vInfo_local[i]; const int idx[3] = {info.index[0], info.index[1], info.index[2]}; B & b = *(B*)info.ptrBlock; for(int ix=sX; ix<eX; ix++) for(int iy=sY; iy<eY; iy++) for(int iz=sZ; iz<eZ; iz++) { const int gx = idx[0]*B::sizeX + ix; const int gy = idx[1]*B::sizeY + iy; const int gz = idx[2]*B::sizeZ + iz; //Real * const ptr_input = array_all + NCHANNELS*(gz + NZ * (gy + NY * gx)); Real * const ptr_input = array_all + (gz + NZ * (gy + NY * gx)); TStreamer::operate(b, *ptr_input, ix, iy, iz, ichannel); // output -> point } } } /* ichannel */ MPI_File_close(&file_id); delete [] array_all; } CUBISM_NAMESPACE_END
lastprivate-clause.c
/* gcc -fopenmp -O2 lastprivate-clause.c -o lastprivate-clause */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif main() { int i, n = 7; int a[n], v; for (i=0; i<n; i++) a[i] = i+1; // asigna el valor de la variable que estamos haciendo privada y tras el parallel SÍ conserva el valor que tenga al salir del parallel #pragma omp parallel for lastprivate(v) for (i=0; i<n; i++){ v = a[i]; printf("thread %d v=%d / ", omp_get_thread_num(), v); } printf("\nFuera de la construcción'parallel for' v=%d\n", v); }
GB_unop__ainv_fc32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef 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__ainv_fc32_fc32) // op(A') function: GB (_unop_tran__ainv_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = GB_FC32_ainv (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_FC32_ainv (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = aij ; \ Cx [pC] = GB_FC32_ainv (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__ainv_fc32_fc32) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = GB_FC32_ainv (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = GB_FC32_ainv (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__ainv_fc32_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 8; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; 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 ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #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(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
search.h
// -*- C++ -*- // Copyright (C) 2007, 2008 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) any later // version. // This 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 // General Public License for more details. // You should have received a copy of the GNU General Public License // along with this library; see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA. // As a special exception, you may use this file as part of a free // software library without restriction. Specifically, if other files // instantiate templates or use macros or inline functions from this // file, or you compile this file and link it with other files to // produce an executable, this file does not by itself cause the // resulting executable to be covered by the GNU General Public // License. This exception does not however invalidate any other // reasons why the executable file might be covered by the GNU General // Public License. /** @file parallel/search.h * @brief Parallel implementation base for std::search() and * std::search_n(). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_SEARCH_H #define _GLIBCXX_PARALLEL_SEARCH_H 1 #include <bits/stl_algobase.h> #include <parallel/parallel.h> #include <parallel/equally_split.h> namespace __gnu_parallel { /** * @brief Precalculate advances for Knuth-Morris-Pratt algorithm. * @param elements Begin iterator of sequence to search for. * @param length Length of sequence to search for. * @param advances Returned offsets. */ template<typename RandomAccessIterator, typename _DifferenceTp> void calc_borders(RandomAccessIterator elements, _DifferenceTp length, _DifferenceTp* off) { typedef _DifferenceTp difference_type; off[0] = -1; if (length > 1) off[1] = 0; difference_type k = 0; for (difference_type j = 2; j <= length; j++) { while ((k >= 0) && !(elements[k] == elements[j-1])) k = off[k]; off[j] = ++k; } } // Generic parallel find algorithm (requires random access iterator). /** @brief Parallel std::search. * @param begin1 Begin iterator of first sequence. * @param end1 End iterator of first sequence. * @param begin2 Begin iterator of second sequence. * @param end2 End iterator of second sequence. * @param pred Find predicate. * @return Place of finding in first sequences. */ template<typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename Pred> _RandomAccessIterator1 search_template(_RandomAccessIterator1 begin1, _RandomAccessIterator1 end1, _RandomAccessIterator2 begin2, _RandomAccessIterator2 end2, Pred pred) { typedef std::iterator_traits<_RandomAccessIterator1> traits_type; typedef typename traits_type::difference_type difference_type; _GLIBCXX_CALL((end1 - begin1) + (end2 - begin2)); difference_type pattern_length = end2 - begin2; // Pattern too short. if(pattern_length <= 0) return end1; // Last point to start search. difference_type input_length = (end1 - begin1) - pattern_length; // Where is first occurrence of pattern? defaults to end. difference_type result = (end1 - begin1); difference_type *splitters; // Pattern too long. if (input_length < 0) return end1; omp_lock_t result_lock; omp_init_lock(&result_lock); thread_index_t num_threads = std::max<difference_type>(1, std::min<difference_type>(input_length, get_max_threads())); difference_type advances[pattern_length]; calc_borders(begin2, pattern_length, advances); # pragma omp parallel num_threads(num_threads) { # pragma omp single { num_threads = omp_get_num_threads(); splitters = new difference_type[num_threads + 1]; equally_split(input_length, num_threads, splitters); } thread_index_t iam = omp_get_thread_num(); difference_type start = splitters[iam], stop = splitters[iam + 1]; difference_type pos_in_pattern = 0; bool found_pattern = false; while (start <= stop && !found_pattern) { // Get new value of result. #pragma omp flush(result) // No chance for this thread to find first occurrence. if (result < start) break; while (pred(begin1[start + pos_in_pattern], begin2[pos_in_pattern])) { ++pos_in_pattern; if (pos_in_pattern == pattern_length) { // Found new candidate for result. omp_set_lock(&result_lock); result = std::min(result, start); omp_unset_lock(&result_lock); found_pattern = true; break; } } // Make safe jump. start += (pos_in_pattern - advances[pos_in_pattern]); pos_in_pattern = (advances[pos_in_pattern] < 0) ? 0 : advances[pos_in_pattern]; } } //parallel omp_destroy_lock(&result_lock); delete[] splitters; // Return iterator on found element. return (begin1 + result); } } // end namespace #endif
oskar_imager_rotate_vis.c
/* * Copyright (c) 2016-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "math/oskar_cmath.h" #include "imager/private_imager.h" #include "imager/oskar_imager.h" #include <stddef.h> #ifdef __cplusplus extern "C" { #endif void oskar_imager_rotate_vis(const oskar_Imager* h, size_t num_vis, const oskar_Mem* uu_in, const oskar_Mem* vv_in, const oskar_Mem* ww_in, oskar_Mem* amps) { #ifdef OSKAR_OS_WIN int i; const int num = (const int) num_vis; #else size_t i; const size_t num = num_vis; #endif const double delta_l = h->delta_l; const double delta_m = h->delta_m; const double delta_n = h->delta_n; const double twopi = 2.0 * M_PI; if (oskar_mem_precision(amps) == OSKAR_DOUBLE) { const double *u, *v, *w; double2* a; u = (const double*)oskar_mem_void_const(uu_in); v = (const double*)oskar_mem_void_const(vv_in); w = (const double*)oskar_mem_void_const(ww_in); a = (double2*)oskar_mem_void(amps); #pragma omp parallel for private(i) for (i = 0; i < num; ++i) { double arg, phase_re, phase_im, re, im; arg = twopi * (u[i] * delta_l + v[i] * delta_m + w[i] * delta_n); phase_re = cos(arg); phase_im = sin(arg); re = a[i].x * phase_re - a[i].y * phase_im; im = a[i].x * phase_im + a[i].y * phase_re; a[i].x = re; a[i].y = im; } } else { const float *u, *v, *w; float2* a; u = (const float*)oskar_mem_void_const(uu_in); v = (const float*)oskar_mem_void_const(vv_in); w = (const float*)oskar_mem_void_const(ww_in); a = (float2*)oskar_mem_void(amps); #pragma omp parallel for private(i) for (i = 0; i < num; ++i) { double arg, phase_re, phase_im, re, im; arg = twopi * (u[i] * delta_l + v[i] * delta_m + w[i] * delta_n); phase_re = cos(arg); phase_im = sin(arg); re = a[i].x * phase_re - a[i].y * phase_im; im = a[i].x * phase_im + a[i].y * phase_re; a[i].x = (float) re; a[i].y = (float) im; } } } #ifdef __cplusplus } #endif
GB_unop__identity_fp64_fp64.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_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = aij #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ #if 0 GrB_Info GB (_unop_apply__(none)) ( double *Cx, // Cx and Ax may be aliased const double *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; double aij = Ax [p] ; double z = aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fp64_fp64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
linAlgWeightedNorm2.c
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus 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. */ extern "C" void FUNC(weightedNorm2)(const dlong & Nblocks, const dlong & N, const dfloat * __restrict__ cpu_w, const dfloat * __restrict__ cpu_a, dfloat * __restrict__ cpu_wa){ dfloat wa2 = 0; #ifdef __NEKRS__OMP__ #pragma omp parallel for reduction(+:wa2) #endif for(int i=0;i<N;++i){ const dfloat ai = cpu_a[i]; const dfloat wi = cpu_w[i]; wa2 += ai*ai*wi; } cpu_wa[0] = wa2; } extern "C" void FUNC(weightedNorm2Many)(const dlong & Nblocks, const dlong & N, const dlong & Nfields, const dlong & offset, const dfloat * __restrict__ cpu_w, const dfloat * __restrict__ cpu_a, dfloat * __restrict__ cpu_wa){ dfloat wa2 = 0; #ifdef __NEKRS__OMP__ #pragma omp parallel for collapse(2) reduction(+:wa2) #endif for(int fld=0;fld<Nfields;fld++) { for(int i=0;i<N;++i){ const dlong id = i + fld*offset; const dfloat ai = cpu_a[id]; const dfloat wi = cpu_w[i]; wa2 += ai*ai*wi; } } cpu_wa[0] = wa2; }
Example_declare_target.1.c
/* * @@name: declare_target.1c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_4.0 */ #pragma omp declare target extern void fib(int N); #pragma omp end declare target #define THRESHOLD 1000000 void fib_wrapper(int n) { #pragma omp target if(n > THRESHOLD) { fib(n); } }
column_matrix.h
/*! * Copyright 2017 by Contributors * \file column_matrix.h * \brief Utility for fast column-wise access * \author Philip Cho */ #ifndef XGBOOST_COMMON_COLUMN_MATRIX_H_ #define XGBOOST_COMMON_COLUMN_MATRIX_H_ #include <limits> #include <vector> #include "hist_util.h" namespace xgboost { namespace common { /*! \brief column type */ enum ColumnType { kDenseColumn, kSparseColumn }; /*! \brief a column storage, to be used with ApplySplit. Note that each bin id is stored as index[i] + index_base. */ class Column { public: Column(ColumnType type, const uint32_t* index, uint32_t index_base, const size_t* row_ind, size_t len) : type_(type), index_(index), index_base_(index_base), row_ind_(row_ind), len_(len) {} size_t Size() const { return len_; } uint32_t GetGlobalBinIdx(size_t idx) const { return index_base_ + index_[idx]; } uint32_t GetFeatureBinIdx(size_t idx) const { return index_[idx]; } common::Span<const uint32_t> GetFeatureBinIdxPtr() const { return { index_, len_ }; } // column.GetFeatureBinIdx(idx) + column.GetBaseIdx(idx) == // column.GetGlobalBinIdx(idx) uint32_t GetBaseIdx() const { return index_base_; } ColumnType GetType() const { return type_; } size_t GetRowIdx(size_t idx) const { // clang-tidy worries that row_ind_ might be a nullptr, which is possible, // but low level structure is not safe anyway. return type_ == ColumnType::kDenseColumn ? idx : row_ind_[idx]; // NOLINT } bool IsMissing(size_t idx) const { return index_[idx] == std::numeric_limits<uint32_t>::max(); } const size_t* GetRowData() const { return row_ind_; } private: ColumnType type_; const uint32_t* index_; uint32_t index_base_; const size_t* row_ind_; const size_t len_; }; /*! \brief a collection of columns, with support for construction from GHistIndexMatrix. */ class ColumnMatrix { public: // get number of features inline bst_uint GetNumFeature() const { return static_cast<bst_uint>(type_.size()); } // construct column matrix from GHistIndexMatrix inline void Init(const GHistIndexMatrix& gmat, double sparse_threshold) { const int32_t nfeature = static_cast<int32_t>(gmat.cut.Ptrs().size() - 1); const size_t nrow = gmat.row_ptr.size() - 1; // identify type of each column feature_counts_.resize(nfeature); type_.resize(nfeature); std::fill(feature_counts_.begin(), feature_counts_.end(), 0); uint32_t max_val = std::numeric_limits<uint32_t>::max(); for (int32_t fid = 0; fid < nfeature; ++fid) { CHECK_LE(gmat.cut.Ptrs()[fid + 1] - gmat.cut.Ptrs()[fid], max_val); } gmat.GetFeatureCounts(&feature_counts_[0]); // classify features for (int32_t fid = 0; fid < nfeature; ++fid) { if (static_cast<double>(feature_counts_[fid]) < sparse_threshold * nrow) { type_[fid] = kSparseColumn; } else { type_[fid] = kDenseColumn; } } // want to compute storage boundary for each feature // using variants of prefix sum scan boundary_.resize(nfeature); size_t accum_index_ = 0; size_t accum_row_ind_ = 0; for (int32_t fid = 0; fid < nfeature; ++fid) { boundary_[fid].index_begin = accum_index_; boundary_[fid].row_ind_begin = accum_row_ind_; if (type_[fid] == kDenseColumn) { accum_index_ += static_cast<size_t>(nrow); accum_row_ind_ += static_cast<size_t>(nrow); } else { accum_index_ += feature_counts_[fid]; accum_row_ind_ += feature_counts_[fid]; } boundary_[fid].index_end = accum_index_; boundary_[fid].row_ind_end = accum_row_ind_; } index_.resize(boundary_[nfeature - 1].index_end); row_ind_.resize(boundary_[nfeature - 1].row_ind_end); // store least bin id for each feature index_base_.resize(nfeature); for (int32_t fid = 0; fid < nfeature; ++fid) { index_base_[fid] = gmat.cut.Ptrs()[fid]; } // pre-fill index_ for dense columns #pragma omp parallel for for (int32_t fid = 0; fid < nfeature; ++fid) { if (type_[fid] == kDenseColumn) { const size_t ibegin = boundary_[fid].index_begin; uint32_t* begin = &index_[ibegin]; uint32_t* end = begin + nrow; std::fill(begin, end, std::numeric_limits<uint32_t>::max()); // max() indicates missing values } } // loop over all rows and fill column entries // num_nonzeros[fid] = how many nonzeros have this feature accumulated so far? std::vector<size_t> num_nonzeros; num_nonzeros.resize(nfeature); std::fill(num_nonzeros.begin(), num_nonzeros.end(), 0); for (size_t rid = 0; rid < nrow; ++rid) { const size_t ibegin = gmat.row_ptr[rid]; const size_t iend = gmat.row_ptr[rid + 1]; size_t fid = 0; for (size_t i = ibegin; i < iend; ++i) { const uint32_t bin_id = gmat.index[i]; auto iter = std::upper_bound(gmat.cut.Ptrs().cbegin() + fid, gmat.cut.Ptrs().cend(), bin_id); fid = std::distance(gmat.cut.Ptrs().cbegin(), iter) - 1; if (type_[fid] == kDenseColumn) { uint32_t* begin = &index_[boundary_[fid].index_begin]; begin[rid] = bin_id - index_base_[fid]; } else { uint32_t* begin = &index_[boundary_[fid].index_begin]; begin[num_nonzeros[fid]] = bin_id - index_base_[fid]; row_ind_[boundary_[fid].row_ind_begin + num_nonzeros[fid]] = rid; ++num_nonzeros[fid]; } } } } /* Fetch an individual column. This code should be used with XGBOOST_TYPE_SWITCH to determine type of bin id's */ inline Column GetColumn(unsigned fid) const { Column c(type_[fid], &index_[boundary_[fid].index_begin], index_base_[fid], (type_[fid] == ColumnType::kSparseColumn ? &row_ind_[boundary_[fid].row_ind_begin] : nullptr), boundary_[fid].index_end - boundary_[fid].index_begin); return c; } private: struct ColumnBoundary { // indicate where each column's index and row_ind is stored. // index_begin and index_end are logical offsets, so they should be converted to // actual offsets by scaling with packing_factor_ size_t index_begin; size_t index_end; size_t row_ind_begin; size_t row_ind_end; }; std::vector<size_t> feature_counts_; std::vector<ColumnType> type_; std::vector<uint32_t> index_; // index_: may store smaller integers; needs padding std::vector<size_t> row_ind_; std::vector<ColumnBoundary> boundary_; // index_base_[fid]: least bin id for feature fid std::vector<uint32_t> index_base_; }; } // namespace common } // namespace xgboost #endif // XGBOOST_COMMON_COLUMN_MATRIX_H_
horizontal_generation.c
/* This source file is part of the Geophysical Fluids Modeling Framework (GAME), which is released under the MIT license. Github repository: https://github.com/OpenNWP/GAME */ /* In this file, the horizontal grid generation procedure is stored. */ #include <stdlib.h> #include <stdio.h> #include <netcdf.h> #include <geos95.h> #include "../../src/game_types.h" #include "../../src/game_constants.h" #include "include.h" #define ERRCODE 2 #define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);} int generate_horizontal_generators(double latitude_ico[], double longitude_ico[], double latitude_scalar[], double longitude_scalar[], double x_unity[], double y_unity[], double z_unity[], int face_edges_reverse[][3], int face_edges[][3], int face_vertices[][3]) { /* This function computes the geographical coordinates of the generators (centers of the pentagons and hexagons). */ int base_index_down_triangles, base_index_old, test_index, last_triangle_bool, old_triangle_on_line_index, base_index_up_triangles, points_downwards, points_upwards, dump, points_per_edge, edgepoint_0, edgepoint_1, edgepoint_2, no_of_triangles_per_face, point_0, point_1, point_2, dual_scalar_on_face_index, coord_0, coord_1, triangle_on_face_index, coord_0_points_amount; double x_res, y_res, z_res; for (int i = 0; i < NO_OF_SCALARS_H; ++i) { upscale_scalar_point(RES_ID, i, &test_index); if (test_index != i) { printf("problem with upscale_scalar_point detected\n"); } } for (int i = 0; i < NO_OF_PENTAGONS; ++i) { latitude_scalar[i] = latitude_ico[i]; longitude_scalar[i] = longitude_ico[i]; find_global_normal(latitude_ico[i], longitude_ico[i], &x_res, &y_res, &z_res); x_unity[i] = x_res; y_unity[i] = y_res; z_unity[i] = z_res; } for (int i = 0; i < NO_OF_BASIC_TRIANGLES; ++i) { for (int j = 0; j < RES_ID; ++j) { no_of_triangles_per_face = find_triangles_per_face(j); for (int k = 0; k < no_of_triangles_per_face; ++k) { if (j == 0) { dual_scalar_on_face_index = 1; find_triangle_edge_points_from_dual_scalar_on_face_index(dual_scalar_on_face_index, i, j + 1, &point_0, &point_1, &point_2, face_vertices, face_edges, face_edges_reverse); upscale_scalar_point(j + 1, point_0, &point_0); upscale_scalar_point(j + 1, point_1, &point_1); upscale_scalar_point(j + 1, point_2, &point_2); points_upwards = 1; write_scalar_coordinates(face_vertices[i][0], face_vertices[i][1], face_vertices[i][2], point_0, point_1, point_2, points_upwards, x_unity, y_unity, z_unity, latitude_scalar, longitude_scalar); } else { find_triangle_edge_points_from_dual_scalar_on_face_index(k, i, j, &edgepoint_0, &edgepoint_1, &edgepoint_2, face_vertices, face_edges, face_edges_reverse); find_triangle_on_face_index_from_dual_scalar_on_face_index(k, j, &triangle_on_face_index, &points_downwards, &dump, &last_triangle_bool); find_coords_from_triangle_on_face_index(triangle_on_face_index, j, &coord_0, &coord_1, &coord_0_points_amount); points_per_edge = find_points_per_edge(j); base_index_old = 0; base_index_down_triangles = 0; base_index_up_triangles = base_index_down_triangles + 4*points_per_edge + 3; for (int l = 0; l < coord_1; ++l) { coord_0_points_amount = points_per_edge - l; base_index_old += 2*coord_0_points_amount + 1; base_index_down_triangles += 4*(2*coord_0_points_amount + 1); base_index_up_triangles = base_index_down_triangles + 4*(points_per_edge - l) + 3; } if (last_triangle_bool == 1) { base_index_old += 3; base_index_down_triangles += 12; base_index_up_triangles = base_index_down_triangles + 3; } old_triangle_on_line_index = k - base_index_old; if (points_downwards == 0) { dual_scalar_on_face_index = base_index_down_triangles + 1 + 2*old_triangle_on_line_index; } else { dual_scalar_on_face_index = base_index_up_triangles + 2*old_triangle_on_line_index; } find_triangle_edge_points_from_dual_scalar_on_face_index(dual_scalar_on_face_index, i, j + 1, &point_0, &point_1, &point_2, face_vertices, face_edges, face_edges_reverse); upscale_scalar_point(j, edgepoint_0, &edgepoint_0); upscale_scalar_point(j, edgepoint_1, &edgepoint_1); upscale_scalar_point(j, edgepoint_2, &edgepoint_2); upscale_scalar_point(j + 1, point_0, &point_0); upscale_scalar_point(j + 1, point_1, &point_1); upscale_scalar_point(j + 1, point_2, &point_2); points_upwards = 1; if (points_downwards == 1) { points_upwards = 0; } write_scalar_coordinates(edgepoint_0, edgepoint_1, edgepoint_2, point_0, point_1, point_2, points_upwards, x_unity, y_unity, z_unity, latitude_scalar, longitude_scalar); } } } } return 0; } int calc_cell_area_unity(double pent_hex_face_unity_sphere[], double latitude_scalar_dual[], double longitude_scalar_dual[], int adjacent_vector_indices_h[], int vorticity_indices_pre[]) { /* This function computes the areas of the cells (pentagons and hexagons) on the unity sphere. */ int check_0, check_1, check_2, counter, no_of_edges; for (int i = 0; i < NO_OF_SCALARS_H; ++i) { no_of_edges = 6; if (i < NO_OF_PENTAGONS) { no_of_edges = 5; } double lat_points[no_of_edges]; double lon_points[no_of_edges]; int cell_vector_indices[no_of_edges]; for (int j = 0; j < no_of_edges; ++j) { cell_vector_indices[j] = adjacent_vector_indices_h[6*i + j]; } counter = 0; for (int j = 0; j < NO_OF_DUAL_SCALARS_H; ++j) { check_0 = in_bool_calculator(vorticity_indices_pre[3*j + 0], cell_vector_indices, no_of_edges); check_1 = in_bool_calculator(vorticity_indices_pre[3*j + 1], cell_vector_indices, no_of_edges); check_2 = in_bool_calculator(vorticity_indices_pre[3*j + 2], cell_vector_indices, no_of_edges); if (check_0 == 1 || check_1 == 1 || check_2 == 1) { lat_points[counter] = latitude_scalar_dual[j]; lon_points[counter] = longitude_scalar_dual[j]; counter++; } } if (counter != no_of_edges) { printf("Trouble in calc_cell_face_unity.\n"); } pent_hex_face_unity_sphere[i] = calc_spherical_polygon_area(lat_points, lon_points, no_of_edges); } double pent_hex_sum_unity_sphere = 0; double pent_hex_avg_unity_sphere_ideal = 4*M_PI/NO_OF_SCALARS_H; for (int i = 0; i < NO_OF_SCALARS_H; ++i) { pent_hex_sum_unity_sphere += pent_hex_face_unity_sphere[i]; if (pent_hex_face_unity_sphere[i] <= 0) { printf("pent_hex_face_unity_sphere contains a non-positive value.\n"); exit(1); } if (fabs(pent_hex_face_unity_sphere[i]/pent_hex_avg_unity_sphere_ideal - 1) > 0.4) { printf("Pentagons and hexagons on unity sphere have significantly different surfaces.\n"); exit(1); } } if (fabs(pent_hex_sum_unity_sphere/(4*M_PI) - 1) > EPSILON_SECURITY) { printf("Sum of faces of pentagons and hexagons on unity sphere does not match face of unit sphere.\n"); exit(1); } return 0; } int calc_triangle_area_unity(double triangle_face_unit_sphere[], double latitude_scalar[], double longitude_scalar[], int face_edges[][3], int face_edges_reverse[][3], int face_vertices[][3]) { /* This function computes the areas of the triangles on the unity sphere. */ int dual_scalar_index, point_0, point_1, point_2, point_3, point_4, point_5, dual_scalar_on_face_index, small_triangle_edge_index, coord_0_points_amount, coord_0, coord_1, face_index, on_face_index, triangle_on_face_index; double triangle_face; for (int i = 0; i < NO_OF_VECTORS_H; ++i) { if (i >= NO_OF_EDGES*(POINTS_PER_EDGE + 1)) { find_triangle_indices_from_h_vector_index(RES_ID, i, &point_0, &point_1, &point_2, &point_3, &point_4, &point_5, &dual_scalar_on_face_index, &small_triangle_edge_index, face_edges, face_vertices, face_edges_reverse); face_index = (i - NO_OF_EDGES*(POINTS_PER_EDGE + 1))/VECTOR_POINTS_PER_INNER_FACE; on_face_index = i - (NO_OF_EDGES*(POINTS_PER_EDGE + 1) + face_index*VECTOR_POINTS_PER_INNER_FACE); triangle_on_face_index = on_face_index/3; find_coords_from_triangle_on_face_index(triangle_on_face_index, RES_ID, &coord_0, &coord_1, &coord_0_points_amount); dual_scalar_index = dual_scalar_on_face_index + face_index*NO_OF_TRIANGLES/NO_OF_BASIC_TRIANGLES; triangle_face = calc_triangle_area(latitude_scalar[point_0], longitude_scalar[point_0], latitude_scalar[point_1], longitude_scalar[point_1], latitude_scalar[point_2], longitude_scalar[point_2]); triangle_face_unit_sphere[dual_scalar_index] = triangle_face; triangle_face = calc_triangle_area(latitude_scalar[point_3], longitude_scalar[point_3], latitude_scalar[point_0], longitude_scalar[point_0], latitude_scalar[point_2], longitude_scalar[point_2]); triangle_face_unit_sphere[dual_scalar_index - 1] = triangle_face; if (coord_0 == coord_0_points_amount - 1) { triangle_face = calc_triangle_area(latitude_scalar[point_0], longitude_scalar[point_0], latitude_scalar[point_4], longitude_scalar[point_4], latitude_scalar[point_1], longitude_scalar[point_1]); triangle_face_unit_sphere[dual_scalar_index + 1] = triangle_face; if (coord_1 == POINTS_PER_EDGE - 1) { triangle_face = calc_triangle_area(latitude_scalar[point_2], longitude_scalar[point_2], latitude_scalar[point_1], longitude_scalar[point_1], latitude_scalar[point_5], longitude_scalar[point_5]); triangle_face_unit_sphere[dual_scalar_index + 2] = triangle_face; } } } } double triangle_sum_unit_sphere = 0; double triangle_avg_unit_sphere_ideal = 4*M_PI/NO_OF_TRIANGLES; for (int i = 0; i < NO_OF_DUAL_SCALARS_H; ++i) { triangle_sum_unit_sphere += triangle_face_unit_sphere[i]; if (triangle_face_unit_sphere[i] <= 0) { printf("triangle_face_unit_sphere contains a non-positive value.\n"); exit(1); } if (fabs(triangle_face_unit_sphere[i]/triangle_avg_unit_sphere_ideal - 1) > 0.4) { printf("Triangles on unit sphere have significantly different surfaces.\n"); exit(1); } } if (fabs(triangle_sum_unit_sphere/(4*M_PI) - 1) > EPSILON_SECURITY) { printf("Sum of faces of triangles on unit sphere does not match face of unit sphere.\n"); exit(1); } return 0; } int set_vector_h_doubles(int from_index[], int to_index[], double latitude_scalar[], double longitude_scalar[], double latitude_vector[], double longitude_vector[], double direction[]) { /* This function sets the geographical coordinates and the directions of the horizontal vector points. */ double x_point_0, y_point_0, z_point_0, x_point_1, y_point_1, z_point_1, x_res, y_res, z_res, lat_res, lon_res; #pragma omp parallel for private(x_point_0, y_point_0, z_point_0, x_point_1, y_point_1, z_point_1, x_res, y_res, z_res, lat_res, lon_res) for (int i = 0; i < NO_OF_VECTORS_H; ++i) { find_global_normal(latitude_scalar[from_index[i]], longitude_scalar[from_index[i]], &x_point_0, &y_point_0, &z_point_0); find_global_normal(latitude_scalar[to_index[i]], longitude_scalar[to_index[i]], &x_point_1, &y_point_1, &z_point_1); find_between_point(x_point_0, y_point_0, z_point_0, x_point_1, y_point_1, z_point_1, 0.5, &x_res, &y_res, &z_res); find_geos(x_res, y_res, z_res, &lat_res, &lon_res); latitude_vector[i] = lat_res; longitude_vector[i] = lon_res; direction[i] = find_geodetic_direction(latitude_scalar[from_index[i]], longitude_scalar[from_index[i]], latitude_scalar[to_index[i]], longitude_scalar[to_index[i]], 0.5); } return 0; } int set_from_to_index(int from_index[], int to_index[], int face_edges[][3], int face_edges_reverse[][3], int face_vertices[][3], int edge_vertices[][2]) { /* This function computes the neighbourship relationships of the horizontal vectors. */ int edge_index, on_edge_index, point_0, point_1, point_2, point_3, point_4, point_5, dual_scalar_on_face_index, small_triangle_edge_index; #pragma omp parallel for private(edge_index, on_edge_index, point_0, point_1, point_2, point_3, point_4, point_5, dual_scalar_on_face_index, small_triangle_edge_index) for (int i = 0; i < NO_OF_VECTORS_H; ++i) { if (i < NO_OF_EDGES*(POINTS_PER_EDGE + 1)) { edge_index = i/(POINTS_PER_EDGE + 1); on_edge_index = i - edge_index*(POINTS_PER_EDGE + 1); if(on_edge_index == 0) { from_index[i] = edge_vertices[edge_index][0]; to_index[i] = NO_OF_PENTAGONS + edge_index*POINTS_PER_EDGE; } else if (on_edge_index == POINTS_PER_EDGE) { from_index[i] = NO_OF_PENTAGONS + (edge_index + 1)*POINTS_PER_EDGE - 1; to_index[i] = edge_vertices[edge_index][1]; } else { from_index[i] = NO_OF_PENTAGONS + edge_index*POINTS_PER_EDGE + on_edge_index - 1; to_index[i] = NO_OF_PENTAGONS + edge_index*POINTS_PER_EDGE + on_edge_index; } } else { find_triangle_indices_from_h_vector_index(RES_ID, i, &point_0, &point_1, &point_2, &point_3, &point_4, &point_5, &dual_scalar_on_face_index, &small_triangle_edge_index, face_edges, face_vertices, face_edges_reverse); if (small_triangle_edge_index == 0) { from_index[i] = point_0; to_index[i] = point_2; } if (small_triangle_edge_index == 1) { from_index[i] = point_0; to_index[i] = point_1; } if (small_triangle_edge_index == 2) { from_index[i] = point_2; to_index[i] = point_1; } } } return 0; } int set_scalar_h_dual_coords(double latitude_scalar_dual[], double longitude_scalar_dual[], double latitude_scalar[], double longitude_scalar[], int face_edges[][3], int face_edges_reverse[][3], int face_vertices[][3]) { /* This function calculates the geographical coordinates of the dual scalar points. */ double lat_res, lon_res; int point_0, point_1, point_2, point_3, point_4, point_5, dual_scalar_on_face_index, small_triangle_edge_index, dual_scalar_index, coord_0, coord_1, coord_0_points_amount, face_index, on_face_index, triangle_on_face_index; #pragma omp parallel for private(lat_res, lon_res, point_0, point_1, point_2, point_3, point_4, point_5, dual_scalar_on_face_index, small_triangle_edge_index, dual_scalar_index, coord_0, coord_1, coord_0_points_amount, face_index, on_face_index, triangle_on_face_index) for (int i = 0; i < NO_OF_VECTORS_H; ++i) { if (i >= NO_OF_EDGES*(POINTS_PER_EDGE + 1)) { find_triangle_indices_from_h_vector_index(RES_ID, i, &point_0, &point_1, &point_2, &point_3, &point_4, &point_5, &dual_scalar_on_face_index, &small_triangle_edge_index, face_edges, face_vertices, face_edges_reverse); face_index = (i - NO_OF_EDGES*(POINTS_PER_EDGE + 1))/VECTOR_POINTS_PER_INNER_FACE; on_face_index = i - (NO_OF_EDGES*(POINTS_PER_EDGE + 1) + face_index*VECTOR_POINTS_PER_INNER_FACE); triangle_on_face_index = on_face_index/3; find_coords_from_triangle_on_face_index(triangle_on_face_index, RES_ID, &coord_0, &coord_1, &coord_0_points_amount); dual_scalar_index = dual_scalar_on_face_index + face_index*NO_OF_TRIANGLES/NO_OF_BASIC_TRIANGLES; // We want to construct a Voronoi gird, that's why we choose this function for calculating the dual cell centers. find_voronoi_center_sphere(latitude_scalar[point_0], longitude_scalar[point_0], latitude_scalar[point_1], longitude_scalar[point_1], latitude_scalar[point_2], longitude_scalar[point_2], &lat_res, &lon_res); latitude_scalar_dual[dual_scalar_index] = lat_res; longitude_scalar_dual[dual_scalar_index] = lon_res; find_voronoi_center_sphere(latitude_scalar[point_3], longitude_scalar[point_3], latitude_scalar[point_0], longitude_scalar[point_0], latitude_scalar[point_2], longitude_scalar[point_2], &lat_res, &lon_res); latitude_scalar_dual[dual_scalar_index - 1] = lat_res; longitude_scalar_dual[dual_scalar_index - 1] = lon_res; if (coord_0 == coord_0_points_amount - 1) { find_voronoi_center_sphere(latitude_scalar[point_0], longitude_scalar[point_0], latitude_scalar[point_4], longitude_scalar[point_4], latitude_scalar[point_1], longitude_scalar[point_1], &lat_res, &lon_res); latitude_scalar_dual[dual_scalar_index + 1] = lat_res; longitude_scalar_dual[dual_scalar_index + 1] = lon_res; if (coord_1 == POINTS_PER_EDGE - 1) { find_voronoi_center_sphere(latitude_scalar[point_2], longitude_scalar[point_2], latitude_scalar[point_1], longitude_scalar[point_1], latitude_scalar[point_5], longitude_scalar[point_5], &lat_res, &lon_res); latitude_scalar_dual[dual_scalar_index + 2] = lat_res; longitude_scalar_dual[dual_scalar_index + 2] = lon_res; } } } } return 0; } int set_from_to_index_dual(int from_index_dual[], int to_index_dual[], int face_edges [][3], int face_edges_reverse[][3]) { /* This function computes the neighbourship relationships of the horizontal dual vectors. */ int coord_0, coord_1, on_face_index, on_edge_index, edge_index, small_triangle_edge_index, coord_0_points_amount, first_face_found, face_index; #pragma omp parallel for private(coord_0, coord_1, on_face_index, on_edge_index, edge_index, small_triangle_edge_index, coord_0_points_amount, first_face_found, face_index) for (int i = 0; i < NO_OF_VECTORS_H; ++i) { int edge_rel_to_face_0 = 0; int edge_rel_to_face_1 = 0; int face_index_0 = 0; int face_index_1 = 0; int triangle_on_face_index = 0; if (i < NO_OF_EDGES*(POINTS_PER_EDGE + 1)) { edge_index = i/(POINTS_PER_EDGE + 1); on_edge_index = i - edge_index*(POINTS_PER_EDGE + 1); first_face_found = 0; for (int j = 0; j < NO_OF_BASIC_TRIANGLES; ++j) { if (face_edges[j][0] == edge_index || face_edges[j][1] == edge_index || face_edges[j][2] == edge_index) { if (first_face_found == 0) { face_index_0 = j; first_face_found = 1; } else { face_index_1 = j; } } } if (face_edges[face_index_0][0] == edge_index) { edge_rel_to_face_0 = 0; } if (face_edges[face_index_0][1] == edge_index) { edge_rel_to_face_0 = 1; } if (face_edges[face_index_0][2] == edge_index) { edge_rel_to_face_0 = 2; } if (face_edges[face_index_1][0] == edge_index) { edge_rel_to_face_1 = 0; } if (face_edges[face_index_1][1] == edge_index) { edge_rel_to_face_1 = 1; } if (face_edges[face_index_1][2] == edge_index) { edge_rel_to_face_1 = 2; } if (edge_rel_to_face_0 == 0) { if (face_edges_reverse[face_index_0][edge_rel_to_face_0] == 0) { triangle_on_face_index = 2*on_edge_index; } else { triangle_on_face_index = 2*POINTS_PER_EDGE - 2*on_edge_index; } } if (edge_rel_to_face_0 == 1) { if (face_edges_reverse[face_index_0][edge_rel_to_face_0] == 0) { triangle_on_face_index = -1 + (on_edge_index + 1)*(2*POINTS_PER_EDGE - on_edge_index + 1); } else { triangle_on_face_index = TRIANGLES_PER_FACE - on_edge_index*on_edge_index - 1; } } if (edge_rel_to_face_0 == 2) { if (face_edges_reverse[face_index_0][edge_rel_to_face_0] == 0) { triangle_on_face_index = TRIANGLES_PER_FACE - 1 - on_edge_index*(on_edge_index + 2); } else { triangle_on_face_index = on_edge_index*(2*POINTS_PER_EDGE + 2 - on_edge_index); } } to_index_dual[i] = face_index_0*TRIANGLES_PER_FACE + triangle_on_face_index; if (edge_rel_to_face_1 == 0) { if (face_edges_reverse[face_index_1][edge_rel_to_face_1] == 0) { triangle_on_face_index = 2*on_edge_index; } else { triangle_on_face_index = 2*POINTS_PER_EDGE - 2*on_edge_index; } } if (edge_rel_to_face_1 == 1) { if (face_edges_reverse[face_index_1][edge_rel_to_face_1] == 0) { triangle_on_face_index = -1 + (on_edge_index + 1)*(2*POINTS_PER_EDGE - on_edge_index + 1); } else { triangle_on_face_index = TRIANGLES_PER_FACE - on_edge_index*on_edge_index - 1; } } if (edge_rel_to_face_1 == 2) { if (face_edges_reverse[face_index_1][edge_rel_to_face_1] == 0) { triangle_on_face_index = TRIANGLES_PER_FACE - 1 - on_edge_index*(on_edge_index + 2); } else { triangle_on_face_index = on_edge_index*(2*POINTS_PER_EDGE + 2 - on_edge_index); } } from_index_dual[i] = face_index_1*TRIANGLES_PER_FACE + triangle_on_face_index; } else { face_index = (i - NO_OF_EDGES*(POINTS_PER_EDGE + 1))/VECTOR_POINTS_PER_INNER_FACE; on_face_index = i - (NO_OF_EDGES*(POINTS_PER_EDGE + 1) + face_index*VECTOR_POINTS_PER_INNER_FACE); triangle_on_face_index = on_face_index/3; small_triangle_edge_index = on_face_index - 3*triangle_on_face_index; find_coords_from_triangle_on_face_index(triangle_on_face_index, RES_ID, &coord_0, &coord_1, &coord_0_points_amount); if (small_triangle_edge_index == 0) { from_index_dual[i] = face_index*TRIANGLES_PER_FACE + 2*triangle_on_face_index + coord_1; to_index_dual[i] = from_index_dual[i] + 1; } if (small_triangle_edge_index == 1) { from_index_dual[i] = face_index*TRIANGLES_PER_FACE + 2*triangle_on_face_index + 1 + coord_1; to_index_dual[i] = from_index_dual[i] + 1; } if (small_triangle_edge_index == 2) { from_index_dual[i] = face_index*TRIANGLES_PER_FACE + 2*triangle_on_face_index + 1 + coord_1; to_index_dual[i] = from_index_dual[i] + 2*coord_0_points_amount; } } } return 0; } int set_dual_vector_h_doubles(double latitude_scalar_dual[], double latitude_vector[], double direction_dual[], double longitude_vector[], int to_index_dual[], int from_index_dual[], double longitude_scalar_dual[], double rel_on_line_dual[]) { /* This function computes the following two properties of horizontal dual vectors: - where they are placed in between the dual scalar points - in which direction they point */ #pragma omp parallel for for (int i = 0; i < NO_OF_VECTORS_H; ++i) { find_min_dist_rel_on_line(latitude_scalar_dual[from_index_dual[i]], longitude_scalar_dual[from_index_dual[i]], latitude_scalar_dual[to_index_dual[i]], longitude_scalar_dual[to_index_dual[i]], latitude_vector[i], longitude_vector[i], &rel_on_line_dual[i]); if (fabs(rel_on_line_dual[i] - 0.5) > 0.14) { printf("Bisection warning.\n"); } direction_dual[i] = find_geodetic_direction(latitude_scalar_dual[from_index_dual[i]], longitude_scalar_dual[from_index_dual[i]], latitude_scalar_dual[to_index_dual[i]], longitude_scalar_dual[to_index_dual[i]], rel_on_line_dual[i]); } return 0; } int direct_tangential_unity(double latitude_scalar_dual[], double longitude_scalar_dual[], double direction[], double direction_dual[], int to_index_dual[], int from_index_dual[], double rel_on_line_dual[], double ORTH_CRITERION_DEG) { /* This function determines the directions of the dual vectors. */ // ensuring e_y = k x e_z int temp_index; double direction_change; #pragma omp parallel for private(temp_index, direction_change) for (int i = 0; i < NO_OF_VECTORS_H; ++i) { direction_change = find_turn_angle(direction[i], direction_dual[i]); if (rad2deg(direction_change) < -ORTH_CRITERION_DEG) { temp_index = from_index_dual[i]; from_index_dual[i] = to_index_dual[i]; to_index_dual[i] = temp_index; rel_on_line_dual[i] = 1 - rel_on_line_dual[i]; direction_dual[i] = find_geodetic_direction(latitude_scalar_dual[from_index_dual[i]], longitude_scalar_dual[from_index_dual[i]], latitude_scalar_dual[to_index_dual[i]], longitude_scalar_dual[to_index_dual[i]], rel_on_line_dual[i]); } } // checking for orthogonality #pragma omp parallel for private(direction_change) for (int i = 0; i < NO_OF_VECTORS_H; ++i) { direction_change = find_turn_angle(direction[i], direction_dual[i]); if (fabs(rad2deg(direction_change)) < ORTH_CRITERION_DEG || fabs(rad2deg(direction_change)) > 90 + (90 - ORTH_CRITERION_DEG)) { printf("Grid non-orthogonal: Intersection angle of %lf degrees detected.\n", fabs(rad2deg(direction_change))); } } return 0; } int read_horizontal_explicit(double latitude_scalar[], double longitude_scalar[], int from_index[], int to_index[], int from_index_dual[], int to_index_dual[], char filename[], int *no_of_lloyd_iterations) { /* This function reads the arrays that fully define the horizontal grid from a previously created grid file. This is an optional feature. */ int ncid, latitude_scalar_id, longitude_scalar_id, retval, from_index_id, to_index_id, from_index_dual_id, to_index_dual_id, no_of_lloyd_iterations_id; retval = 0; if ((nc_open(filename, NC_NOWRITE, &ncid))) ERR(retval); if ((nc_inq_varid(ncid, "latitude_scalar", &latitude_scalar_id))) ERR(retval); if ((nc_inq_varid(ncid, "longitude_scalar", &longitude_scalar_id))) ERR(retval); if ((nc_inq_varid(ncid, "from_index", &from_index_id))) ERR(retval); if ((nc_inq_varid(ncid, "to_index", &to_index_id))) ERR(retval); if ((nc_inq_varid(ncid, "from_index_dual", &from_index_dual_id))) ERR(retval); if ((nc_inq_varid(ncid, "to_index_dual", &to_index_dual_id))) ERR(retval); if ((nc_inq_varid(ncid, "no_of_lloyd_iterations", &no_of_lloyd_iterations_id))) ERR(retval); if ((nc_get_var_double(ncid, latitude_scalar_id, &latitude_scalar[0]))) ERR(retval); if ((nc_get_var_double(ncid, longitude_scalar_id, &longitude_scalar[0]))) ERR(retval); if ((nc_get_var_int(ncid, from_index_id, &from_index[0]))) ERR(retval); if ((nc_get_var_int(ncid, to_index_id, &to_index[0]))) ERR(retval); if ((nc_get_var_int(ncid, from_index_dual_id, &from_index_dual[0]))) ERR(retval); if ((nc_get_var_int(ncid, to_index_dual_id, &to_index_dual[0]))) ERR(retval); if ((nc_get_var_int(ncid, no_of_lloyd_iterations_id, no_of_lloyd_iterations))) ERR(retval); if ((nc_close(ncid))) ERR(retval); return 0; }
GB_binop__first_fp64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__first_fp64 // A.*B function (eWiseMult): GB_AemultB__first_fp64 // A*D function (colscale): GB_AxD__first_fp64 // D*A function (rowscale): GB_DxB__first_fp64 // C+=B function (dense accum): GB_Cdense_accumB__first_fp64 // C+=b function (dense accum): GB_Cdense_accumb__first_fp64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__first_fp64 // C=scalar+B GB_bind1st__first_fp64 // C=scalar+B' GB_bind1st_tran__first_fp64 // C=A+scalar (none) // C=A'+scalar (none) // C type: double // A type: double // B,b type: double // BinaryOp: cij = aij #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ double t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = x ; // 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_FIRST || GxB_NO_FP64 || GxB_NO_FIRST_FP64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__first_fp64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__first_fp64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #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__first_fp64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type double double bwork = (*((double *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__first_fp64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *GB_RESTRICT Cx = (double *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__first_fp64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *GB_RESTRICT Cx = (double *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__first_fp64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__first_fp64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__first_fp64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { ; ; Cx [p] = x ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; Cx [p] = aij ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = x ; \ } GrB_Info GB_bind1st_tran__first_fp64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = Ax [pA] ; \ Cx [pC] = aij ; \ } GrB_Info (none) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double y = (*((const double *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
common.h
#ifndef __COMMON_H__ #define __COMMON_H__ #include <string.h> #include <string> #include <stdio.h> #include <assert.h> #include <stdint.h> #include <math.h> #include <algorithm> #include <list> #include <vector> #include <complex> #include <unistd.h> #include <iostream> #include <limits.h> #include <random> #include "../shared/model.h" /** * labels corresponding to symmetry of each tensor dimension * NS = 0 - nonsymmetric * SY = 1 - symmetric * AS = 2 - antisymmetric * SH = 3 - symmetric hollow */ //enum SYM : int { NS, SY, AS, SH }; /** * labels corresponding to symmetry or strucutre of entire tensor * NS = 0 - nonsymmetric * SY = 1 - symmetric * AS = 2 - antisymmetric * SH = 3 - symmetric hollow * SP = 4 - sparse */ enum STRUCTURE : int { NS, SY, AS, SH, SP }; typedef STRUCTURE SYM; namespace CTF { /** * \addtogroup CTF * @{ */ extern int DGTOG_SWITCH; /** * \brief reduction types for tensor data * deprecated types: OP_NORM1=OP_SUMABS, OP_NORM2=call norm2(), OP_NORM_INFTY=OP_MAXABS */ enum OP { OP_SUM, OP_SUMABS, OP_SUMSQ, OP_MAX, OP_MIN, OP_MAXABS, OP_MINABS}; // sets flops counters to 0 void initialize_flops_counter(); // get analytically estimated flops, which are effectual flops in dense case, but estimates based on aggregate nonzero density for sparse case int64_t get_estimated_flops(); /** * @} */ } namespace CTF_int { /** * \brief initialized random number generator * \param[in] rank processor index */ void init_rng(int rank); /** * \brief returns new random number in [0,1) */ double get_rand48(); void handler(); #define IASSERT(...) \ do { if (!(__VA_ARGS__)){ int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); if (rank == 0){ printf("CTF ERROR: %s:%d, ASSERT(%s) failed\n",__FILE__,__LINE__,#__VA_ARGS__); } CTF_int::handler(); assert(__VA_ARGS__); } } while (0) /** * \brief computes the size of a tensor in SY (NOT HOLLOW) packed symmetric layout * \param[in] order tensor dimension * \param[in] len tensor edge _elngths * \param[in] sym tensor symmetries * \return size of tensor in packed layout */ int64_t sy_packed_size(int order, const int64_t * len, const int* sym); /** * \brief computes the size of a tensor in packed symmetric (SY, SH, or AS) layout * \param[in] order tensor dimension * \param[in] len tensor edge _elngths * \param[in] sym tensor symmetries * \return size of tensor in packed layout */ int64_t packed_size(int order, const int64_t * len, const int* sym); enum { SUCCESS, ERROR, NEGATIVE }; template <typename type=char> int conv_idx(int order, type const * cidx, int ** iidx); template <typename type=char> int conv_idx(int order_A, type const * cidx_A, int ** iidx_A, int order_B, type const * cidx_B, int ** iidx_B); template <typename type=char> int conv_idx(int order_A, type const * cidx_A, int ** iidx_A, int order_B, type const * cidx_B, int ** iidx_B, int order_C, type const * cidx_C, int ** iidx_C); int64_t * conv_to_int64(int const * arr, int len); int * conv_to_int(int64_t const * arr, int len); int64_t * copy_int64(int64_t const * arr, int len); // accumulates computed flops (targeted for internal use) void add_computed_flops(int64_t n); // get computed flops int64_t get_computed_flops(); // accumulates computed flops (targeted for internal use) void add_estimated_flops(int64_t n); class CommData { public: MPI_Comm cm; int np; int rank; int color; int alive; int created; CommData(); ~CommData(); /** \brief copy constructor sets created to zero */ CommData(CommData const & other); CommData& operator=(CommData const & other); /** * \brief create active communicator wrapper * \param[in] cm MPI_Comm defining this wrapper */ CommData(MPI_Comm cm); /** * \brief create non-active communicator wrapper * \param[in] rank rank within this comm * \param[in] color identifier of comm within parent * \param[in] np number of processors within this comm */ CommData(int rank, int color, int np); /** * \brief create active subcomm from parent comm which must be active * \param[in] rank processor rank within subcomm * \param[in] color identifier of subcomm within this comm * \param[in] parent comm to split */ CommData(int rank, int color, CommData parent); /** * \brief activate this subcommunicator by splitting parent_comm * \param[in] parent communicator to split */ void activate(MPI_Comm parent); /* \brief deactivate (MPI_Free) this comm */ void deactivate(); /* \brief provide estimate of broadcast execution time */ double estimate_bcast_time(int64_t msg_sz); /* \brief provide estimate of allreduction execution time */ double estimate_allred_time(int64_t msg_sz, MPI_Op op); /* \brief provide estimate of reduction execution time */ double estimate_red_time(int64_t msg_sz, MPI_Op op); /* \brief provide estimate of sparse reduction execution time */ // double estimate_csrred_time(int64_t msg_sz, MPI_Op op); /* \brief provide estimate of all_to_all execution time */ double estimate_alltoall_time(int64_t chunk_sz); /* \brief provide estimate of all_to_all_v execution time */ double estimate_alltoallv_time(int64_t tot_sz); /** * \brief broadcast, same interface as MPI_Bcast, but excluding the comm */ void bcast(void * buf, int64_t count, MPI_Datatype mdtype, int root); /** * \brief allreduce, same interface as MPI_Allreduce, but excluding the comm */ void allred(void * inbuf, void * outbuf, int64_t count, MPI_Datatype mdtype, MPI_Op op); /** * \brief reduce, same interface as MPI_Reduce, but excluding the comm */ void red(void * inbuf, void * outbuf, int64_t count, MPI_Datatype mdtype, MPI_Op op, int root); /** * \brief performs all-to-all-v with 64-bit integer counts and offset on arbitrary * length types (datum_size), and uses point-to-point when all-to-all-v sparse * \param[in] send_buffer data to send * \param[in] send_counts number of datums to send to each process * \param[in] send_displs displacements of datum sets in sen_buffer * \param[in] datum_size size of MPI_datatype to use * \param[in,out] recv_buffer data to recv * \param[in] recv_counts number of datums to recv to each process * \param[in] recv_displs displacements of datum sets in sen_buffer */ void all_to_allv(void * send_buffer, int64_t const * send_counts, int64_t const * send_displs, int64_t datum_size, void * recv_buffer, int64_t const * recv_counts, int64_t const * recv_displs); }; int alloc_ptr(int64_t len, void ** const ptr); int mst_alloc_ptr(int64_t len, void ** const ptr); void * alloc(int64_t len); void * mst_alloc(int64_t len); int cdealloc(void * ptr); void memprof_dealloc(void * ptr); char * get_default_inds(int order, int start_index=0); void cvrt_idx(int order, int64_t const * lens, int64_t idx, int64_t ** idx_arr); void cvrt_idx(int order, int64_t const * lens, int64_t idx, int64_t * idx_arr); void cvrt_idx(int order, int64_t const * lens, int64_t const * idx_arr, int64_t * idx); /** * \brief gives a datatype for arbitrary datum_size, errors if exceeding 32-bits * * \param[in] count number of elements we want to communicate * \param[in] datum_size element size * \param[in] dt new datatype to pass to MPI routine * \return whether the datatype is custom and needs to be freed */ bool get_mpi_dt(int64_t count, int64_t datum_size, MPI_Datatype & dt); /** * \brief compute prefix sum * \param[in] n integer length of array * \param[in] A array of input data of size n * \param[in,out] B initially zero array of size n, on output B[i] = sum_{j=0}^i/stride A[j*stride] */ template <typename dtype> void parallel_postfix(int64_t n, int64_t stride, dtype * B){ if ((n+stride-1)/stride <= 2){ if ((n+stride-1)/stride == 2) B[stride] += B[0]; } else { int64_t stride2 = 2*stride; #ifdef _OPENMP #pragma omp parallel for #endif for (int64_t i=stride; i<n; i+=stride2){ B[i] = B[i]+B[i-stride]; } parallel_postfix(n-stride, stride2, B+stride); #ifdef _OPENMP #pragma omp parallel for #endif for (int64_t i=stride; i<n-stride; i+=stride2){ B[i+stride] += B[i]; } } } /** * \brief compute prefix sum * \param[in] n integer length of array * \param[in] A array of input data of size n * \param[in,out] B initially zero array of size n, on output B[i] = sum_{j=0}^i/stride-1 A[j*stride] */ template <typename dtype> void parallel_prefix(int64_t n, int64_t stride, dtype * B){ if (n/stride < 2){ if ((n-1)/stride >= 1) B[stride] = B[0]; B[0] = 0.; } else { int64_t stride2 = 2*stride; #ifdef _OPENMP #pragma omp parallel for #endif for (int64_t i=stride; i<n; i+=stride2){ B[i] = B[i]+B[i-stride]; } int64_t nsub = (n+stride-1)/stride; if (nsub % 2 != 0){ B[(nsub-1)*stride] = B[(nsub-2)*stride]; } parallel_prefix(n-stride, stride2, B+stride); if (nsub % 2 != 0){ B[(nsub-1)*stride] += B[(nsub-2)*stride]; } #ifdef _OPENMP #pragma omp parallel for #endif for (int64_t i=stride; i<n; i+=stride2){ dtype num = B[i-stride]; B[i-stride] = B[i]; B[i] += num; } } } /** * \brief compute prefix sum * \param[in] n integer length of array * \param[in] A array of input data of size n * \param[in,out] B initially zero array of size n, on output B[i] = sum_{j=0}^i-1 A[j] */ template <typename dtype> void prefix(int64_t n, dtype const * A, dtype * B){ #pragma omp parallel for for (int64_t i=0; i<n; i++){ B[i] = A[i]; } CTF_int::parallel_prefix<dtype>(n, 1, B); } } #endif
Parallel.h
#pragma once #include <ATen/ATen.h> #include <atomic> #include <cstddef> #include <exception> #ifdef _OPENMP #include <omp.h> #endif namespace at { namespace internal { // This parameter is heuristically chosen to determine the minimum number of // work that warrants paralellism. For example, when summing an array, it is // deemed inefficient to parallelise over arrays shorter than 32768. Further, // no parallel algorithm (such as parallel_reduce) should split work into // smaller than GRAIN_SIZE chunks. constexpr int64_t GRAIN_SIZE = 32768; } // namespace internal inline int64_t divup(int64_t x, int64_t y) { return (x + y - 1) / y; } inline int get_max_threads() { #ifdef _OPENMP return omp_get_max_threads(); #else return 1; #endif } inline int get_thread_num() { #ifdef _OPENMP return omp_get_thread_num(); #else return 0; #endif } inline bool in_parallel_region() { #ifdef _OPENMP return omp_in_parallel(); #else return false; #endif } template <class F> inline void parallel_for( const int64_t begin, const int64_t end, const int64_t grain_size, const F& f) { #ifdef _OPENMP std::atomic_flag err_flag = ATOMIC_FLAG_INIT; std::exception_ptr eptr; #pragma omp parallel if (!omp_in_parallel() && ((end - begin) >= grain_size)) { int64_t num_threads = omp_get_num_threads(); int64_t tid = omp_get_thread_num(); int64_t chunk_size = divup((end - begin), num_threads); int64_t begin_tid = begin + tid * chunk_size; if (begin_tid < end) { try { f(begin_tid, std::min(end, chunk_size + begin_tid)); } catch (...) { if (!err_flag.test_and_set()) { eptr = std::current_exception(); } } } } if (eptr) { std::rethrow_exception(eptr); } #else if (begin < end) { f(begin, end); } #endif } /* parallel_reduce begin: index at which to start applying reduction end: index at which to stop applying reduction grain_size: number of elements per chunk. impacts number of elements in intermediate results tensor and degree of parallelization. ident: identity for binary combination function sf. sf(ident, x) needs to return x. f: function for reduction over a chunk. f needs to be of signature scalar_t f(int64_t partial_begin, int64_t partial_end, scalar_t identifiy) sf: function to combine two partial results. sf needs to be of signature scalar_t sf(scalar_t x, scalar_t y) For example, you might have a tensor of 10000 entires and want to sum together all the elements. Parallel_reduce with a grain_size of 2500 will then allocate an intermediate result tensor with 4 elements. Then it will execute the function "f" you provide and pass the beginning and end index of these chunks, so 0-24999, 2500-4999, etc. and the combination identity. It will then write out the result from each of these chunks into the intermediate result tensor. After that it'll reduce the partial results from each chunk into a single number using the combination function sf and the identity ident. For a total summation this would be "+" and 0 respectively. This is similar to tbb's approach [1], where you need to provide a function to accumulate a subrange, a function to combine two partial results and an identity. [1] https://software.intel.com/en-us/node/506154 */ template <class scalar_t, class F, class SF> inline scalar_t parallel_reduce( const int64_t begin, const int64_t end, const int64_t grain_size, const scalar_t ident, const F f, const SF sf) { if (get_num_threads() == 1) { return f(begin, end, ident); } else { const int64_t num_results = divup((end - begin), grain_size); std::vector<scalar_t> results(num_results); scalar_t* results_data = results.data(); #pragma omp parallel for if ((end - begin) >= grain_size) for (int64_t id = 0; id < num_results; id++) { int64_t i = begin + id * grain_size; results_data[id] = f(i, i + std::min(end - i, grain_size), ident); } return std::accumulate( results_data, results_data + results.size(), ident, sf); } } } // namespace at
convolution_1x1_pack1to4_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv1x1s1_sgemm_pack1to4_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, 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_pack1to4_int8_neon(bottom_im2col, top_blob, kernel, opt); } static void conv1x1s2_pack1to4_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, 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; 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 signed char* r0 = bottom_blob.channel(p); signed char* outptr = bottom_blob_shrinked.channel(p); for (int i = 0; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { outptr[0] = r0[0]; outptr[1] = r0[2]; outptr[2] = r0[4]; outptr[3] = r0[6]; r0 += 8; outptr += 4; } for (; j + 1 < outw; j += 2) { outptr[0] = r0[0]; outptr[1] = r0[2]; r0 += 4; outptr += 2; } for (; j < outw; j++) { outptr[0] = r0[0]; r0 += 2; outptr += 1; } r0 += tailstep; } } conv1x1s1_sgemm_pack1to4_int8_neon(bottom_blob_shrinked, top_blob, kernel, opt); }
pst_fmt_plug.c
/* PST cracker patch for JtR. Hacked together during July of 2012 by * Dhiru Kholia <dhiru.kholia at gmail.com> * * Optimizations and shift to pkzip CRC32 code done by JimF * * 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. * * Uses code from crc32_fmt_plug.c written by JimF */ #if FMT_EXTERNS_H extern struct fmt_main fmt_pst; #elif FMT_REGISTERS_H john_register_one(&fmt_pst); #else #include <string.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "crc32.h" #if !FAST_FORMATS_OMP #undef _OPENMP #endif #ifdef _OPENMP #include <omp.h> #ifdef __MIC__ #ifndef OMP_SCALE #define OMP_SCALE 1024 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 16384 // core i7 no HT #endif #endif static int omp_t = 1; #endif #include "memdbg.h" #define FORMAT_LABEL "PST" #define FORMAT_NAME "custom CRC-32" #define ALGORITHM_NAME "32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 8 #define BINARY_SIZE 4 #define SALT_SIZE 0 #define BINARY_ALIGN sizeof(ARCH_WORD_32) #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 256 static struct fmt_tests tests[] = { {"$pst$a9290513", "openwall"}, /* "jfuck jw" works too ;) */ {"$pst$50e099bc", "password"}, {"$pst$00000000", ""}, {"$pst$e3da3318", "xxx"}, {"$pst$a655dd18", "XYz123"}, {"$pst$29b14070", "thisisalongstring"}, {"$pst$25b44615", "string with space"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out); static void init(struct fmt_main *self) { #if defined (_OPENMP) omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(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) { char *p; if (strncmp(ciphertext, "$pst$", 5)) return 0; p = ciphertext + 5; if (hexlenl(p) != BINARY_SIZE * 2) return 0; return 1; } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, PLAINTEXT_LENGTH+1); } static int cmp_all(void *binary, int count) { ARCH_WORD_32 crc=*((ARCH_WORD_32*)binary), i; for (i = 0; i < count; ++i) if (crc == crypt_out[i]) return 1; return 0; } static int cmp_one(void *binary, int index) { return *((ARCH_WORD_32*)binary) == crypt_out[index]; } static int cmp_exact(char *source, int index) { return 1; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int i; #ifdef _OPENMP #pragma omp parallel for private(i) #endif for (i = 0; i < count; ++i) { CRC32_t crc = 0; unsigned char *p = (unsigned char*)saved_key[i]; while (*p) crc = jtr_crc32(crc, *p++); crypt_out[i] = crc; } return count; } static void *get_binary(char *ciphertext) { static ARCH_WORD_32 *out; if (!out) out = mem_alloc_tiny(sizeof(ARCH_WORD_32), MEM_ALIGN_WORD); sscanf(&ciphertext[5], "%x", out); return out; } static char *get_key(int index) { return saved_key[index]; } static int get_hash_0(int index) { return crypt_out[index] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index] & PH_MASK_6; } struct fmt_main fmt_pst = { { 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, #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_TRUNC | FMT_8_BIT | FMT_NOT_EXACT, { NULL }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, 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, 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 */
par_2s_interp.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_parcsr_ls.h" /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildModExtInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildModPartialExtInterpHost( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr ) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A); hypre_ParCSRCommHandle *comm_handle = NULL; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ 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_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); /*HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt total_global_cpts; HYPRE_BigInt total_old_global_cpts; /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /* Intermediate matrices */ hypre_ParCSRMatrix *As_FF, *As_FC, *W; HYPRE_Real *D_q, *D_w; HYPRE_Real *D_q_offd = NULL; hypre_CSRMatrix *As_FF_diag; hypre_CSRMatrix *As_FF_offd; hypre_CSRMatrix *As_FC_diag; hypre_CSRMatrix *As_FC_offd; hypre_CSRMatrix *W_diag; hypre_CSRMatrix *W_offd; HYPRE_Int *As_FF_diag_i; HYPRE_Int *As_FF_diag_j; HYPRE_Int *As_FF_offd_i; HYPRE_Int *As_FF_offd_j; HYPRE_Int *As_FC_diag_i; HYPRE_Int *As_FC_offd_i; HYPRE_Int *W_diag_i; HYPRE_Int *W_offd_i; HYPRE_Int *W_diag_j; HYPRE_Int *W_offd_j; HYPRE_Real *As_FF_diag_data; HYPRE_Real *As_FF_offd_data; HYPRE_Real *As_FC_diag_data; HYPRE_Real *As_FC_offd_data; HYPRE_Real *W_diag_data; HYPRE_Real *W_offd_data; HYPRE_Real *buf_data = NULL; HYPRE_BigInt *col_map_offd_P = NULL; HYPRE_BigInt *new_col_map_offd = NULL; HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int num_cols_A_FF_offd; HYPRE_Int new_ncols_P_offd; HYPRE_Int num_cols_P_offd; HYPRE_Int *P_marker = NULL; //HYPRE_Int *dof_func_offd = NULL; /* Loop variables */ HYPRE_Int index; HYPRE_Int i, j; HYPRE_Int *cpt_array; HYPRE_Int *new_fpt_array; HYPRE_Int *start_array; HYPRE_Int *new_fine_to_fine; HYPRE_Int start, stop, startf, stopf, startnewf, stopnewf; HYPRE_Int cnt_diag, cnt_offd, row, c_pt, fpt; HYPRE_Int startc, num_sends; /* Definitions */ //HYPRE_Real wall_time; HYPRE_Int n_Cpts, n_Fpts, n_old_Cpts, n_new_Fpts; HYPRE_Int num_threads = hypre_NumThreads(); //if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1]; if (my_id == (num_procs -1)) total_old_global_cpts = num_old_cpts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); n_Cpts = num_cpts_global[1]-num_cpts_global[0]; n_old_Cpts = num_old_cpts_global[1]-num_old_cpts_global[0]; hypre_ParCSRMatrixGenerateFFFC3(A, CF_marker, num_cpts_global, S, &As_FC, &As_FF); As_FC_diag = hypre_ParCSRMatrixDiag(As_FC); As_FC_diag_i = hypre_CSRMatrixI(As_FC_diag); As_FC_diag_data = hypre_CSRMatrixData(As_FC_diag); As_FC_offd = hypre_ParCSRMatrixOffd(As_FC); As_FC_offd_i = hypre_CSRMatrixI(As_FC_offd); As_FC_offd_data = hypre_CSRMatrixData(As_FC_offd); As_FF_diag = hypre_ParCSRMatrixDiag(As_FF); As_FF_diag_i = hypre_CSRMatrixI(As_FF_diag); As_FF_diag_j = hypre_CSRMatrixJ(As_FF_diag); As_FF_diag_data = hypre_CSRMatrixData(As_FF_diag); As_FF_offd = hypre_ParCSRMatrixOffd(As_FF); As_FF_offd_i = hypre_CSRMatrixI(As_FF_offd); As_FF_offd_j = hypre_CSRMatrixJ(As_FF_offd); As_FF_offd_data = hypre_CSRMatrixData(As_FF_offd); n_new_Fpts = hypre_CSRMatrixNumRows(As_FF_diag); n_Fpts = hypre_CSRMatrixNumRows(As_FC_diag); n_new_Fpts = n_old_Cpts - n_Cpts; num_cols_A_FF_offd = hypre_CSRMatrixNumCols(As_FF_offd); D_q = hypre_CTAlloc(HYPRE_Real, n_Fpts, memory_location_P); new_fine_to_fine = hypre_CTAlloc(HYPRE_Int, n_new_Fpts, HYPRE_MEMORY_HOST); D_w = hypre_CTAlloc(HYPRE_Real, n_new_Fpts, memory_location_P); cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); new_fpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); start_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,startf,stopf,startnewf,stopnewf,row,fpt) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Real beta, gamma; start = (n_fine/num_threads)*my_thread_num; if (my_thread_num == num_threads-1) { stop = n_fine; } else { stop = (n_fine/num_threads)*(my_thread_num+1); } start_array[my_thread_num+1] = stop; row = 0; for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { cpt_array[my_thread_num]++; } else if (CF_marker[i] == -2) { new_fpt_array[my_thread_num]++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { for (i=1; i < num_threads; i++) { cpt_array[i] += cpt_array[i-1]; new_fpt_array[i] += new_fpt_array[i-1]; } /*if (num_functions > 1) { HYPRE_Int *int_buf_data = NULL; HYPRE_Int num_sends, startc; HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, memory_location_P); index = 0; num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), memory_location_P); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data, memory_location_P); }*/ } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num > 0) { startf = start - cpt_array[my_thread_num-1]; } else { startf = 0; } if (my_thread_num < num_threads-1) { stopf = stop - cpt_array[my_thread_num]; } else { stopf = n_Fpts; } /* Create D_q = D_beta */ for (i=startf; i < stopf; i++) { for (j=As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++) { D_q[i] += As_FC_diag_data[j]; } for (j=As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++) { D_q[i] += As_FC_offd_data[j]; } } row = 0; if (my_thread_num) row = new_fpt_array[my_thread_num-1]; fpt = startf; for (i=start; i < stop; i++) { if (CF_marker[i] == -2) { new_fine_to_fine[row++] = fpt++; } else if (CF_marker[i] < 0) { fpt++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (num_cols_A_FF_offd) { D_q_offd = hypre_CTAlloc(HYPRE_Real, num_cols_A_FF_offd, memory_location_P); } index = 0; comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF); if (!comm_pkg) { hypre_MatvecCommPkgCreate(As_FF); comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), memory_location_P); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { buf_data[index++] = D_q[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data, D_q_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /* Create D_w = D_alpha + D_gamma */ row = 0; if (my_thread_num) row = new_fpt_array[my_thread_num-1]; for (i=start; i < stop; i++) { if (CF_marker[i] == -2) { /*if (num_functions > 1) { HYPRE_Int jA, jC, jS; jC = A_diag_i[i]; for (j=S_diag_i[i]; j < S_diag_i[i+1]; j++) { jS = S_diag_j[j]; jA = A_diag_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func[jA]) { D_w[row] += A_diag_data[jC++]; } else jC++; jA = A_diag_j[jC]; } jC++; } for (j=jC; j < A_diag_i[i+1]; j++) { if (dof_func[i] == dof_func[A_diag_j[j]]) D_w[row] += A_diag_data[j]; } jC = A_offd_i[i]; for (j=S_offd_i[i]; j < S_offd_i[i+1]; j++) { jS = S_offd_j[j]; jA = A_offd_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func_offd[jA]) { D_w[row] += A_offd_data[jC++]; } else jC++; jA = A_offd_j[jC]; } jC++; } for (j=jC; j < A_offd_i[i+1]; j++) { if (dof_func[i] == dof_func_offd[A_offd_j[j]]) D_w[row] += A_offd_data[j]; } row++; } else*/ { for (j=A_diag_i[i]; j < A_diag_i[i+1]; j++) { D_w[row] += A_diag_data[j]; } for (j=A_offd_i[i]; j < A_offd_i[i+1]; j++) { D_w[row] += A_offd_data[j]; } for (j=As_FF_diag_i[row]+1; j < As_FF_diag_i[row+1]; j++) { if (D_q[As_FF_diag_j[j]]) D_w[row] -= As_FF_diag_data[j]; } for (j=As_FF_offd_i[row]; j < As_FF_offd_i[row+1]; j++) { if (D_q_offd[As_FF_offd_j[j]]) D_w[row] -= As_FF_offd_data[j]; } D_w[row] -= D_q[new_fine_to_fine[row]]; row++; } } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif startnewf = 0; if (my_thread_num) startnewf = new_fpt_array[my_thread_num-1]; stopnewf = new_fpt_array[my_thread_num]; for (i=startnewf; i<stopnewf; i++) { j = As_FF_diag_i[i]; if (D_w[i]) { beta = 1.0/D_w[i]; As_FF_diag_data[j] = beta*D_q[new_fine_to_fine[i]]; for (j=As_FF_diag_i[i]+1; j < As_FF_diag_i[i+1]; j++) As_FF_diag_data[j] *= beta; for (j=As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++) As_FF_offd_data[j] *= beta; } } for (i=startf; i<stopf; i++) { if (D_q[i]) gamma = -1.0/D_q[i]; else gamma = 0.0; for (j=As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++) As_FC_diag_data[j] *= gamma; for (j=As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++) As_FC_offd_data[j] *= gamma; } } /* end parallel region */ W = hypre_ParMatmul(As_FF, As_FC); W_diag = hypre_ParCSRMatrixDiag(W); W_offd = hypre_ParCSRMatrixOffd(W); W_diag_i = hypre_CSRMatrixI(W_diag); W_diag_j = hypre_CSRMatrixJ(W_diag); W_diag_data = hypre_CSRMatrixData(W_diag); W_offd_i = hypre_CSRMatrixI(W_offd); W_offd_j = hypre_CSRMatrixJ(W_offd); W_offd_data = hypre_CSRMatrixData(W_offd); num_cols_P_offd = hypre_CSRMatrixNumCols(W_offd); /*----------------------------------------------------------------------- * Intialize data for P *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_old_Cpts+1, memory_location_P); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_old_Cpts+1, memory_location_P); P_diag_size = n_Cpts + hypre_CSRMatrixI(W_diag)[n_new_Fpts]; P_offd_size = hypre_CSRMatrixI(W_offd)[n_new_Fpts]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, memory_location_P); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, memory_location_P); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, memory_location_P); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,startnewf,stopnewf,c_pt,row,cnt_diag,cnt_offd) #endif { HYPRE_Int rowp; HYPRE_Int my_thread_num = hypre_GetThreadNum(); start = start_array[my_thread_num]; stop = start_array[my_thread_num+1]; if (my_thread_num > 0) c_pt = cpt_array[my_thread_num-1]; else c_pt = 0; row = 0; if (my_thread_num) row = new_fpt_array[my_thread_num-1]; rowp = row; if (my_thread_num > 0) rowp = row+cpt_array[my_thread_num-1]; cnt_diag = W_diag_i[row]+c_pt; cnt_offd = W_offd_i[row]; for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { rowp++; P_diag_j[cnt_diag] = c_pt++; P_diag_data[cnt_diag++] = 1.0; P_diag_i[rowp] = cnt_diag; P_offd_i[rowp] = cnt_offd; } else if (CF_marker[i] == -2) { rowp++; for (j=W_diag_i[row]; j < W_diag_i[row+1]; j++) { P_diag_j[cnt_diag] = W_diag_j[j]; P_diag_data[cnt_diag++] = W_diag_data[j]; } for (j=W_offd_i[row]; j < W_offd_i[row+1]; j++) { P_offd_j[cnt_offd] = W_offd_j[j]; P_offd_data[cnt_offd++] = W_offd_data[j]; } row++; P_diag_i[rowp] = cnt_diag; P_offd_i[rowp] = cnt_offd; } } } /* end parallel region */ /*----------------------------------------------------------------------- * Create matrix *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, num_cols_P_offd, P_diag_i[n_old_Cpts], P_offd_i[n_old_Cpts]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; hypre_ParCSRMatrixColMapOffd(P) = hypre_ParCSRMatrixColMapOffd(W); hypre_ParCSRMatrixColMapOffd(W) = NULL; hypre_CSRMatrixMemoryLocation(P_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(P_offd) = memory_location_P; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { HYPRE_Int *map; hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_old_Cpts]; P_offd_size = P_offd_i[n_old_Cpts]; col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P); if (num_cols_P_offd) { P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST); for (i=0; i < P_offd_size; i++) { P_marker[P_offd_j[i]] = 1; } new_ncols_P_offd = 0; for (i=0; i < num_cols_P_offd; i++) if (P_marker[i]) new_ncols_P_offd++; new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_ncols_P_offd, HYPRE_MEMORY_HOST); map = hypre_CTAlloc(HYPRE_Int, new_ncols_P_offd, HYPRE_MEMORY_HOST); index = 0; for (i=0; i < num_cols_P_offd; i++) if (P_marker[i]) { new_col_map_offd[index] = col_map_offd_P[i]; map[index++] = i; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < P_offd_size; i++) { P_offd_j[i] = hypre_BinarySearch(map, P_offd_j[i], new_ncols_P_offd); } hypre_TFree(col_map_offd_P, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd; hypre_CSRMatrixNumCols(P_offd) = new_ncols_P_offd; hypre_TFree(map, HYPRE_MEMORY_HOST); } } hypre_MatvecCommPkgCreate(P); *P_ptr = P; /* Deallocate memory */ hypre_TFree(D_q, memory_location_P); hypre_TFree(D_q_offd, memory_location_P); hypre_TFree(D_w, memory_location_P); //hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); hypre_TFree(cpt_array, HYPRE_MEMORY_HOST); hypre_TFree(new_fpt_array, HYPRE_MEMORY_HOST); hypre_TFree(start_array, HYPRE_MEMORY_HOST); hypre_TFree(new_fine_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(buf_data, memory_location_P); hypre_ParCSRMatrixDestroy(As_FF); hypre_ParCSRMatrixDestroy(As_FC); hypre_ParCSRMatrixDestroy(W); return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGBuildModPartialExtInterp( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("PartialExtInterp"); #endif HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) ); HYPRE_Int ierr = 0; if (exec == HYPRE_EXEC_HOST) { ierr = hypre_BoomerAMGBuildModPartialExtInterpHost(A, CF_marker, S, num_cpts_global, num_old_cpts_global, num_functions, dof_func, debug_flag, trunc_factor, max_elmts, P_ptr); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) else { ierr = hypre_BoomerAMGBuildModPartialExtInterpDevice(A, CF_marker, S, num_cpts_global, num_old_cpts_global, debug_flag, trunc_factor, max_elmts, P_ptr); } #endif #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return ierr; } HYPRE_Int hypre_BoomerAMGBuildModPartialExtPEInterpHost( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A); hypre_ParCSRCommHandle *comm_handle = NULL; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ 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_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt total_global_cpts; HYPRE_BigInt total_old_global_cpts; /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /* Intermediate matrices */ hypre_ParCSRMatrix *As_FF, *As_FC, *W; HYPRE_Real *D_q, *D_w, *D_lambda, *D_inv, *D_tau; HYPRE_Real *D_lambda_offd = NULL, *D_inv_offd = NULL; hypre_CSRMatrix *As_FF_diag; hypre_CSRMatrix *As_FF_offd; hypre_CSRMatrix *As_FC_diag; hypre_CSRMatrix *As_FC_offd; hypre_CSRMatrix *W_diag; hypre_CSRMatrix *W_offd; HYPRE_Int *As_FF_diag_i; HYPRE_Int *As_FF_diag_j; HYPRE_Int *As_FF_offd_i; HYPRE_Int *As_FF_offd_j; HYPRE_Int *As_FC_diag_i; HYPRE_Int *As_FC_offd_i; HYPRE_Int *W_diag_i; HYPRE_Int *W_offd_i; HYPRE_Int *W_diag_j; HYPRE_Int *W_offd_j; HYPRE_Real *As_FF_diag_data; HYPRE_Real *As_FF_offd_data; HYPRE_Real *As_FC_diag_data; HYPRE_Real *As_FC_offd_data; HYPRE_Real *W_diag_data; HYPRE_Real *W_offd_data; HYPRE_Real *buf_data = NULL; HYPRE_BigInt *col_map_offd_P = NULL; HYPRE_BigInt *new_col_map_offd = NULL; HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int num_cols_A_FF_offd; HYPRE_Int new_ncols_P_offd; HYPRE_Int num_cols_P_offd; HYPRE_Int *P_marker = NULL; HYPRE_Int *dof_func_offd = NULL; /* Loop variables */ HYPRE_Int index; HYPRE_Int i, j; HYPRE_Int *cpt_array; HYPRE_Int *new_fpt_array; HYPRE_Int *start_array; HYPRE_Int *new_fine_to_fine; HYPRE_Int start, stop, startf, stopf, startnewf, stopnewf; HYPRE_Int cnt_diag, cnt_offd, row, c_pt, fpt; HYPRE_Int startc, num_sends; /* Definitions */ //HYPRE_Real wall_time; HYPRE_Int n_Cpts, n_Fpts, n_old_Cpts, n_new_Fpts; HYPRE_Int num_threads = hypre_NumThreads(); //if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1]; if (my_id == (num_procs -1)) total_old_global_cpts = num_old_cpts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); n_Cpts = num_cpts_global[1]-num_cpts_global[0]; n_old_Cpts = num_old_cpts_global[1]-num_old_cpts_global[0]; hypre_ParCSRMatrixGenerateFFFCD3(A, CF_marker, num_cpts_global, S, &As_FC, &As_FF, &D_lambda); As_FC_diag = hypre_ParCSRMatrixDiag(As_FC); As_FC_diag_i = hypre_CSRMatrixI(As_FC_diag); As_FC_diag_data = hypre_CSRMatrixData(As_FC_diag); As_FC_offd = hypre_ParCSRMatrixOffd(As_FC); As_FC_offd_i = hypre_CSRMatrixI(As_FC_offd); As_FC_offd_data = hypre_CSRMatrixData(As_FC_offd); As_FF_diag = hypre_ParCSRMatrixDiag(As_FF); As_FF_diag_i = hypre_CSRMatrixI(As_FF_diag); As_FF_diag_j = hypre_CSRMatrixJ(As_FF_diag); As_FF_diag_data = hypre_CSRMatrixData(As_FF_diag); As_FF_offd = hypre_ParCSRMatrixOffd(As_FF); As_FF_offd_i = hypre_CSRMatrixI(As_FF_offd); As_FF_offd_j = hypre_CSRMatrixJ(As_FF_offd); As_FF_offd_data = hypre_CSRMatrixData(As_FF_offd); n_new_Fpts = hypre_CSRMatrixNumRows(As_FF_diag); n_Fpts = hypre_CSRMatrixNumRows(As_FC_diag); n_new_Fpts = n_old_Cpts - n_Cpts; num_cols_A_FF_offd = hypre_CSRMatrixNumCols(As_FF_offd); D_q = hypre_CTAlloc(HYPRE_Real, n_Fpts, memory_location_P); D_inv = hypre_CTAlloc(HYPRE_Real, n_Fpts, memory_location_P); new_fine_to_fine = hypre_CTAlloc(HYPRE_Int, n_new_Fpts, HYPRE_MEMORY_HOST); D_w = hypre_CTAlloc(HYPRE_Real, n_new_Fpts, memory_location_P); D_tau = hypre_CTAlloc(HYPRE_Real, n_new_Fpts, memory_location_P); cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); new_fpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); start_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,startf,stopf,startnewf,stopnewf,row,fpt,index) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Real beta, gamma; start = (n_fine/num_threads)*my_thread_num; if (my_thread_num == num_threads-1) { stop = n_fine; } else { stop = (n_fine/num_threads)*(my_thread_num+1); } start_array[my_thread_num+1] = stop; row = 0; for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { cpt_array[my_thread_num]++; } else if (CF_marker[i] == -2) { new_fpt_array[my_thread_num]++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { for (i=1; i < num_threads; i++) { cpt_array[i] += cpt_array[i-1]; new_fpt_array[i] += new_fpt_array[i-1]; } if (num_functions > 1) { HYPRE_Int *int_buf_data = NULL; HYPRE_Int num_sends, startc; HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, memory_location_P); index = 0; num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), memory_location_P); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data, memory_location_P); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num > 0) { startf = start - cpt_array[my_thread_num-1]; } else { startf = 0; } if (my_thread_num < num_threads-1) { stopf = stop - cpt_array[my_thread_num]; } else { stopf = n_Fpts; } /* Create D_q = D_beta, D_inv = 1/(D_q+D_lambda) */ for (i=startf; i < stopf; i++) { for (j=As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++) { D_q[i] += As_FC_diag_data[j]; } for (j=As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++) { D_q[i] += As_FC_offd_data[j]; } if (D_q[i]+D_lambda[i]) D_inv[i] = 1.0/(D_q[i]+D_lambda[i]); } row = 0; if (my_thread_num) row = new_fpt_array[my_thread_num-1]; fpt = startf; for (i=start; i < stop; i++) { if (CF_marker[i] == -2) { new_fine_to_fine[row++] = fpt++; } else if (CF_marker[i] < 0) { fpt++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (num_cols_A_FF_offd) { D_lambda_offd = hypre_CTAlloc(HYPRE_Real, num_cols_A_FF_offd, memory_location_P); D_inv_offd = hypre_CTAlloc(HYPRE_Real, num_cols_A_FF_offd, memory_location_P); } index = 0; comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF); if (!comm_pkg) { hypre_MatvecCommPkgCreate(As_FF); comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), memory_location_P); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { buf_data[index++] = D_lambda[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data, D_lambda_offd); hypre_ParCSRCommHandleDestroy(comm_handle); index = 0; for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { buf_data[index++] = D_inv[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data, D_inv_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /* Create D_tau */ startnewf = 0; if (my_thread_num) startnewf = new_fpt_array[my_thread_num-1]; stopnewf = new_fpt_array[my_thread_num]; for (i=startnewf; i<stopnewf; i++) { for (j=As_FF_diag_i[i]+1; j < As_FF_diag_i[i+1]; j++) { index = As_FF_diag_j[j]; D_tau[i] += As_FF_diag_data[j]*D_lambda[index]*D_inv[index]; } for (j=As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++) { index = As_FF_offd_j[j]; D_tau[i] += As_FF_offd_data[j]*D_lambda_offd[index]*D_inv_offd[index]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /* Create D_w = D_alpha + D_gamma + D_tau */ row = 0; if (my_thread_num) row = new_fpt_array[my_thread_num-1]; for (i=start; i < stop; i++) { if (CF_marker[i] == -2) { if (num_functions > 1) { HYPRE_Int jA, jC, jS; jC = A_diag_i[i]; for (j=S_diag_i[i]; j < S_diag_i[i+1]; j++) { jS = S_diag_j[j]; jA = A_diag_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func[jA]) { D_w[row] += A_diag_data[jC++]; } else jC++; jA = A_diag_j[jC]; } jC++; } for (j=jC; j < A_diag_i[i+1]; j++) { if (dof_func[i] == dof_func[A_diag_j[j]]) D_w[row] += A_diag_data[j]; } jC = A_offd_i[i]; for (j=S_offd_i[i]; j < S_offd_i[i+1]; j++) { jS = S_offd_j[j]; jA = A_offd_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func_offd[jA]) { D_w[row] += A_offd_data[jC++]; } else jC++; jA = A_offd_j[jC]; } jC++; } for (j=jC; j < A_offd_i[i+1]; j++) { if (dof_func[i] == dof_func_offd[A_offd_j[j]]) D_w[row] += A_offd_data[j]; } D_w[row] += D_tau[row]; row++; } else { for (j=A_diag_i[i]; j < A_diag_i[i+1]; j++) { D_w[row] += A_diag_data[j]; } for (j=A_offd_i[i]; j < A_offd_i[i+1]; j++) { D_w[row] += A_offd_data[j]; } for (j=As_FF_diag_i[row]+1; j < As_FF_diag_i[row+1]; j++) { if (D_inv[As_FF_diag_j[j]]) D_w[row] -= As_FF_diag_data[j]; } for (j=As_FF_offd_i[row]; j < As_FF_offd_i[row+1]; j++) { if (D_inv_offd[As_FF_offd_j[j]]) D_w[row] -= As_FF_offd_data[j]; } D_w[row] += D_tau[row] - D_q[new_fine_to_fine[row]]; row++; } } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif startnewf = 0; if (my_thread_num) startnewf = new_fpt_array[my_thread_num-1]; stopnewf = new_fpt_array[my_thread_num]; for (i=startnewf; i<stopnewf; i++) { j = As_FF_diag_i[i]; if (D_w[i]) { beta = -1.0/D_w[i]; As_FF_diag_data[j] = beta*(D_q[new_fine_to_fine[i]]+D_lambda[new_fine_to_fine[i]]); for (j=As_FF_diag_i[i]+1; j < As_FF_diag_i[i+1]; j++) As_FF_diag_data[j] *= beta; for (j=As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++) As_FF_offd_data[j] *= beta; } } for (i=startf; i<stopf; i++) { gamma = D_inv[i]; for (j=As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++) As_FC_diag_data[j] *= gamma; for (j=As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++) As_FC_offd_data[j] *= gamma; } } /* end parallel region */ W = hypre_ParMatmul(As_FF, As_FC); W_diag = hypre_ParCSRMatrixDiag(W); W_offd = hypre_ParCSRMatrixOffd(W); W_diag_i = hypre_CSRMatrixI(W_diag); W_diag_j = hypre_CSRMatrixJ(W_diag); W_diag_data = hypre_CSRMatrixData(W_diag); W_offd_i = hypre_CSRMatrixI(W_offd); W_offd_j = hypre_CSRMatrixJ(W_offd); W_offd_data = hypre_CSRMatrixData(W_offd); num_cols_P_offd = hypre_CSRMatrixNumCols(W_offd); /*----------------------------------------------------------------------- * Intialize data for P *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_old_Cpts+1, memory_location_P); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_old_Cpts+1, memory_location_P); P_diag_size = n_Cpts + hypre_CSRMatrixI(W_diag)[n_new_Fpts]; P_offd_size = hypre_CSRMatrixI(W_offd)[n_new_Fpts]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, memory_location_P); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, memory_location_P); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, memory_location_P); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,c_pt,row,cnt_diag,cnt_offd) #endif { HYPRE_Int rowp; HYPRE_Int my_thread_num = hypre_GetThreadNum(); start = start_array[my_thread_num]; stop = start_array[my_thread_num+1]; if (my_thread_num > 0) c_pt = cpt_array[my_thread_num-1]; else c_pt = 0; row = 0; if (my_thread_num) row = new_fpt_array[my_thread_num-1]; rowp = row; if (my_thread_num > 0) rowp = row+cpt_array[my_thread_num-1]; cnt_diag = W_diag_i[row]+c_pt; cnt_offd = W_offd_i[row]; for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { rowp++; P_diag_j[cnt_diag] = c_pt++; P_diag_data[cnt_diag++] = 1.0; P_diag_i[rowp] = cnt_diag; P_offd_i[rowp] = cnt_offd; } else if (CF_marker[i] == -2) { rowp++; for (j=W_diag_i[row]; j < W_diag_i[row+1]; j++) { P_diag_j[cnt_diag] = W_diag_j[j]; P_diag_data[cnt_diag++] = W_diag_data[j]; } for (j=W_offd_i[row]; j < W_offd_i[row+1]; j++) { P_offd_j[cnt_offd] = W_offd_j[j]; P_offd_data[cnt_offd++] = W_offd_data[j]; } row++; P_diag_i[rowp] = cnt_diag; P_offd_i[rowp] = cnt_offd; } } } /* end parallel region */ /*----------------------------------------------------------------------- * Create matrix *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, num_cols_P_offd, P_diag_i[n_old_Cpts], P_offd_i[n_old_Cpts]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; hypre_ParCSRMatrixColMapOffd(P) = hypre_ParCSRMatrixColMapOffd(W); hypre_ParCSRMatrixColMapOffd(W) = NULL; hypre_CSRMatrixMemoryLocation(P_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(P_offd) = memory_location_P; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { HYPRE_Int *map; hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_old_Cpts]; P_offd_size = P_offd_i[n_old_Cpts]; col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P); if (num_cols_P_offd) { P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST); for (i=0; i < P_offd_size; i++) { P_marker[P_offd_j[i]] = 1; } new_ncols_P_offd = 0; for (i=0; i < num_cols_P_offd; i++) { if (P_marker[i]) { new_ncols_P_offd++; } } new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_ncols_P_offd, HYPRE_MEMORY_HOST); map = hypre_CTAlloc(HYPRE_Int, new_ncols_P_offd, HYPRE_MEMORY_HOST); index = 0; for (i=0; i < num_cols_P_offd; i++) { if (P_marker[i]) { new_col_map_offd[index] = col_map_offd_P[i]; map[index++] = i; } } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < P_offd_size; i++) { P_offd_j[i] = hypre_BinarySearch(map, P_offd_j[i], new_ncols_P_offd); } hypre_TFree(col_map_offd_P, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd; hypre_CSRMatrixNumCols(P_offd) = new_ncols_P_offd; hypre_TFree(map, HYPRE_MEMORY_HOST); } } hypre_MatvecCommPkgCreate(P); *P_ptr = P; /* Deallocate memory */ hypre_TFree(D_q, memory_location_P); hypre_TFree(D_inv, memory_location_P); hypre_TFree(D_inv_offd, memory_location_P); hypre_TFree(D_lambda, memory_location_P); hypre_TFree(D_lambda_offd, memory_location_P); hypre_TFree(D_tau, memory_location_P); hypre_TFree(D_w, memory_location_P); hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); hypre_TFree(cpt_array, HYPRE_MEMORY_HOST); hypre_TFree(new_fpt_array, HYPRE_MEMORY_HOST); hypre_TFree(start_array, HYPRE_MEMORY_HOST); hypre_TFree(new_fine_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(buf_data, memory_location_P); hypre_ParCSRMatrixDestroy(As_FF); hypre_ParCSRMatrixDestroy(As_FC); hypre_ParCSRMatrixDestroy(W); return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGBuildModPartialExtPEInterp( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("PartialExtPEInterp"); #endif HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) ); HYPRE_Int ierr = 0; if (exec == HYPRE_EXEC_HOST) { ierr = hypre_BoomerAMGBuildModPartialExtPEInterpHost(A, CF_marker, S, num_cpts_global, num_old_cpts_global, num_functions, dof_func, debug_flag, trunc_factor, max_elmts, P_ptr); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) else { ierr = hypre_BoomerAMGBuildModPartialExtPEInterpDevice(A, CF_marker, S, num_cpts_global, num_old_cpts_global, debug_flag, trunc_factor, max_elmts, P_ptr); } #endif #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return ierr; }
GB_binop__bor_uint8.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__bor_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__bor_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__bor_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__bor_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bor_uint8) // A*D function (colscale): GB (_AxD__bor_uint8) // D*A function (rowscale): GB (_DxB__bor_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__bor_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__bor_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bor_uint8) // C=scalar+B GB (_bind1st__bor_uint8) // C=scalar+B' GB (_bind1st_tran__bor_uint8) // C=A+scalar GB (_bind2nd__bor_uint8) // C=A'+scalar GB (_bind2nd_tran__bor_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = (aij) | (bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_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) \ uint8_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) \ uint8_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) \ uint8_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_BOR || GxB_NO_UINT8 || GxB_NO_BOR_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bor_uint8) ( 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__bor_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #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__bor_uint8) ( 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 uint8_t uint8_t bwork = (*((uint8_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__bor_uint8) ( 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 uint8_t *restrict Cx = (uint8_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__bor_uint8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_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__bor_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_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__bor_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__bor_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bor_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__bor_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bor_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = (x) | (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bor_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = (aij) | (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) | (aij) ; \ } GrB_Info GB (_bind1st_tran__bor_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) | (y) ; \ } GrB_Info GB (_bind2nd_tran__bor_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
3d7pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * 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, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (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); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][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] = 4; tile_size[1] = 4; tile_size[2] = 32; tile_size[3] = 32; 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; const double alpha = 0.0876; const double beta = 0.0765; // 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); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-15,16)),ceild(4*t2-Nz-28,32));t3<=min(min(min(floord(4*t2+Ny,32),floord(Nt+Ny-4,32)),floord(2*t1+Ny+1,32)),floord(4*t1-4*t2+Nz+Ny-1,32));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(4*t2-Nz-28,32)),ceild(32*t3-Ny-28,32));t4<=min(min(min(min(floord(4*t2+Nx,32),floord(Nt+Nx-4,32)),floord(2*t1+Nx+1,32)),floord(32*t3+Nx+28,32)),floord(4*t1-4*t2+Nz+Nx-1,32));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),32*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),32*t3+30),32*t4+30),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) { lbv=max(32*t4,t5+1); ubv=min(32*t4+31,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* 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]); */ return 0; }
distort.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD IIIII SSSSS TTTTT OOO RRRR TTTTT % % D D I SS T O O R R T % % D D I SSS T O O RRRR T % % D D I SS T O O R R T % % DDDD IIIII SSSSS T OOO R R T % % % % % % MagickCore Image Distortion Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % June 2007 % % % % % % Copyright 1999-2014 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/artifact.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite-private.h" #include "magick/distort.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/hashmap.h" #include "magick/image.h" #include "magick/list.h" #include "magick/matrix.h" #include "magick/memory_.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/registry.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/shear.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/token.h" #include "magick/transform.h" /* Numerous internal routines for image distortions. */ static inline double MagickMin(const double x,const double y) { return( x < y ? x : y); } static inline double MagickMax(const double x,const double y) { return( x > y ? x : y); } static inline void AffineArgsToCoefficients(double *affine) { /* map external sx,ry,rx,sy,tx,ty to internal c0,c2,c4,c1,c3,c5 */ double tmp[4]; /* note indexes 0 and 5 remain unchanged */ tmp[0]=affine[1]; tmp[1]=affine[2]; tmp[2]=affine[3]; tmp[3]=affine[4]; affine[3]=tmp[0]; affine[1]=tmp[1]; affine[4]=tmp[2]; affine[2]=tmp[3]; } static inline void CoefficientsToAffineArgs(double *coeff) { /* map internal c0,c1,c2,c3,c4,c5 to external sx,ry,rx,sy,tx,ty */ double tmp[4]; /* note indexes 0 and 5 remain unchanged */ tmp[0]=coeff[3]; tmp[1]=coeff[1]; tmp[2]=coeff[4]; tmp[3]=coeff[2]; coeff[1]=tmp[0]; coeff[2]=tmp[1]; coeff[3]=tmp[2]; coeff[4]=tmp[3]; } static void InvertAffineCoefficients(const double *coeff,double *inverse) { /* From "Digital Image Warping" by George Wolberg, page 50 */ double determinant; determinant=PerceptibleReciprocal(coeff[0]*coeff[4]-coeff[1]*coeff[3]); inverse[0]=determinant*coeff[4]; inverse[1]=determinant*(-coeff[1]); inverse[2]=determinant*(coeff[1]*coeff[5]-coeff[2]*coeff[4]); inverse[3]=determinant*(-coeff[3]); inverse[4]=determinant*coeff[0]; inverse[5]=determinant*(coeff[2]*coeff[3]-coeff[0]*coeff[5]); } static void InvertPerspectiveCoefficients(const double *coeff, double *inverse) { /* From "Digital Image Warping" by George Wolberg, page 53 */ double determinant; determinant=PerceptibleReciprocal(coeff[0]*coeff[4]-coeff[3]*coeff[1]); inverse[0]=determinant*(coeff[4]-coeff[7]*coeff[5]); inverse[1]=determinant*(coeff[7]*coeff[2]-coeff[1]); inverse[2]=determinant*(coeff[1]*coeff[5]-coeff[4]*coeff[2]); inverse[3]=determinant*(coeff[6]*coeff[5]-coeff[3]); inverse[4]=determinant*(coeff[0]-coeff[6]*coeff[2]); inverse[5]=determinant*(coeff[3]*coeff[2]-coeff[0]*coeff[5]); inverse[6]=determinant*(coeff[3]*coeff[7]-coeff[6]*coeff[4]); inverse[7]=determinant*(coeff[6]*coeff[1]-coeff[0]*coeff[7]); } /* * Polynomial Term Defining Functions * * Order must either be an integer, or 1.5 to produce * the 2 number_valuesal polynomial function... * affine 1 (3) u = c0 + c1*x + c2*y * bilinear 1.5 (4) u = '' + c3*x*y * quadratic 2 (6) u = '' + c4*x*x + c5*y*y * cubic 3 (10) u = '' + c6*x^3 + c7*x*x*y + c8*x*y*y + c9*y^3 * quartic 4 (15) u = '' + c10*x^4 + ... + c14*y^4 * quintic 5 (21) u = '' + c15*x^5 + ... + c20*y^5 * number in parenthesis minimum number of points needed. * Anything beyond quintic, has not been implemented until * a more automated way of determining terms is found. * Note the slight re-ordering of the terms for a quadratic polynomial * which is to allow the use of a bi-linear (order=1.5) polynomial. * All the later polynomials are ordered simply from x^N to y^N */ static size_t poly_number_terms(double order) { /* Return the number of terms for a 2d polynomial */ if ( order < 1 || order > 5 || ( order != floor(order) && (order-1.5) > MagickEpsilon) ) return 0; /* invalid polynomial order */ return((size_t) floor((order+1)*(order+2)/2)); } static double poly_basis_fn(ssize_t n, double x, double y) { /* Return the result for this polynomial term */ switch(n) { case 0: return( 1.0 ); /* constant */ case 1: return( x ); case 2: return( y ); /* affine order = 1 terms = 3 */ case 3: return( x*y ); /* bilinear order = 1.5 terms = 4 */ case 4: return( x*x ); case 5: return( y*y ); /* quadratic order = 2 terms = 6 */ case 6: return( x*x*x ); case 7: return( x*x*y ); case 8: return( x*y*y ); case 9: return( y*y*y ); /* cubic order = 3 terms = 10 */ case 10: return( x*x*x*x ); case 11: return( x*x*x*y ); case 12: return( x*x*y*y ); case 13: return( x*y*y*y ); case 14: return( y*y*y*y ); /* quartic order = 4 terms = 15 */ case 15: return( x*x*x*x*x ); case 16: return( x*x*x*x*y ); case 17: return( x*x*x*y*y ); case 18: return( x*x*y*y*y ); case 19: return( x*y*y*y*y ); case 20: return( y*y*y*y*y ); /* quintic order = 5 terms = 21 */ } return( 0 ); /* should never happen */ } static const char *poly_basis_str(ssize_t n) { /* return the result for this polynomial term */ switch(n) { case 0: return(""); /* constant */ case 1: return("*ii"); case 2: return("*jj"); /* affine order = 1 terms = 3 */ case 3: return("*ii*jj"); /* bilinear order = 1.5 terms = 4 */ case 4: return("*ii*ii"); case 5: return("*jj*jj"); /* quadratic order = 2 terms = 6 */ case 6: return("*ii*ii*ii"); case 7: return("*ii*ii*jj"); case 8: return("*ii*jj*jj"); case 9: return("*jj*jj*jj"); /* cubic order = 3 terms = 10 */ case 10: return("*ii*ii*ii*ii"); case 11: return("*ii*ii*ii*jj"); case 12: return("*ii*ii*jj*jj"); case 13: return("*ii*jj*jj*jj"); case 14: return("*jj*jj*jj*jj"); /* quartic order = 4 terms = 15 */ case 15: return("*ii*ii*ii*ii*ii"); case 16: return("*ii*ii*ii*ii*jj"); case 17: return("*ii*ii*ii*jj*jj"); case 18: return("*ii*ii*jj*jj*jj"); case 19: return("*ii*jj*jj*jj*jj"); case 20: return("*jj*jj*jj*jj*jj"); /* quintic order = 5 terms = 21 */ } return( "UNKNOWN" ); /* should never happen */ } static double poly_basis_dx(ssize_t n, double x, double y) { /* polynomial term for x derivative */ switch(n) { case 0: return( 0.0 ); /* constant */ case 1: return( 1.0 ); case 2: return( 0.0 ); /* affine order = 1 terms = 3 */ case 3: return( y ); /* bilinear order = 1.5 terms = 4 */ case 4: return( x ); case 5: return( 0.0 ); /* quadratic order = 2 terms = 6 */ case 6: return( x*x ); case 7: return( x*y ); case 8: return( y*y ); case 9: return( 0.0 ); /* cubic order = 3 terms = 10 */ case 10: return( x*x*x ); case 11: return( x*x*y ); case 12: return( x*y*y ); case 13: return( y*y*y ); case 14: return( 0.0 ); /* quartic order = 4 terms = 15 */ case 15: return( x*x*x*x ); case 16: return( x*x*x*y ); case 17: return( x*x*y*y ); case 18: return( x*y*y*y ); case 19: return( y*y*y*y ); case 20: return( 0.0 ); /* quintic order = 5 terms = 21 */ } return( 0.0 ); /* should never happen */ } static double poly_basis_dy(ssize_t n, double x, double y) { /* polynomial term for y derivative */ switch(n) { case 0: return( 0.0 ); /* constant */ case 1: return( 0.0 ); case 2: return( 1.0 ); /* affine order = 1 terms = 3 */ case 3: return( x ); /* bilinear order = 1.5 terms = 4 */ case 4: return( 0.0 ); case 5: return( y ); /* quadratic order = 2 terms = 6 */ default: return( poly_basis_dx(n-1,x,y) ); /* weird but true */ } /* NOTE: the only reason that last is not true for 'quadratic' is due to the re-arrangement of terms to allow for 'bilinear' */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A f f i n e T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AffineTransformImage() transforms an image as dictated by the affine matrix. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the AffineTransformImage method is: % % Image *AffineTransformImage(const Image *image, % AffineMatrix *affine_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o affine_matrix: the affine matrix. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AffineTransformImage(const Image *image, const AffineMatrix *affine_matrix,ExceptionInfo *exception) { double distort[6]; Image *deskew_image; /* Affine transform image. */ assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(affine_matrix != (AffineMatrix *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); distort[0]=affine_matrix->sx; distort[1]=affine_matrix->rx; distort[2]=affine_matrix->ry; distort[3]=affine_matrix->sy; distort[4]=affine_matrix->tx; distort[5]=affine_matrix->ty; deskew_image=DistortImage(image,AffineProjectionDistortion,6,distort, MagickTrue,exception); return(deskew_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e n e r a t e C o e f f i c i e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GenerateCoefficients() takes user provided input arguments and generates % the coefficients, needed to apply the specific distortion for either % distorting images (generally using control points) or generating a color % gradient from sparsely separated color points. % % The format of the GenerateCoefficients() method is: % % Image *GenerateCoefficients(const Image *image,DistortImageMethod method, % const size_t number_arguments,const double *arguments, % size_t number_values, ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to be distorted. % % o method: the method of image distortion/ sparse gradient % % o number_arguments: the number of arguments given. % % o arguments: the arguments for this distortion method. % % o number_values: the style and format of given control points, (caller type) % 0: 2 dimensional mapping of control points (Distort) % Format: u,v,x,y where u,v is the 'source' of the % the color to be plotted, for DistortImage() % N: Interpolation of control points with N values (usally r,g,b) % Format: x,y,r,g,b mapping x,y to color values r,g,b % IN future, variable number of values may be given (1 to N) % % o exception: return any errors or warnings in this structure % % Note that the returned array of double values must be freed by the % calling method using RelinquishMagickMemory(). This however may change in % the future to require a more 'method' specific method. % % Because of this this method should not be classed as stable or used % outside other MagickCore library methods. */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } static double *GenerateCoefficients(const Image *image, DistortImageMethod *method,const size_t number_arguments, const double *arguments,size_t number_values,ExceptionInfo *exception) { double *coeff; register size_t i; size_t number_coeff, /* number of coefficients to return (array size) */ cp_size, /* number floating point numbers per control point */ cp_x,cp_y, /* the x,y indexes for control point */ cp_values; /* index of values for this control point */ /* number_values Number of values given per control point */ if ( number_values == 0 ) { /* Image distortion using control points (or other distortion) That is generate a mapping so that x,y->u,v given u,v,x,y */ number_values = 2; /* special case: two values of u,v */ cp_values = 0; /* the values i,j are BEFORE the destination CP x,y */ cp_x = 2; /* location of x,y in input control values */ cp_y = 3; /* NOTE: cp_values, also used for later 'reverse map distort' tests */ } else { cp_x = 0; /* location of x,y in input control values */ cp_y = 1; cp_values = 2; /* and the other values are after x,y */ /* Typically in this case the values are R,G,B color values */ } cp_size = number_values+2; /* each CP defintion involves this many numbers */ /* If not enough control point pairs are found for specific distortions fall back to Affine distortion (allowing 0 to 3 point pairs) */ if ( number_arguments < 4*cp_size && ( *method == BilinearForwardDistortion || *method == BilinearReverseDistortion || *method == PerspectiveDistortion ) ) *method = AffineDistortion; number_coeff=0; switch (*method) { case AffineDistortion: /* also BarycentricColorInterpolate: */ number_coeff=3*number_values; break; case PolynomialDistortion: /* number of coefficents depend on the given polynomal 'order' */ if ( number_arguments <= 1 && (number_arguments-1)%cp_size != 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","Polynomial", "Invalid number of args: order [CPs]..."); return((double *) NULL); } i = poly_number_terms(arguments[0]); number_coeff = 2 + i*number_values; if ( i == 0 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","Polynomial", "Invalid order, should be interger 1 to 5, or 1.5"); return((double *) NULL); } if ( number_arguments < 1+i*cp_size ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument", "%s : 'require at least %.20g CPs'", "Polynomial", (double) i); return((double *) NULL); } break; case BilinearReverseDistortion: number_coeff=4*number_values; break; /* The rest are constants as they are only used for image distorts */ case BilinearForwardDistortion: number_coeff=10; /* 2*4 coeff plus 2 constants */ cp_x = 0; /* Reverse src/dest coords for forward mapping */ cp_y = 1; cp_values = 2; break; #if 0 case QuadraterialDistortion: number_coeff=19; /* BilinearForward + BilinearReverse */ #endif break; case ShepardsDistortion: number_coeff=1; /* The power factor to use */ break; case ArcDistortion: number_coeff=5; break; case ScaleRotateTranslateDistortion: case AffineProjectionDistortion: case Plane2CylinderDistortion: case Cylinder2PlaneDistortion: number_coeff=6; break; case PolarDistortion: case DePolarDistortion: number_coeff=8; break; case PerspectiveDistortion: case PerspectiveProjectionDistortion: number_coeff=9; break; case BarrelDistortion: case BarrelInverseDistortion: number_coeff=10; break; default: perror("unknown method given"); /* just fail assertion */ } /* allocate the array of coefficients needed */ coeff = (double *) AcquireQuantumMemory(number_coeff,sizeof(*coeff)); if (coeff == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed", "%s", "GenerateCoefficients"); return((double *) NULL); } /* zero out coefficients array */ for (i=0; i < number_coeff; i++) coeff[i] = 0.0; switch (*method) { case AffineDistortion: { /* Affine Distortion v = c0*x + c1*y + c2 for each 'value' given Input Arguments are sets of control points... For Distort Images u,v, x,y ... For Sparse Gradients x,y, r,g,b ... */ if ( number_arguments%cp_size != 0 || number_arguments < cp_size ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument", "%s : 'require at least %.20g CPs'", "Affine", 1.0); coeff=(double *) RelinquishMagickMemory(coeff); return((double *) NULL); } /* handle special cases of not enough arguments */ if ( number_arguments == cp_size ) { /* Only 1 CP Set Given */ if ( cp_values == 0 ) { /* image distortion - translate the image */ coeff[0] = 1.0; coeff[2] = arguments[0] - arguments[2]; coeff[4] = 1.0; coeff[5] = arguments[1] - arguments[3]; } else { /* sparse gradient - use the values directly */ for (i=0; i<number_values; i++) coeff[i*3+2] = arguments[cp_values+i]; } } else { /* 2 or more points (usally 3) given. Solve a least squares simultaneous equation for coefficients. */ double **matrix, **vectors, terms[3]; MagickBooleanType status; /* create matrix, and a fake vectors matrix */ matrix = AcquireMagickMatrix(3UL,3UL); vectors = (double **) AcquireQuantumMemory(number_values,sizeof(*vectors)); if (matrix == (double **) NULL || vectors == (double **) NULL) { matrix = RelinquishMagickMatrix(matrix, 3UL); vectors = (double **) RelinquishMagickMemory(vectors); coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed", "%s", "DistortCoefficients"); return((double *) NULL); } /* fake a number_values x3 vectors matrix from coefficients array */ for (i=0; i < number_values; i++) vectors[i] = &(coeff[i*3]); /* Add given control point pairs for least squares solving */ for (i=0; i < number_arguments; i+=cp_size) { terms[0] = arguments[i+cp_x]; /* x */ terms[1] = arguments[i+cp_y]; /* y */ terms[2] = 1; /* 1 */ LeastSquaresAddTerms(matrix,vectors,terms, &(arguments[i+cp_values]),3UL,number_values); } if ( number_arguments == 2*cp_size ) { /* Only two pairs were given, but we need 3 to solve the affine. Fake extra coordinates by rotating p1 around p0 by 90 degrees. x2 = x0 - (y1-y0) y2 = y0 + (x1-x0) */ terms[0] = arguments[cp_x] - ( arguments[cp_size+cp_y] - arguments[cp_y] ); /* x2 */ terms[1] = arguments[cp_y] + + ( arguments[cp_size+cp_x] - arguments[cp_x] ); /* y2 */ terms[2] = 1; /* 1 */ if ( cp_values == 0 ) { /* Image Distortion - rotate the u,v coordients too */ double uv2[2]; uv2[0] = arguments[0] - arguments[5] + arguments[1]; /* u2 */ uv2[1] = arguments[1] + arguments[4] - arguments[0]; /* v2 */ LeastSquaresAddTerms(matrix,vectors,terms,uv2,3UL,2UL); } else { /* Sparse Gradient - use values of p0 for linear gradient */ LeastSquaresAddTerms(matrix,vectors,terms, &(arguments[cp_values]),3UL,number_values); } } /* Solve for LeastSquares Coefficients */ status=GaussJordanElimination(matrix,vectors,3UL,number_values); matrix = RelinquishMagickMatrix(matrix, 3UL); vectors = (double **) RelinquishMagickMemory(vectors); if ( status == MagickFalse ) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Unsolvable Matrix'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } } return(coeff); } case AffineProjectionDistortion: { /* Arguments: Affine Matrix (forward mapping) Arguments sx, rx, ry, sy, tx, ty Where u = sx*x + ry*y + tx v = rx*x + sy*y + ty Returns coefficients (in there inverse form) ordered as... sx ry tx rx sy ty AffineProjection Distortion Notes... + Will only work with a 2 number_values for Image Distortion + Can not be used for generating a sparse gradient (interpolation) */ double inverse[8]; if (number_arguments != 6) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Needs 6 coeff values'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } /* FUTURE: trap test for sx*sy-rx*ry == 0 (determinant = 0, no inverse) */ for(i=0; i<6UL; i++ ) inverse[i] = arguments[i]; AffineArgsToCoefficients(inverse); /* map into coefficents */ InvertAffineCoefficients(inverse, coeff); /* invert */ *method = AffineDistortion; return(coeff); } case ScaleRotateTranslateDistortion: { /* Scale, Rotate and Translate Distortion An alternative Affine Distortion Argument options, by number of arguments given: 7: x,y, sx,sy, a, nx,ny 6: x,y, s, a, nx,ny 5: x,y, sx,sy, a 4: x,y, s, a 3: x,y, a 2: s, a 1: a Where actions are (in order of application) x,y 'center' of transforms (default = image center) sx,sy scale image by this amount (default = 1) a angle of rotation (argument required) nx,ny move 'center' here (default = x,y or no movement) And convert to affine mapping coefficients ScaleRotateTranslate Distortion Notes... + Does not use a set of CPs in any normal way + Will only work with a 2 number_valuesal Image Distortion + Cannot be used for generating a sparse gradient (interpolation) */ double cosine, sine, x,y,sx,sy,a,nx,ny; /* set default center, and default scale */ x = nx = (double)(image->columns)/2.0 + (double)image->page.x; y = ny = (double)(image->rows)/2.0 + (double)image->page.y; sx = sy = 1.0; switch ( number_arguments ) { case 0: coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Needs at least 1 argument'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); case 1: a = arguments[0]; break; case 2: sx = sy = arguments[0]; a = arguments[1]; break; default: x = nx = arguments[0]; y = ny = arguments[1]; switch ( number_arguments ) { case 3: a = arguments[2]; break; case 4: sx = sy = arguments[2]; a = arguments[3]; break; case 5: sx = arguments[2]; sy = arguments[3]; a = arguments[4]; break; case 6: sx = sy = arguments[2]; a = arguments[3]; nx = arguments[4]; ny = arguments[5]; break; case 7: sx = arguments[2]; sy = arguments[3]; a = arguments[4]; nx = arguments[5]; ny = arguments[6]; break; default: coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Too Many Arguments (7 or less)'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } break; } /* Trap if sx or sy == 0 -- image is scaled out of existance! */ if ( fabs(sx) < MagickEpsilon || fabs(sy) < MagickEpsilon ) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Zero Scale Given'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } /* Save the given arguments as an affine distortion */ a=DegreesToRadians(a); cosine=cos(a); sine=sin(a); *method = AffineDistortion; coeff[0]=cosine/sx; coeff[1]=sine/sx; coeff[2]=x-nx*coeff[0]-ny*coeff[1]; coeff[3]=(-sine)/sy; coeff[4]=cosine/sy; coeff[5]=y-nx*coeff[3]-ny*coeff[4]; return(coeff); } case PerspectiveDistortion: { /* Perspective Distortion (a ratio of affine distortions) p(x,y) c0*x + c1*y + c2 u = ------ = ------------------ r(x,y) c6*x + c7*y + 1 q(x,y) c3*x + c4*y + c5 v = ------ = ------------------ r(x,y) c6*x + c7*y + 1 c8 = Sign of 'r', or the denominator affine, for the actual image. This determines what part of the distorted image is 'ground' side of the horizon, the other part is 'sky' or invalid. Valid values are +1.0 or -1.0 only. Input Arguments are sets of control points... For Distort Images u,v, x,y ... For Sparse Gradients x,y, r,g,b ... Perspective Distortion Notes... + Can be thought of as ratio of 3 affine transformations + Not separatable: r() or c6 and c7 are used by both equations + All 8 coefficients must be determined simultaniously + Will only work with a 2 number_valuesal Image Distortion + Can not be used for generating a sparse gradient (interpolation) + It is not linear, but is simple to generate an inverse + All lines within an image remain lines. + but distances between points may vary. */ double **matrix, *vectors[1], terms[8]; size_t cp_u = cp_values, cp_v = cp_values+1; MagickBooleanType status; if ( number_arguments%cp_size != 0 || number_arguments < cp_size*4 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument", "%s : 'require at least %.20g CPs'", CommandOptionToMnemonic(MagickDistortOptions, *method), 4.0); coeff=(double *) RelinquishMagickMemory(coeff); return((double *) NULL); } /* fake 1x8 vectors matrix directly using the coefficients array */ vectors[0] = &(coeff[0]); /* 8x8 least-squares matrix (zeroed) */ matrix = AcquireMagickMatrix(8UL,8UL); if (matrix == (double **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed", "%s", "DistortCoefficients"); return((double *) NULL); } /* Add control points for least squares solving */ for (i=0; i < number_arguments; i+=4) { terms[0]=arguments[i+cp_x]; /* c0*x */ terms[1]=arguments[i+cp_y]; /* c1*y */ terms[2]=1.0; /* c2*1 */ terms[3]=0.0; terms[4]=0.0; terms[5]=0.0; terms[6]=-terms[0]*arguments[i+cp_u]; /* 1/(c6*x) */ terms[7]=-terms[1]*arguments[i+cp_u]; /* 1/(c7*y) */ LeastSquaresAddTerms(matrix,vectors,terms,&(arguments[i+cp_u]), 8UL,1UL); terms[0]=0.0; terms[1]=0.0; terms[2]=0.0; terms[3]=arguments[i+cp_x]; /* c3*x */ terms[4]=arguments[i+cp_y]; /* c4*y */ terms[5]=1.0; /* c5*1 */ terms[6]=-terms[3]*arguments[i+cp_v]; /* 1/(c6*x) */ terms[7]=-terms[4]*arguments[i+cp_v]; /* 1/(c7*y) */ LeastSquaresAddTerms(matrix,vectors,terms,&(arguments[i+cp_v]), 8UL,1UL); } /* Solve for LeastSquares Coefficients */ status=GaussJordanElimination(matrix,vectors,8UL,1UL); matrix = RelinquishMagickMatrix(matrix, 8UL); if ( status == MagickFalse ) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Unsolvable Matrix'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } /* Calculate 9'th coefficient! The ground-sky determination. What is sign of the 'ground' in r() denominator affine function? Just use any valid image coordinate (first control point) in destination for determination of what part of view is 'ground'. */ coeff[8] = coeff[6]*arguments[cp_x] + coeff[7]*arguments[cp_y] + 1.0; coeff[8] = (coeff[8] < 0.0) ? -1.0 : +1.0; return(coeff); } case PerspectiveProjectionDistortion: { /* Arguments: Perspective Coefficents (forward mapping) */ if (number_arguments != 8) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument", "%s : 'Needs 8 coefficient values'", CommandOptionToMnemonic(MagickDistortOptions, *method)); return((double *) NULL); } /* FUTURE: trap test c0*c4-c3*c1 == 0 (determinate = 0, no inverse) */ InvertPerspectiveCoefficients(arguments, coeff); /* Calculate 9'th coefficient! The ground-sky determination. What is sign of the 'ground' in r() denominator affine function? Just use any valid image cocodinate in destination for determination. For a forward mapped perspective the images 0,0 coord will map to c2,c5 in the distorted image, so set the sign of denominator of that. */ coeff[8] = coeff[6]*arguments[2] + coeff[7]*arguments[5] + 1.0; coeff[8] = (coeff[8] < 0.0) ? -1.0 : +1.0; *method = PerspectiveDistortion; return(coeff); } case BilinearForwardDistortion: case BilinearReverseDistortion: { /* Bilinear Distortion (Forward mapping) v = c0*x + c1*y + c2*x*y + c3; for each 'value' given This is actually a simple polynomial Distortion! The difference however is when we need to reverse the above equation to generate a BilinearForwardDistortion (see below). Input Arguments are sets of control points... For Distort Images u,v, x,y ... For Sparse Gradients x,y, r,g,b ... */ double **matrix, **vectors, terms[4]; MagickBooleanType status; /* check the number of arguments */ if ( number_arguments%cp_size != 0 || number_arguments < cp_size*4 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument", "%s : 'require at least %.20g CPs'", CommandOptionToMnemonic(MagickDistortOptions, *method), 4.0); coeff=(double *) RelinquishMagickMemory(coeff); return((double *) NULL); } /* create matrix, and a fake vectors matrix */ matrix = AcquireMagickMatrix(4UL,4UL); vectors = (double **) AcquireQuantumMemory(number_values,sizeof(*vectors)); if (matrix == (double **) NULL || vectors == (double **) NULL) { matrix = RelinquishMagickMatrix(matrix, 4UL); vectors = (double **) RelinquishMagickMemory(vectors); coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed", "%s", "DistortCoefficients"); return((double *) NULL); } /* fake a number_values x4 vectors matrix from coefficients array */ for (i=0; i < number_values; i++) vectors[i] = &(coeff[i*4]); /* Add given control point pairs for least squares solving */ for (i=0; i < number_arguments; i+=cp_size) { terms[0] = arguments[i+cp_x]; /* x */ terms[1] = arguments[i+cp_y]; /* y */ terms[2] = terms[0]*terms[1]; /* x*y */ terms[3] = 1; /* 1 */ LeastSquaresAddTerms(matrix,vectors,terms, &(arguments[i+cp_values]),4UL,number_values); } /* Solve for LeastSquares Coefficients */ status=GaussJordanElimination(matrix,vectors,4UL,number_values); matrix = RelinquishMagickMatrix(matrix, 4UL); vectors = (double **) RelinquishMagickMemory(vectors); if ( status == MagickFalse ) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Unsolvable Matrix'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } if ( *method == BilinearForwardDistortion ) { /* Bilinear Forward Mapped Distortion The above least-squares solved for coefficents but in the forward direction, due to changes to indexing constants. i = c0*x + c1*y + c2*x*y + c3; j = c4*x + c5*y + c6*x*y + c7; where i,j are in the destination image, NOT the source. Reverse Pixel mapping however needs to use reverse of these functions. It required a full page of algbra to work out the reversed mapping formula, but resolves down to the following... c8 = c0*c5-c1*c4; c9 = 2*(c2*c5-c1*c6); // '2*a' in the quadratic formula i = i - c3; j = j - c7; b = c6*i - c2*j + c8; // So that a*y^2 + b*y + c == 0 c = c4*i - c0*j; // y = ( -b +- sqrt(bb - 4ac) ) / (2*a) r = b*b - c9*(c+c); if ( c9 != 0 ) y = ( -b + sqrt(r) ) / c9; else y = -c/b; x = ( i - c1*y) / ( c1 - c2*y ); NB: if 'r' is negative there is no solution! NB: the sign of the sqrt() should be negative if image becomes flipped or flopped, or crosses over itself. NB: techniqually coefficient c5 is not needed, anymore, but kept for completness. See Anthony Thyssen <A.Thyssen@griffith.edu.au> or Fred Weinhaus <fmw@alink.net> for more details. */ coeff[8] = coeff[0]*coeff[5] - coeff[1]*coeff[4]; coeff[9] = 2*(coeff[2]*coeff[5] - coeff[1]*coeff[6]); } return(coeff); } #if 0 case QuadrilateralDistortion: { /* Map a Quadrilateral to a unit square using BilinearReverse Then map that unit square back to the final Quadrilateral using BilinearForward. Input Arguments are sets of control points... For Distort Images u,v, x,y ... For Sparse Gradients x,y, r,g,b ... */ /* UNDER CONSTRUCTION */ return(coeff); } #endif case PolynomialDistortion: { /* Polynomial Distortion First two coefficents are used to hole global polynomal information c0 = Order of the polynimial being created c1 = number_of_terms in one polynomial equation Rest of the coefficients map to the equations.... v = c0 + c1*x + c2*y + c3*x*y + c4*x^2 + c5*y^2 + c6*x^3 + ... for each 'value' (number_values of them) given. As such total coefficients = 2 + number_terms * number_values Input Arguments are sets of control points... For Distort Images order [u,v, x,y] ... For Sparse Gradients order [x,y, r,g,b] ... Polynomial Distortion Notes... + UNDER DEVELOPMENT -- Do not expect this to remain as is. + Currently polynomial is a reversed mapped distortion. + Order 1.5 is fudged to map into a bilinear distortion. though it is not the same order as that distortion. */ double **matrix, **vectors, *terms; size_t nterms; /* number of polynomial terms per number_values */ register ssize_t j; MagickBooleanType status; /* first two coefficients hold polynomial order information */ coeff[0] = arguments[0]; coeff[1] = (double) poly_number_terms(arguments[0]); nterms = (size_t) coeff[1]; /* create matrix, a fake vectors matrix, and least sqs terms */ matrix = AcquireMagickMatrix(nterms,nterms); vectors = (double **) AcquireQuantumMemory(number_values,sizeof(*vectors)); terms = (double *) AcquireQuantumMemory(nterms, sizeof(*terms)); if (matrix == (double **) NULL || vectors == (double **) NULL || terms == (double *) NULL ) { matrix = RelinquishMagickMatrix(matrix, nterms); vectors = (double **) RelinquishMagickMemory(vectors); terms = (double *) RelinquishMagickMemory(terms); coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed", "%s", "DistortCoefficients"); return((double *) NULL); } /* fake a number_values x3 vectors matrix from coefficients array */ for (i=0; i < number_values; i++) vectors[i] = &(coeff[2+i*nterms]); /* Add given control point pairs for least squares solving */ for (i=1; i < number_arguments; i+=cp_size) { /* NB: start = 1 not 0 */ for (j=0; j < (ssize_t) nterms; j++) terms[j] = poly_basis_fn(j,arguments[i+cp_x],arguments[i+cp_y]); LeastSquaresAddTerms(matrix,vectors,terms, &(arguments[i+cp_values]),nterms,number_values); } terms = (double *) RelinquishMagickMemory(terms); /* Solve for LeastSquares Coefficients */ status=GaussJordanElimination(matrix,vectors,nterms,number_values); matrix = RelinquishMagickMatrix(matrix, nterms); vectors = (double **) RelinquishMagickMemory(vectors); if ( status == MagickFalse ) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Unsolvable Matrix'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } return(coeff); } case ArcDistortion: { /* Arc Distortion Args: arc_width rotate top_edge_radius bottom_edge_radius All but first argument are optional arc_width The angle over which to arc the image side-to-side rotate Angle to rotate image from vertical center top_radius Set top edge of source image at this radius bottom_radius Set bootom edge to this radius (radial scaling) By default, if the radii arguments are nor provided the image radius is calculated so the horizontal center-line is fits the given arc without scaling. The output image size is ALWAYS adjusted to contain the whole image, and an offset is given to position image relative to the 0,0 point of the origin, allowing users to use relative positioning onto larger background (via -flatten). The arguments are converted to these coefficients c0: angle for center of source image c1: angle scale for mapping to source image c2: radius for top of source image c3: radius scale for mapping source image c4: centerline of arc within source image Note the coefficients use a center angle, so asymptotic join is furthest from both sides of the source image. This also means that for arc angles greater than 360 the sides of the image will be trimmed equally. Arc Distortion Notes... + Does not use a set of CPs + Will only work with Image Distortion + Can not be used for generating a sparse gradient (interpolation) */ if ( number_arguments >= 1 && arguments[0] < MagickEpsilon ) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Arc Angle Too Small'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } if ( number_arguments >= 3 && arguments[2] < MagickEpsilon ) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : 'Outer Radius Too Small'", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } coeff[0] = -MagickPI2; /* -90, place at top! */ if ( number_arguments >= 1 ) coeff[1] = DegreesToRadians(arguments[0]); else coeff[1] = MagickPI2; /* zero arguments - center is at top */ if ( number_arguments >= 2 ) coeff[0] += DegreesToRadians(arguments[1]); coeff[0] /= Magick2PI; /* normalize radians */ coeff[0] -= MagickRound(coeff[0]); coeff[0] *= Magick2PI; /* de-normalize back to radians */ coeff[3] = (double)image->rows-1; coeff[2] = (double)image->columns/coeff[1] + coeff[3]/2.0; if ( number_arguments >= 3 ) { if ( number_arguments >= 4 ) coeff[3] = arguments[2] - arguments[3]; else coeff[3] *= arguments[2]/coeff[2]; coeff[2] = arguments[2]; } coeff[4] = ((double)image->columns-1.0)/2.0; return(coeff); } case PolarDistortion: case DePolarDistortion: { /* (De)Polar Distortion (same set of arguments) Args: Rmax, Rmin, Xcenter,Ycenter, Afrom,Ato DePolar can also have the extra arguments of Width, Height Coefficients 0 to 5 is the sanatized version first 6 input args Coefficient 6 is the angle to coord ratio and visa-versa Coefficient 7 is the radius to coord ratio and visa-versa WARNING: It is possible for Radius max<min and/or Angle from>to */ if ( number_arguments == 3 || ( number_arguments > 6 && *method == PolarDistortion ) || number_arguments > 8 ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"InvalidArgument", "%s : number of arguments", CommandOptionToMnemonic(MagickDistortOptions, *method) ); coeff=(double *) RelinquishMagickMemory(coeff); return((double *) NULL); } /* Rmax - if 0 calculate appropriate value */ if ( number_arguments >= 1 ) coeff[0] = arguments[0]; else coeff[0] = 0.0; /* Rmin - usally 0 */ coeff[1] = number_arguments >= 2 ? arguments[1] : 0.0; /* Center X,Y */ if ( number_arguments >= 4 ) { coeff[2] = arguments[2]; coeff[3] = arguments[3]; } else { /* center of actual image */ coeff[2] = (double)(image->columns)/2.0+image->page.x; coeff[3] = (double)(image->rows)/2.0+image->page.y; } /* Angle from,to - about polar center 0 is downward */ coeff[4] = -MagickPI; if ( number_arguments >= 5 ) coeff[4] = DegreesToRadians(arguments[4]); coeff[5] = coeff[4]; if ( number_arguments >= 6 ) coeff[5] = DegreesToRadians(arguments[5]); if ( fabs(coeff[4]-coeff[5]) < MagickEpsilon ) coeff[5] += Magick2PI; /* same angle is a full circle */ /* if radius 0 or negative, its a special value... */ if ( coeff[0] < MagickEpsilon ) { /* Use closest edge if radius == 0 */ if ( fabs(coeff[0]) < MagickEpsilon ) { coeff[0]=MagickMin(fabs(coeff[2]-image->page.x), fabs(coeff[3]-image->page.y)); coeff[0]=MagickMin(coeff[0], fabs(coeff[2]-image->page.x-image->columns)); coeff[0]=MagickMin(coeff[0], fabs(coeff[3]-image->page.y-image->rows)); } /* furthest diagonal if radius == -1 */ if ( fabs(-1.0-coeff[0]) < MagickEpsilon ) { double rx,ry; rx = coeff[2]-image->page.x; ry = coeff[3]-image->page.y; coeff[0] = rx*rx+ry*ry; ry = coeff[3]-image->page.y-image->rows; coeff[0] = MagickMax(coeff[0],rx*rx+ry*ry); rx = coeff[2]-image->page.x-image->columns; coeff[0] = MagickMax(coeff[0],rx*rx+ry*ry); ry = coeff[3]-image->page.y; coeff[0] = MagickMax(coeff[0],rx*rx+ry*ry); coeff[0] = sqrt(coeff[0]); } } /* IF Rmax <= 0 or Rmin < 0 OR Rmax < Rmin, THEN error */ if ( coeff[0] < MagickEpsilon || coeff[1] < -MagickEpsilon || (coeff[0]-coeff[1]) < MagickEpsilon ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument", "%s : Invalid Radius", CommandOptionToMnemonic(MagickDistortOptions, *method) ); coeff=(double *) RelinquishMagickMemory(coeff); return((double *) NULL); } /* converstion ratios */ if ( *method == PolarDistortion ) { coeff[6]=(double) image->columns/(coeff[5]-coeff[4]); coeff[7]=(double) image->rows/(coeff[0]-coeff[1]); } else { /* *method == DePolarDistortion */ coeff[6]=(coeff[5]-coeff[4])/image->columns; coeff[7]=(coeff[0]-coeff[1])/image->rows; } return(coeff); } case Cylinder2PlaneDistortion: case Plane2CylinderDistortion: { /* 3D Cylinder to/from a Tangential Plane Projection between a clinder and flat plain from a point on the center line of the cylinder. The two surfaces coincide in 3D space at the given centers of distortion (perpendicular to projection point) on both images. Args: FOV_arc_width Coefficents: FOV(radians), Radius, center_x,y, dest_center_x,y FOV (Field Of View) the angular field of view of the distortion, across the width of the image, in degrees. The centers are the points of least distortion in the input and resulting images. These centers are however determined later. Coeff 0 is the FOV angle of view of image width in radians Coeff 1 is calculated radius of cylinder. Coeff 2,3 center of distortion of input image Coefficents 4,5 Center of Distortion of dest (determined later) */ if ( arguments[0] < MagickEpsilon || arguments[0] > 160.0 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument", "%s : Invalid FOV Angle", CommandOptionToMnemonic(MagickDistortOptions, *method) ); coeff=(double *) RelinquishMagickMemory(coeff); return((double *) NULL); } coeff[0] = DegreesToRadians(arguments[0]); if ( *method == Cylinder2PlaneDistortion ) /* image is curved around cylinder, so FOV angle (in radians) * scales directly to image X coordinate, according to its radius. */ coeff[1] = (double) image->columns/coeff[0]; else /* radius is distance away from an image with this angular FOV */ coeff[1] = (double) image->columns / ( 2 * tan(coeff[0]/2) ); coeff[2] = (double)(image->columns)/2.0+image->page.x; coeff[3] = (double)(image->rows)/2.0+image->page.y; coeff[4] = coeff[2]; coeff[5] = coeff[3]; /* assuming image size is the same */ return(coeff); } case BarrelDistortion: case BarrelInverseDistortion: { /* Barrel Distortion Rs=(A*Rd^3 + B*Rd^2 + C*Rd + D)*Rd BarrelInv Distortion Rs=Rd/(A*Rd^3 + B*Rd^2 + C*Rd + D) Where Rd is the normalized radius from corner to middle of image Input Arguments are one of the following forms (number of arguments)... 3: A,B,C 4: A,B,C,D 5: A,B,C X,Y 6: A,B,C,D X,Y 8: Ax,Bx,Cx,Dx Ay,By,Cy,Dy 10: Ax,Bx,Cx,Dx Ay,By,Cy,Dy X,Y Returns 10 coefficent values, which are de-normalized (pixel scale) Ax, Bx, Cx, Dx, Ay, By, Cy, Dy, Xc, Yc */ /* Radius de-normalization scaling factor */ double rscale = 2.0/MagickMin((double) image->columns,(double) image->rows); /* sanity check number of args must = 3,4,5,6,8,10 or error */ if ( (number_arguments < 3) || (number_arguments == 7) || (number_arguments == 9) || (number_arguments > 10) ) { coeff=(double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"InvalidArgument", "%s : number of arguments", CommandOptionToMnemonic(MagickDistortOptions, *method) ); return((double *) NULL); } /* A,B,C,D coefficients */ coeff[0] = arguments[0]; coeff[1] = arguments[1]; coeff[2] = arguments[2]; if ((number_arguments == 3) || (number_arguments == 5) ) coeff[3] = 1.0 - coeff[0] - coeff[1] - coeff[2]; else coeff[3] = arguments[3]; /* de-normalize the coefficients */ coeff[0] *= pow(rscale,3.0); coeff[1] *= rscale*rscale; coeff[2] *= rscale; /* Y coefficients: as given OR same as X coefficients */ if ( number_arguments >= 8 ) { coeff[4] = arguments[4] * pow(rscale,3.0); coeff[5] = arguments[5] * rscale*rscale; coeff[6] = arguments[6] * rscale; coeff[7] = arguments[7]; } else { coeff[4] = coeff[0]; coeff[5] = coeff[1]; coeff[6] = coeff[2]; coeff[7] = coeff[3]; } /* X,Y Center of Distortion (image coodinates) */ if ( number_arguments == 5 ) { coeff[8] = arguments[3]; coeff[9] = arguments[4]; } else if ( number_arguments == 6 ) { coeff[8] = arguments[4]; coeff[9] = arguments[5]; } else if ( number_arguments == 10 ) { coeff[8] = arguments[8]; coeff[9] = arguments[9]; } else { /* center of the image provided (image coodinates) */ coeff[8] = (double)image->columns/2.0 + image->page.x; coeff[9] = (double)image->rows/2.0 + image->page.y; } return(coeff); } case ShepardsDistortion: { /* Shepards Distortion input arguments are the coefficents! Just check the number of arguments is valid! Args: u1,v1, x1,y1, ... OR : u1,v1, r1,g1,c1, ... */ if ( number_arguments%cp_size != 0 || number_arguments < cp_size ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument", "%s : 'requires CP's (4 numbers each)'", CommandOptionToMnemonic(MagickDistortOptions, *method)); coeff=(double *) RelinquishMagickMemory(coeff); return((double *) NULL); } /* User defined weighting power for Shepard's Method */ { const char *artifact=GetImageArtifact(image,"shepards:power"); if ( artifact != (const char *) NULL ) { coeff[0]=StringToDouble(artifact,(char **) NULL) / 2.0; if ( coeff[0] < MagickEpsilon ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"InvalidArgument","%s", "-define shepards:power" ); coeff=(double *) RelinquishMagickMemory(coeff); return((double *) NULL); } } else coeff[0]=1.0; /* Default power of 2 (Inverse Squared) */ } return(coeff); } default: break; } /* you should never reach this point */ perror("no method handler"); /* just fail assertion */ return((double *) NULL); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i s t o r t R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DistortResizeImage() resize image using the equivalent but slower image % distortion operator. The filter is applied using a EWA cylindrical % resampling. But like resize the final image size is limited to whole pixels % with no effects by virtual-pixels on the result. % % Note that images containing a transparency channel will be twice as slow to % resize as images one without transparency. % % The format of the DistortResizeImage method is: % % Image *AdaptiveResizeImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the resized image. % % o rows: the number of rows in the resized image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DistortResizeImage(const Image *image, const size_t columns,const size_t rows,ExceptionInfo *exception) { #define DistortResizeImageTag "Distort/Image" Image *resize_image, *tmp_image; RectangleInfo crop_area; double distort_args[12]; VirtualPixelMethod vp_save; /* Distort resize image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((columns == 0) || (rows == 0)) return((Image *) NULL); /* Do not short-circuit this resize if final image size is unchanged */ (void) ResetMagickMemory(distort_args,0,12*sizeof(double)); distort_args[4]=(double) image->columns; distort_args[6]=(double) columns; distort_args[9]=(double) image->rows; distort_args[11]=(double) rows; vp_save=GetImageVirtualPixelMethod(image); tmp_image=CloneImage(image,0,0,MagickTrue,exception); if ( tmp_image == (Image *) NULL ) return((Image *) NULL); (void) SetImageVirtualPixelMethod(tmp_image,TransparentVirtualPixelMethod); if (image->matte == MagickFalse) { /* Image has not transparency channel, so we free to use it */ (void) SetImageAlphaChannel(tmp_image,SetAlphaChannel); resize_image=DistortImage(tmp_image,AffineDistortion,12,distort_args, MagickTrue,exception), tmp_image=DestroyImage(tmp_image); if ( resize_image == (Image *) NULL ) return((Image *) NULL); (void) SetImageAlphaChannel(resize_image,DeactivateAlphaChannel); InheritException(exception,&image->exception); } else { /* Image has transparency so handle colors and alpha separatly. Basically we need to separate Virtual-Pixel alpha in the resized image, so only the actual original images alpha channel is used. */ Image *resize_alpha; /* distort alpha channel separately */ (void) SeparateImageChannel(tmp_image,TrueAlphaChannel); (void) SetImageAlphaChannel(tmp_image,OpaqueAlphaChannel); resize_alpha=DistortImage(tmp_image,AffineDistortion,12,distort_args, MagickTrue,exception), tmp_image=DestroyImage(tmp_image); if ( resize_alpha == (Image *) NULL ) return((Image *) NULL); /* distort the actual image containing alpha + VP alpha */ tmp_image=CloneImage(image,0,0,MagickTrue,exception); if ( tmp_image == (Image *) NULL ) return((Image *) NULL); (void) SetImageVirtualPixelMethod(tmp_image, TransparentVirtualPixelMethod); (void) SetImageVirtualPixelMethod(tmp_image, TransparentVirtualPixelMethod); resize_image=DistortImage(tmp_image,AffineDistortion,12,distort_args, MagickTrue,exception), tmp_image=DestroyImage(tmp_image); if ( resize_image == (Image *) NULL) { resize_alpha=DestroyImage(resize_alpha); return((Image *) NULL); } /* replace resize images alpha with the separally distorted alpha */ (void) SetImageAlphaChannel(resize_image,DeactivateAlphaChannel); (void) SetImageAlphaChannel(resize_alpha,DeactivateAlphaChannel); (void) CompositeImage(resize_image,CopyOpacityCompositeOp,resize_alpha, 0,0); InheritException(exception,&resize_image->exception); resize_alpha=DestroyImage(resize_alpha); } (void) SetImageVirtualPixelMethod(resize_image,vp_save); /* Clean up the results of the Distortion */ crop_area.width=columns; crop_area.height=rows; crop_area.x=0; crop_area.y=0; tmp_image=resize_image; resize_image=CropImage(tmp_image,&crop_area,exception); tmp_image=DestroyImage(tmp_image); return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s t o r t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DistortImage() distorts an image using various distortion methods, by % mapping color lookups of the source image to a new destination image % usally of the same size as the source image, unless 'bestfit' is set to % true. % % If 'bestfit' is enabled, and distortion allows it, the destination image is % adjusted to ensure the whole source 'image' will just fit within the final % destination image, which will be sized and offset accordingly. Also in % many cases the virtual offset of the source image will be taken into % account in the mapping. % % If the '-verbose' control option has been set print to standard error the % equicelent '-fx' formula with coefficients for the function, if practical. % % The format of the DistortImage() method is: % % Image *DistortImage(const Image *image,const DistortImageMethod method, % const size_t number_arguments,const double *arguments, % MagickBooleanType bestfit, ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to be distorted. % % o method: the method of image distortion. % % ArcDistortion always ignores source image offset, and always % 'bestfit' the destination image with the top left corner offset % relative to the polar mapping center. % % Affine, Perspective, and Bilinear, do least squares fitting of the % distrotion when more than the minimum number of control point pairs % are provided. % % Perspective, and Bilinear, fall back to a Affine distortion when less % than 4 control point pairs are provided. While Affine distortions % let you use any number of control point pairs, that is Zero pairs is % a No-Op (viewport only) distortion, one pair is a translation and % two pairs of control points do a scale-rotate-translate, without any % shearing. % % o number_arguments: the number of arguments given. % % o arguments: an array of floating point arguments for this method. % % o bestfit: Attempt to 'bestfit' the size of the resulting image. % This also forces the resulting image to be a 'layered' virtual % canvas image. Can be overridden using 'distort:viewport' setting. % % o exception: return any errors or warnings in this structure % % Extra Controls from Image meta-data (artifacts)... % % o "verbose" % Output to stderr alternatives, internal coefficents, and FX % equivalents for the distortion operation (if feasible). % This forms an extra check of the distortion method, and allows users % access to the internal constants IM calculates for the distortion. % % o "distort:viewport" % Directly set the output image canvas area and offest to use for the % resulting image, rather than use the original images canvas, or a % calculated 'bestfit' canvas. % % o "distort:scale" % Scale the size of the output canvas by this amount to provide a % method of Zooming, and for super-sampling the results. % % Other settings that can effect results include % % o 'interpolate' For source image lookups (scale enlargements) % % o 'filter' Set filter to use for area-resampling (scale shrinking). % Set to 'point' to turn off and use 'interpolate' lookup % instead % */ MagickExport Image *DistortImage(const Image *image,DistortImageMethod method, const size_t number_arguments,const double *arguments, MagickBooleanType bestfit,ExceptionInfo *exception) { #define DistortImageTag "Distort/Image" double *coeff, output_scaling; Image *distort_image; RectangleInfo geometry; /* geometry of the distorted space viewport */ MagickBooleanType viewport_given; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); /* Handle Special Compound Distortions */ if ( method == ResizeDistortion ) { if ( number_arguments != 2 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","Resize", "Invalid number of args: 2 only"); return((Image *) NULL); } distort_image=DistortResizeImage(image,(size_t)arguments[0], (size_t)arguments[1], exception); return(distort_image); } /* Convert input arguments (usually as control points for reverse mapping) into mapping coefficients to apply the distortion. Note that some distortions are mapped to other distortions, and as such do not require specific code after this point. */ coeff = GenerateCoefficients(image, &method, number_arguments, arguments, 0, exception); if ( coeff == (double *) NULL ) return((Image *) NULL); /* Determine the size and offset for a 'bestfit' destination. Usally the four corners of the source image is enough. */ /* default output image bounds, when no 'bestfit' is requested */ geometry.width=image->columns; geometry.height=image->rows; geometry.x=0; geometry.y=0; if ( method == ArcDistortion ) { bestfit = MagickTrue; /* always calculate a 'best fit' viewport */ } /* Work out the 'best fit', (required for ArcDistortion) */ if ( bestfit ) { PointInfo s,d,min,max; /* source, dest coords --mapping--> min, max coords */ MagickBooleanType fix_bounds = MagickTrue; /* enlarge bounds for VP handling */ s.x=s.y=min.x=max.x=min.y=max.y=0.0; /* keep compiler happy */ /* defines to figure out the bounds of the distorted image */ #define InitalBounds(p) \ { \ /* printf("%lg,%lg -> %lg,%lg\n", s.x,s.y, d.x,d.y); */ \ min.x = max.x = p.x; \ min.y = max.y = p.y; \ } #define ExpandBounds(p) \ { \ /* printf("%lg,%lg -> %lg,%lg\n", s.x,s.y, d.x,d.y); */ \ min.x = MagickMin(min.x,p.x); \ max.x = MagickMax(max.x,p.x); \ min.y = MagickMin(min.y,p.y); \ max.y = MagickMax(max.y,p.y); \ } switch (method) { case AffineDistortion: { double inverse[6]; InvertAffineCoefficients(coeff, inverse); s.x = (double) image->page.x; s.y = (double) image->page.y; d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2]; d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5]; InitalBounds(d); s.x = (double) image->page.x+image->columns; s.y = (double) image->page.y; d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2]; d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5]; ExpandBounds(d); s.x = (double) image->page.x; s.y = (double) image->page.y+image->rows; d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2]; d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5]; ExpandBounds(d); s.x = (double) image->page.x+image->columns; s.y = (double) image->page.y+image->rows; d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2]; d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5]; ExpandBounds(d); break; } case PerspectiveDistortion: { double inverse[8], scale; InvertPerspectiveCoefficients(coeff, inverse); s.x = (double) image->page.x; s.y = (double) image->page.y; scale=inverse[6]*s.x+inverse[7]*s.y+1.0; scale=PerceptibleReciprocal(scale); d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]); d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]); InitalBounds(d); s.x = (double) image->page.x+image->columns; s.y = (double) image->page.y; scale=inverse[6]*s.x+inverse[7]*s.y+1.0; scale=PerceptibleReciprocal(scale); d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]); d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]); ExpandBounds(d); s.x = (double) image->page.x; s.y = (double) image->page.y+image->rows; scale=inverse[6]*s.x+inverse[7]*s.y+1.0; scale=PerceptibleReciprocal(scale); d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]); d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]); ExpandBounds(d); s.x = (double) image->page.x+image->columns; s.y = (double) image->page.y+image->rows; scale=inverse[6]*s.x+inverse[7]*s.y+1.0; scale=PerceptibleReciprocal(scale); d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]); d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]); ExpandBounds(d); break; } case ArcDistortion: { double a, ca, sa; /* Forward Map Corners */ a = coeff[0]-coeff[1]/2; ca = cos(a); sa = sin(a); d.x = coeff[2]*ca; d.y = coeff[2]*sa; InitalBounds(d); d.x = (coeff[2]-coeff[3])*ca; d.y = (coeff[2]-coeff[3])*sa; ExpandBounds(d); a = coeff[0]+coeff[1]/2; ca = cos(a); sa = sin(a); d.x = coeff[2]*ca; d.y = coeff[2]*sa; ExpandBounds(d); d.x = (coeff[2]-coeff[3])*ca; d.y = (coeff[2]-coeff[3])*sa; ExpandBounds(d); /* Orthogonal points along top of arc */ for( a=(double) (ceil((double) ((coeff[0]-coeff[1]/2.0)/MagickPI2))*MagickPI2); a<(coeff[0]+coeff[1]/2.0); a+=MagickPI2 ) { ca = cos(a); sa = sin(a); d.x = coeff[2]*ca; d.y = coeff[2]*sa; ExpandBounds(d); } /* Convert the angle_to_width and radius_to_height to appropriate scaling factors, to allow faster processing in the mapping function. */ coeff[1] = (double) (Magick2PI*image->columns/coeff[1]); coeff[3] = (double)image->rows/coeff[3]; break; } case PolarDistortion: { if (number_arguments < 2) coeff[2] = coeff[3] = 0.0; min.x = coeff[2]-coeff[0]; max.x = coeff[2]+coeff[0]; min.y = coeff[3]-coeff[0]; max.y = coeff[3]+coeff[0]; /* should be about 1.0 if Rmin = 0 */ coeff[7]=(double) geometry.height/(coeff[0]-coeff[1]); break; } case DePolarDistortion: { /* direct calculation as it needs to tile correctly * for reversibility in a DePolar-Polar cycle */ fix_bounds = MagickFalse; geometry.x = geometry.y = 0; geometry.height = (size_t) ceil(coeff[0]-coeff[1]); geometry.width = (size_t) ceil((coeff[0]-coeff[1])*(coeff[5]-coeff[4])*0.5); /* correct scaling factors relative to new size */ coeff[6]=(coeff[5]-coeff[4])/geometry.width; /* changed width */ coeff[7]=(coeff[0]-coeff[1])/geometry.height; /* should be about 1.0 */ break; } case Cylinder2PlaneDistortion: { /* direct calculation so center of distortion is either a pixel * center, or pixel edge. This allows for reversibility of the * distortion */ geometry.x = geometry.y = 0; geometry.width = (size_t) ceil( 2.0*coeff[1]*tan(coeff[0]/2.0) ); geometry.height = (size_t) ceil( 2.0*coeff[3]/cos(coeff[0]/2.0) ); /* correct center of distortion relative to new size */ coeff[4] = (double) geometry.width/2.0; coeff[5] = (double) geometry.height/2.0; fix_bounds = MagickFalse; break; } case Plane2CylinderDistortion: { /* direct calculation center is either pixel center, or pixel edge * so as to allow reversibility of the image distortion */ geometry.x = geometry.y = 0; geometry.width = (size_t) ceil(coeff[0]*coeff[1]); /* FOV * radius */ geometry.height = (size_t) (2*coeff[3]); /* input image height */ /* correct center of distortion relative to new size */ coeff[4] = (double) geometry.width/2.0; coeff[5] = (double) geometry.height/2.0; fix_bounds = MagickFalse; break; } case ShepardsDistortion: case BilinearForwardDistortion: case BilinearReverseDistortion: #if 0 case QuadrilateralDistortion: #endif case PolynomialDistortion: case BarrelDistortion: case BarrelInverseDistortion: default: /* no calculated bestfit available for these distortions */ bestfit = MagickFalse; fix_bounds = MagickFalse; break; } /* Set the output image geometry to calculated 'bestfit'. Yes this tends to 'over do' the file image size, ON PURPOSE! Do not do this for DePolar which needs to be exact for virtual tiling. */ if ( fix_bounds ) { geometry.x = (ssize_t) floor(min.x-0.5); geometry.y = (ssize_t) floor(min.y-0.5); geometry.width=(size_t) ceil(max.x-geometry.x+0.5); geometry.height=(size_t) ceil(max.y-geometry.y+0.5); } } /* end bestfit destination image calculations */ /* The user provided a 'viewport' expert option which may overrides some parts of the current output image geometry. This also overrides its default 'bestfit' setting. */ { const char *artifact=GetImageArtifact(image,"distort:viewport"); viewport_given = MagickFalse; if ( artifact != (const char *) NULL ) { MagickStatusType flags=ParseAbsoluteGeometry(artifact,&geometry); if (flags==NoValue) (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"InvalidGeometry","`%s' `%s'", "distort:viewport",artifact); else viewport_given = MagickTrue; } } /* Verbose output */ if ( GetImageArtifact(image,"verbose") != (const char *) NULL ) { register ssize_t i; char image_gen[MaxTextExtent]; const char *lookup; /* Set destination image size and virtual offset */ if ( bestfit || viewport_given ) { (void) FormatLocaleString(image_gen, MaxTextExtent," -size %.20gx%.20g " "-page %+.20g%+.20g xc: +insert \\\n",(double) geometry.width, (double) geometry.height,(double) geometry.x,(double) geometry.y); lookup="v.p{ xx-v.page.x-.5, yy-v.page.y-.5 }"; } else { image_gen[0] = '\0'; /* no destination to generate */ lookup = "p{ xx-page.x-.5, yy-page.y-.5 }"; /* simplify lookup */ } switch (method) { case AffineDistortion: { double *inverse; inverse = (double *) AcquireQuantumMemory(6,sizeof(*inverse)); if (inverse == (double *) NULL) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed", "%s", "DistortImages"); return((Image *) NULL); } InvertAffineCoefficients(coeff, inverse); CoefficientsToAffineArgs(inverse); (void) FormatLocaleFile(stderr, "Affine Projection:\n"); (void) FormatLocaleFile(stderr, " -distort AffineProjection \\\n '"); for (i=0; i < 5; i++) (void) FormatLocaleFile(stderr, "%lf,", inverse[i]); (void) FormatLocaleFile(stderr, "%lf'\n", inverse[5]); inverse = (double *) RelinquishMagickMemory(inverse); (void) FormatLocaleFile(stderr, "Affine Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\n"); (void) FormatLocaleFile(stderr, " xx=%+lf*ii %+lf*jj %+lf;\n", coeff[0], coeff[1], coeff[2]); (void) FormatLocaleFile(stderr, " yy=%+lf*ii %+lf*jj %+lf;\n", coeff[3], coeff[4], coeff[5]); (void) FormatLocaleFile(stderr, " %s' \\\n", lookup); break; } case PerspectiveDistortion: { double *inverse; inverse = (double *) AcquireQuantumMemory(8,sizeof(*inverse)); if (inverse == (double *) NULL) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed", "%s", "DistortCoefficients"); return((Image *) NULL); } InvertPerspectiveCoefficients(coeff, inverse); (void) FormatLocaleFile(stderr, "Perspective Projection:\n"); (void) FormatLocaleFile(stderr, " -distort PerspectiveProjection \\\n '"); for (i=0; i<4; i++) (void) FormatLocaleFile(stderr, "%lf, ", inverse[i]); (void) FormatLocaleFile(stderr, "\n "); for (; i<7; i++) (void) FormatLocaleFile(stderr, "%lf, ", inverse[i]); (void) FormatLocaleFile(stderr, "%lf'\n", inverse[7]); inverse = (double *) RelinquishMagickMemory(inverse); (void) FormatLocaleFile(stderr, "Perspective Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\n"); (void) FormatLocaleFile(stderr, " rr=%+lf*ii %+lf*jj + 1;\n", coeff[6], coeff[7]); (void) FormatLocaleFile(stderr, " xx=(%+lf*ii %+lf*jj %+lf)/rr;\n", coeff[0], coeff[1], coeff[2]); (void) FormatLocaleFile(stderr, " yy=(%+lf*ii %+lf*jj %+lf)/rr;\n", coeff[3], coeff[4], coeff[5]); (void) FormatLocaleFile(stderr, " rr%s0 ? %s : blue' \\\n", coeff[8] < 0 ? "<" : ">", lookup); break; } case BilinearForwardDistortion: (void) FormatLocaleFile(stderr, "BilinearForward Mapping Equations:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " i = %+lf*x %+lf*y %+lf*x*y %+lf;\n", coeff[0], coeff[1], coeff[2], coeff[3]); (void) FormatLocaleFile(stderr, " j = %+lf*x %+lf*y %+lf*x*y %+lf;\n", coeff[4], coeff[5], coeff[6], coeff[7]); #if 0 /* for debugging */ (void) FormatLocaleFile(stderr, " c8 = %+lf c9 = 2*a = %+lf;\n", coeff[8], coeff[9]); #endif (void) FormatLocaleFile(stderr, "BilinearForward Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x%+lf; jj=j+page.y%+lf;\n", 0.5-coeff[3], 0.5-coeff[7]); (void) FormatLocaleFile(stderr, " bb=%lf*ii %+lf*jj %+lf;\n", coeff[6], -coeff[2], coeff[8]); /* Handle Special degenerate (non-quadratic) or trapezoidal case */ if ( coeff[9] != 0 ) { (void) FormatLocaleFile(stderr, " rt=bb*bb %+lf*(%lf*ii%+lf*jj);\n", -2*coeff[9], coeff[4], -coeff[0]); (void) FormatLocaleFile(stderr, " yy=( -bb + sqrt(rt) ) / %lf;\n", coeff[9]); } else (void) FormatLocaleFile(stderr, " yy=(%lf*ii%+lf*jj)/bb;\n", -coeff[4], coeff[0]); (void) FormatLocaleFile(stderr, " xx=(ii %+lf*yy)/(%lf %+lf*yy);\n", -coeff[1], coeff[0], coeff[2]); if ( coeff[9] != 0 ) (void) FormatLocaleFile(stderr, " (rt < 0 ) ? red : %s'\n", lookup); else (void) FormatLocaleFile(stderr, " %s' \\\n", lookup); break; case BilinearReverseDistortion: #if 0 (void) FormatLocaleFile(stderr, "Polynomial Projection Distort:\n"); (void) FormatLocaleFile(stderr, " -distort PolynomialProjection \\\n"); (void) FormatLocaleFile(stderr, " '1.5, %lf, %lf, %lf, %lf,\n", coeff[3], coeff[0], coeff[1], coeff[2]); (void) FormatLocaleFile(stderr, " %lf, %lf, %lf, %lf'\n", coeff[7], coeff[4], coeff[5], coeff[6]); #endif (void) FormatLocaleFile(stderr, "BilinearReverse Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\n"); (void) FormatLocaleFile(stderr, " xx=%+lf*ii %+lf*jj %+lf*ii*jj %+lf;\n", coeff[0], coeff[1], coeff[2], coeff[3]); (void) FormatLocaleFile(stderr, " yy=%+lf*ii %+lf*jj %+lf*ii*jj %+lf;\n", coeff[4], coeff[5], coeff[6], coeff[7]); (void) FormatLocaleFile(stderr, " %s' \\\n", lookup); break; case PolynomialDistortion: { size_t nterms = (size_t) coeff[1]; (void) FormatLocaleFile(stderr, "Polynomial (order %lg, terms %lu), FX Equivelent\n", coeff[0],(unsigned long) nterms); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\n"); (void) FormatLocaleFile(stderr, " xx ="); for (i=0; i<(ssize_t) nterms; i++) { if ( i != 0 && i%4 == 0 ) (void) FormatLocaleFile(stderr, "\n "); (void) FormatLocaleFile(stderr, " %+lf%s", coeff[2+i], poly_basis_str(i)); } (void) FormatLocaleFile(stderr, ";\n yy ="); for (i=0; i<(ssize_t) nterms; i++) { if ( i != 0 && i%4 == 0 ) (void) FormatLocaleFile(stderr, "\n "); (void) FormatLocaleFile(stderr, " %+lf%s", coeff[2+i+nterms], poly_basis_str(i)); } (void) FormatLocaleFile(stderr, ";\n %s' \\\n", lookup); break; } case ArcDistortion: { (void) FormatLocaleFile(stderr, "Arc Distort, Internal Coefficients:\n"); for ( i=0; i<5; i++ ) (void) FormatLocaleFile(stderr, " c%.20g = %+lf\n", (double) i, coeff[i]); (void) FormatLocaleFile(stderr, "Arc Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x; jj=j+page.y;\n"); (void) FormatLocaleFile(stderr, " xx=(atan2(jj,ii)%+lf)/(2*pi);\n", -coeff[0]); (void) FormatLocaleFile(stderr, " xx=xx-round(xx);\n"); (void) FormatLocaleFile(stderr, " xx=xx*%lf %+lf;\n", coeff[1], coeff[4]); (void) FormatLocaleFile(stderr, " yy=(%lf - hypot(ii,jj)) * %lf;\n", coeff[2], coeff[3]); (void) FormatLocaleFile(stderr, " v.p{xx-.5,yy-.5}' \\\n"); break; } case PolarDistortion: { (void) FormatLocaleFile(stderr, "Polar Distort, Internal Coefficents\n"); for ( i=0; i<8; i++ ) (void) FormatLocaleFile(stderr, " c%.20g = %+lf\n", (double) i, coeff[i]); (void) FormatLocaleFile(stderr, "Polar Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x%+lf; jj=j+page.y%+lf;\n", -coeff[2], -coeff[3]); (void) FormatLocaleFile(stderr, " xx=(atan2(ii,jj)%+lf)/(2*pi);\n", -(coeff[4]+coeff[5])/2 ); (void) FormatLocaleFile(stderr, " xx=xx-round(xx);\n"); (void) FormatLocaleFile(stderr, " xx=xx*2*pi*%lf + v.w/2;\n", coeff[6] ); (void) FormatLocaleFile(stderr, " yy=(hypot(ii,jj)%+lf)*%lf;\n", -coeff[1], coeff[7] ); (void) FormatLocaleFile(stderr, " v.p{xx-.5,yy-.5}' \\\n"); break; } case DePolarDistortion: { (void) FormatLocaleFile(stderr, "DePolar Distort, Internal Coefficents\n"); for ( i=0; i<8; i++ ) (void) FormatLocaleFile(stderr, " c%.20g = %+lf\n", (double) i, coeff[i]); (void) FormatLocaleFile(stderr, "DePolar Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'aa=(i+.5)*%lf %+lf;\n", coeff[6], +coeff[4] ); (void) FormatLocaleFile(stderr, " rr=(j+.5)*%lf %+lf;\n", coeff[7], +coeff[1] ); (void) FormatLocaleFile(stderr, " xx=rr*sin(aa) %+lf;\n", coeff[2] ); (void) FormatLocaleFile(stderr, " yy=rr*cos(aa) %+lf;\n", coeff[3] ); (void) FormatLocaleFile(stderr, " v.p{xx-.5,yy-.5}' \\\n"); break; } case Cylinder2PlaneDistortion: { (void) FormatLocaleFile(stderr, "Cylinder to Plane Distort, Internal Coefficents\n"); (void) FormatLocaleFile(stderr, " cylinder_radius = %+lf\n", coeff[1]); (void) FormatLocaleFile(stderr, "Cylinder to Plane Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x%+lf+0.5; jj=j+page.y%+lf+0.5;\n", -coeff[4], -coeff[5]); (void) FormatLocaleFile(stderr, " aa=atan(ii/%+lf);\n", coeff[1] ); (void) FormatLocaleFile(stderr, " xx=%lf*aa%+lf;\n", coeff[1], coeff[2] ); (void) FormatLocaleFile(stderr, " yy=jj*cos(aa)%+lf;\n", coeff[3] ); (void) FormatLocaleFile(stderr, " %s' \\\n", lookup); break; } case Plane2CylinderDistortion: { (void) FormatLocaleFile(stderr, "Plane to Cylinder Distort, Internal Coefficents\n"); (void) FormatLocaleFile(stderr, " cylinder_radius = %+lf\n", coeff[1]); (void) FormatLocaleFile(stderr, "Plane to Cylinder Distort, FX Equivelent:\n"); (void) FormatLocaleFile(stderr, "%s", image_gen); (void) FormatLocaleFile(stderr, " -fx 'ii=i+page.x%+lf+0.5; jj=j+page.y%+lf+0.5;\n", -coeff[4], -coeff[5]); (void) FormatLocaleFile(stderr, " ii=ii/%+lf;\n", coeff[1] ); (void) FormatLocaleFile(stderr, " xx=%lf*tan(ii)%+lf;\n", coeff[1], coeff[2] ); (void) FormatLocaleFile(stderr, " yy=jj/cos(ii)%+lf;\n", coeff[3] ); (void) FormatLocaleFile(stderr, " %s' \\\n", lookup); break; break; } case BarrelDistortion: case BarrelInverseDistortion: { double xc,yc; /* NOTE: This does the barrel roll in pixel coords not image coords ** The internal distortion must do it in image coordinates, ** so that is what the center coeff (8,9) is given in. */ xc = ((double)image->columns-1.0)/2.0 + image->page.x; yc = ((double)image->rows-1.0)/2.0 + image->page.y; (void) FormatLocaleFile(stderr, "Barrel%s Distort, FX Equivelent:\n", method == BarrelDistortion ? "" : "Inv"); (void) FormatLocaleFile(stderr, "%s", image_gen); if ( fabs(coeff[8]-xc-0.5) < 0.1 && fabs(coeff[9]-yc-0.5) < 0.1 ) (void) FormatLocaleFile(stderr, " -fx 'xc=(w-1)/2; yc=(h-1)/2;\n"); else (void) FormatLocaleFile(stderr, " -fx 'xc=%lf; yc=%lf;\n", coeff[8]-0.5, coeff[9]-0.5); (void) FormatLocaleFile(stderr, " ii=i-xc; jj=j-yc; rr=hypot(ii,jj);\n"); (void) FormatLocaleFile(stderr, " ii=ii%s(%lf*rr*rr*rr %+lf*rr*rr %+lf*rr %+lf);\n", method == BarrelDistortion ? "*" : "/", coeff[0],coeff[1],coeff[2],coeff[3]); (void) FormatLocaleFile(stderr, " jj=jj%s(%lf*rr*rr*rr %+lf*rr*rr %+lf*rr %+lf);\n", method == BarrelDistortion ? "*" : "/", coeff[4],coeff[5],coeff[6],coeff[7]); (void) FormatLocaleFile(stderr, " v.p{fx*ii+xc,fy*jj+yc}' \\\n"); } default: break; } } /* The user provided a 'scale' expert option will scale the output image size, by the factor given allowing for super-sampling of the distorted image space. Any scaling factors must naturally be halved as a result. */ { const char *artifact; artifact=GetImageArtifact(image,"distort:scale"); output_scaling = 1.0; if (artifact != (const char *) NULL) { output_scaling = fabs(StringToDouble(artifact,(char **) NULL)); geometry.width=(size_t) (output_scaling*geometry.width+0.5); geometry.height=(size_t) (output_scaling*geometry.height+0.5); geometry.x=(ssize_t) (output_scaling*geometry.x+0.5); geometry.y=(ssize_t) (output_scaling*geometry.y+0.5); if ( output_scaling < 0.1 ) { coeff = (double *) RelinquishMagickMemory(coeff); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"InvalidArgument","%s","-define distort:scale" ); return((Image *) NULL); } output_scaling = 1/output_scaling; } } #define ScaleFilter(F,A,B,C,D) \ ScaleResampleFilter( (F), \ output_scaling*(A), output_scaling*(B), \ output_scaling*(C), output_scaling*(D) ) /* Initialize the distort image attributes. */ distort_image=CloneImage(image,geometry.width,geometry.height,MagickTrue, exception); if (distort_image == (Image *) NULL) return((Image *) NULL); /* if image is ColorMapped - change it to DirectClass */ if (SetImageStorageClass(distort_image,DirectClass) == MagickFalse) { InheritException(exception,&distort_image->exception); distort_image=DestroyImage(distort_image); return((Image *) NULL); } if ((IsPixelGray(&distort_image->background_color) == MagickFalse) && (IsGrayColorspace(distort_image->colorspace) != MagickFalse)) (void) SetImageColorspace(distort_image,sRGBColorspace); if (distort_image->background_color.opacity != OpaqueOpacity) distort_image->matte=MagickTrue; distort_image->page.x=geometry.x; distort_image->page.y=geometry.y; { /* ----- MAIN CODE ----- Sample the source image to each pixel in the distort image. */ CacheView *distort_view; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; ResampleFilter **restrict resample_filter; ssize_t j; status=MagickTrue; progress=0; GetMagickPixelPacket(distort_image,&zero); resample_filter=AcquireResampleFilterThreadSet(image, UndefinedVirtualPixelMethod,MagickFalse,exception); distort_view=AcquireAuthenticCacheView(distort_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,distort_image,distort_image->rows,1) #endif for (j=0; j < (ssize_t) distort_image->rows; j++) { const int id = GetOpenMPThreadId(); double validity; /* how mathematically valid is this the mapping */ MagickBooleanType sync; MagickPixelPacket pixel, /* pixel color to assign to distorted image */ invalid; /* the color to assign when distort result is invalid */ PointInfo d, s; /* transform destination image x,y to source image x,y */ register IndexPacket *restrict indexes; register ssize_t i; register PixelPacket *restrict q; q=QueueCacheViewAuthenticPixels(distort_view,0,j,distort_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(distort_view); pixel=zero; /* Define constant scaling vectors for Affine Distortions Other methods are either variable, or use interpolated lookup */ switch (method) { case AffineDistortion: ScaleFilter( resample_filter[id], coeff[0], coeff[1], coeff[3], coeff[4] ); break; default: break; } /* Initialize default pixel validity * negative: pixel is invalid output 'matte_color' * 0.0 to 1.0: antialiased, mix with resample output * 1.0 or greater: use resampled output. */ validity = 1.0; GetMagickPixelPacket(distort_image,&invalid); SetMagickPixelPacket(distort_image,&distort_image->matte_color, (IndexPacket *) NULL, &invalid); if (distort_image->colorspace == CMYKColorspace) ConvertRGBToCMYK(&invalid); /* what about other color spaces? */ for (i=0; i < (ssize_t) distort_image->columns; i++) { /* map pixel coordinate to distortion space coordinate */ d.x = (double) (geometry.x+i+0.5)*output_scaling; d.y = (double) (geometry.y+j+0.5)*output_scaling; s = d; /* default is a no-op mapping */ switch (method) { case AffineDistortion: { s.x=coeff[0]*d.x+coeff[1]*d.y+coeff[2]; s.y=coeff[3]*d.x+coeff[4]*d.y+coeff[5]; /* Affine partial derivitives are constant -- set above */ break; } case PerspectiveDistortion: { double p,q,r,abs_r,abs_c6,abs_c7,scale; /* perspective is a ratio of affines */ p=coeff[0]*d.x+coeff[1]*d.y+coeff[2]; q=coeff[3]*d.x+coeff[4]*d.y+coeff[5]; r=coeff[6]*d.x+coeff[7]*d.y+1.0; /* Pixel Validity -- is it a 'sky' or 'ground' pixel */ validity = (r*coeff[8] < 0.0) ? 0.0 : 1.0; /* Determine horizon anti-alias blending */ abs_r = fabs(r)*2; abs_c6 = fabs(coeff[6]); abs_c7 = fabs(coeff[7]); if ( abs_c6 > abs_c7 ) { if ( abs_r < abs_c6*output_scaling ) validity = 0.5 - coeff[8]*r/(coeff[6]*output_scaling); } else if ( abs_r < abs_c7*output_scaling ) validity = 0.5 - coeff[8]*r/(coeff[7]*output_scaling); /* Perspective Sampling Point (if valid) */ if ( validity > 0.0 ) { /* divide by r affine, for perspective scaling */ scale = 1.0/r; s.x = p*scale; s.y = q*scale; /* Perspective Partial Derivatives or Scaling Vectors */ scale *= scale; ScaleFilter( resample_filter[id], (r*coeff[0] - p*coeff[6])*scale, (r*coeff[1] - p*coeff[7])*scale, (r*coeff[3] - q*coeff[6])*scale, (r*coeff[4] - q*coeff[7])*scale ); } break; } case BilinearReverseDistortion: { /* Reversed Mapped is just a simple polynomial */ s.x=coeff[0]*d.x+coeff[1]*d.y+coeff[2]*d.x*d.y+coeff[3]; s.y=coeff[4]*d.x+coeff[5]*d.y +coeff[6]*d.x*d.y+coeff[7]; /* Bilinear partial derivitives of scaling vectors */ ScaleFilter( resample_filter[id], coeff[0] + coeff[2]*d.y, coeff[1] + coeff[2]*d.x, coeff[4] + coeff[6]*d.y, coeff[5] + coeff[6]*d.x ); break; } case BilinearForwardDistortion: { /* Forward mapped needs reversed polynomial equations * which unfortunatally requires a square root! */ double b,c; d.x -= coeff[3]; d.y -= coeff[7]; b = coeff[6]*d.x - coeff[2]*d.y + coeff[8]; c = coeff[4]*d.x - coeff[0]*d.y; validity = 1.0; /* Handle Special degenerate (non-quadratic) case * Currently without horizon anti-alising */ if ( fabs(coeff[9]) < MagickEpsilon ) s.y = -c/b; else { c = b*b - 2*coeff[9]*c; if ( c < 0.0 ) validity = 0.0; else s.y = ( -b + sqrt(c) )/coeff[9]; } if ( validity > 0.0 ) s.x = ( d.x - coeff[1]*s.y) / ( coeff[0] + coeff[2]*s.y ); /* NOTE: the sign of the square root should be -ve for parts where the source image becomes 'flipped' or 'mirrored'. FUTURE: Horizon handling FUTURE: Scaling factors or Deritives (how?) */ break; } #if 0 case BilinearDistortion: /* Bilinear mapping of any Quadrilateral to any Quadrilateral */ /* UNDER DEVELOPMENT */ break; #endif case PolynomialDistortion: { /* multi-ordered polynomial */ register ssize_t k; ssize_t nterms=(ssize_t)coeff[1]; PointInfo du,dv; /* the du,dv vectors from unit dx,dy -- derivatives */ s.x=s.y=du.x=du.y=dv.x=dv.y=0.0; for(k=0; k < nterms; k++) { s.x += poly_basis_fn(k,d.x,d.y)*coeff[2+k]; du.x += poly_basis_dx(k,d.x,d.y)*coeff[2+k]; du.y += poly_basis_dy(k,d.x,d.y)*coeff[2+k]; s.y += poly_basis_fn(k,d.x,d.y)*coeff[2+k+nterms]; dv.x += poly_basis_dx(k,d.x,d.y)*coeff[2+k+nterms]; dv.y += poly_basis_dy(k,d.x,d.y)*coeff[2+k+nterms]; } ScaleFilter( resample_filter[id], du.x,du.y,dv.x,dv.y ); break; } case ArcDistortion: { /* what is the angle and radius in the destination image */ s.x = (double) ((atan2(d.y,d.x) - coeff[0])/Magick2PI); s.x -= MagickRound(s.x); /* angle */ s.y = hypot(d.x,d.y); /* radius */ /* Arc Distortion Partial Scaling Vectors Are derived by mapping the perpendicular unit vectors dR and dA*R*2PI rather than trying to map dx and dy The results is a very simple orthogonal aligned ellipse. */ if ( s.y > MagickEpsilon ) ScaleFilter( resample_filter[id], (double) (coeff[1]/(Magick2PI*s.y)), 0, 0, coeff[3] ); else ScaleFilter( resample_filter[id], distort_image->columns*2, 0, 0, coeff[3] ); /* now scale the angle and radius for source image lookup point */ s.x = s.x*coeff[1] + coeff[4] + image->page.x +0.5; s.y = (coeff[2] - s.y) * coeff[3] + image->page.y; break; } case PolarDistortion: { /* 2D Cartesain to Polar View */ d.x -= coeff[2]; d.y -= coeff[3]; s.x = atan2(d.x,d.y) - (coeff[4]+coeff[5])/2; s.x /= Magick2PI; s.x -= MagickRound(s.x); s.x *= Magick2PI; /* angle - relative to centerline */ s.y = hypot(d.x,d.y); /* radius */ /* Polar Scaling vectors are based on mapping dR and dA vectors This results in very simple orthogonal scaling vectors */ if ( s.y > MagickEpsilon ) ScaleFilter( resample_filter[id], (double) (coeff[6]/(Magick2PI*s.y)), 0, 0, coeff[7] ); else ScaleFilter( resample_filter[id], distort_image->columns*2, 0, 0, coeff[7] ); /* now finish mapping radius/angle to source x,y coords */ s.x = s.x*coeff[6] + (double)image->columns/2.0 + image->page.x; s.y = (s.y-coeff[1])*coeff[7] + image->page.y; break; } case DePolarDistortion: { /* @D Polar to Carteasain */ /* ignore all destination virtual offsets */ d.x = ((double)i+0.5)*output_scaling*coeff[6]+coeff[4]; d.y = ((double)j+0.5)*output_scaling*coeff[7]+coeff[1]; s.x = d.y*sin(d.x) + coeff[2]; s.y = d.y*cos(d.x) + coeff[3]; /* derivatives are usless - better to use SuperSampling */ break; } case Cylinder2PlaneDistortion: { /* 3D Cylinder to Tangential Plane */ double ax, cx; /* relative to center of distortion */ d.x -= coeff[4]; d.y -= coeff[5]; d.x /= coeff[1]; /* x' = x/r */ ax=atan(d.x); /* aa = atan(x/r) = u/r */ cx=cos(ax); /* cx = cos(atan(x/r)) = 1/sqrt(x^2+u^2) */ s.x = coeff[1]*ax; /* u = r*atan(x/r) */ s.y = d.y*cx; /* v = y*cos(u/r) */ /* derivatives... (see personnal notes) */ ScaleFilter( resample_filter[id], 1.0/(1.0+d.x*d.x), 0.0, -d.x*s.y*cx*cx/coeff[1], s.y/d.y ); #if 0 if ( i == 0 && j == 0 ) { fprintf(stderr, "x=%lf y=%lf u=%lf v=%lf\n", d.x*coeff[1], d.y, s.x, s.y); fprintf(stderr, "phi = %lf\n", (double)(ax * 180.0/MagickPI) ); fprintf(stderr, "du/dx=%lf du/dx=%lf dv/dx=%lf dv/dy=%lf\n", 1.0/(1.0+d.x*d.x), 0.0, -d.x*s.y*cx*cx/coeff[1], s.y/d.y ); fflush(stderr); } #endif /* add center of distortion in source */ s.x += coeff[2]; s.y += coeff[3]; break; } case Plane2CylinderDistortion: { /* 3D Cylinder to Tangential Plane */ /* relative to center of distortion */ d.x -= coeff[4]; d.y -= coeff[5]; /* is pixel valid - horizon of a infinite Virtual-Pixel Plane * (see Anthony Thyssen's personal note) */ validity = (double) ((coeff[1]*MagickPI2 - fabs(d.x))/output_scaling + 0.5); if ( validity > 0.0 ) { double cx,tx; d.x /= coeff[1]; /* x'= x/r */ cx = 1/cos(d.x); /* cx = 1/cos(x/r) */ tx = tan(d.x); /* tx = tan(x/r) */ s.x = coeff[1]*tx; /* u = r * tan(x/r) */ s.y = d.y*cx; /* v = y / cos(x/r) */ /* derivatives... (see Anthony Thyssen's personal notes) */ ScaleFilter( resample_filter[id], cx*cx, 0.0, s.y*cx/coeff[1], cx ); #if 1 /*if ( i == 0 && j == 0 ) {*/ if ( d.x == 0.5 && d.y == 0.5 ) { fprintf(stderr, "x=%lf y=%lf u=%lf v=%lf\n", d.x*coeff[1], d.y, s.x, s.y); fprintf(stderr, "radius = %lf phi = %lf validity = %lf\n", coeff[1], (double)(d.x * 180.0/MagickPI), validity ); fprintf(stderr, "du/dx=%lf du/dx=%lf dv/dx=%lf dv/dy=%lf\n", cx*cx, 0.0, s.y*cx/coeff[1], cx); fflush(stderr); } #endif } /* add center of distortion in source */ s.x += coeff[2]; s.y += coeff[3]; break; } case BarrelDistortion: case BarrelInverseDistortion: { /* Lens Barrel Distionion Correction */ double r,fx,fy,gx,gy; /* Radial Polynomial Distortion (de-normalized) */ d.x -= coeff[8]; d.y -= coeff[9]; r = sqrt(d.x*d.x+d.y*d.y); if ( r > MagickEpsilon ) { fx = ((coeff[0]*r + coeff[1])*r + coeff[2])*r + coeff[3]; fy = ((coeff[4]*r + coeff[5])*r + coeff[6])*r + coeff[7]; gx = ((3*coeff[0]*r + 2*coeff[1])*r + coeff[2])/r; gy = ((3*coeff[4]*r + 2*coeff[5])*r + coeff[6])/r; /* adjust functions and scaling for 'inverse' form */ if ( method == BarrelInverseDistortion ) { fx = 1/fx; fy = 1/fy; gx *= -fx*fx; gy *= -fy*fy; } /* Set the source pixel to lookup and EWA derivative vectors */ s.x = d.x*fx + coeff[8]; s.y = d.y*fy + coeff[9]; ScaleFilter( resample_filter[id], gx*d.x*d.x + fx, gx*d.x*d.y, gy*d.x*d.y, gy*d.y*d.y + fy ); } else { /* Special handling to avoid divide by zero when r==0 ** ** The source and destination pixels match in this case ** which was set at the top of the loop using s = d; ** otherwise... s.x=coeff[8]; s.y=coeff[9]; */ if ( method == BarrelDistortion ) ScaleFilter( resample_filter[id], coeff[3], 0, 0, coeff[7] ); else /* method == BarrelInverseDistortion */ /* FUTURE, trap for D==0 causing division by zero */ ScaleFilter( resample_filter[id], 1.0/coeff[3], 0, 0, 1.0/coeff[7] ); } break; } case ShepardsDistortion: { /* Shepards Method, or Inverse Weighted Distance for displacement around the destination image control points The input arguments are the coefficents to the function. This is more of a 'displacement' function rather than an absolute distortion function. Note: We can not determine derivatives using shepards method so only a point sample interpolatation can be used. */ size_t i; double denominator; denominator = s.x = s.y = 0; for(i=0; i<number_arguments; i+=4) { double weight = ((double)d.x-arguments[i+2])*((double)d.x-arguments[i+2]) + ((double)d.y-arguments[i+3])*((double)d.y-arguments[i+3]); weight = pow(weight,coeff[0]); /* shepards power factor */ weight = ( weight < 1.0 ) ? 1.0 : 1.0/weight; s.x += (arguments[ i ]-arguments[i+2])*weight; s.y += (arguments[i+1]-arguments[i+3])*weight; denominator += weight; } s.x /= denominator; s.y /= denominator; s.x += d.x; /* make it as relative displacement */ s.y += d.y; break; } default: break; /* use the default no-op given above */ } /* map virtual canvas location back to real image coordinate */ if ( bestfit && method != ArcDistortion ) { s.x -= image->page.x; s.y -= image->page.y; } s.x -= 0.5; s.y -= 0.5; if ( validity <= 0.0 ) { /* result of distortion is an invalid pixel - don't resample */ SetPixelPacket(distort_image,&invalid,q,indexes); } else { /* resample the source image to find its correct color */ (void) ResamplePixelColor(resample_filter[id],s.x,s.y,&pixel); /* if validity between 0.0 and 1.0 mix result with invalid pixel */ if ( validity < 1.0 ) { /* Do a blend of sample color and invalid pixel */ /* should this be a 'Blend', or an 'Over' compose */ MagickPixelCompositeBlend(&pixel,validity,&invalid,(1.0-validity), &pixel); } SetPixelPacket(distort_image,&pixel,q,indexes); } q++; indexes++; } sync=SyncCacheViewAuthenticPixels(distort_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_DistortImage) #endif proceed=SetImageProgress(image,DistortImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } distort_view=DestroyCacheView(distort_view); resample_filter=DestroyResampleFilterThreadSet(resample_filter); if (status == MagickFalse) distort_image=DestroyImage(distort_image); } /* Arc does not return an offset unless 'bestfit' is in effect And the user has not provided an overriding 'viewport'. */ if ( method == ArcDistortion && !bestfit && !viewport_given ) { distort_image->page.x = 0; distort_image->page.y = 0; } coeff = (double *) RelinquishMagickMemory(coeff); return(distort_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotateImage() creates a new image that is a rotated copy of an existing % one. Positive angles rotate counter-clockwise (right-hand rule), while % negative angles rotate clockwise. Rotated images are usually larger than % the originals and have 'empty' triangular corners. X axis. Empty % triangles left over from shearing the image are filled with the background % color defined by member 'background_color' of the image. RotateImage % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the RotateImage method is: % % Image *RotateImage(const Image *image,const double degrees, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: Specifies the number of degrees to rotate the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *RotateImage(const Image *image,const double degrees, ExceptionInfo *exception) { Image *distort_image, *rotate_image; MagickRealType angle; PointInfo shear; size_t rotations; /* Adjust rotation angle. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); angle=degrees; while (angle < -45.0) angle+=360.0; for (rotations=0; angle > 45.0; rotations++) angle-=90.0; rotations%=4; shear.x=(-tan((double) DegreesToRadians(angle)/2.0)); shear.y=sin((double) DegreesToRadians(angle)); if ((fabs(shear.x) < MagickEpsilon) && (fabs(shear.y) < MagickEpsilon)) return(IntegralRotateImage(image,rotations,exception)); distort_image=CloneImage(image,0,0,MagickTrue,exception); if (distort_image == (Image *) NULL) return((Image *) NULL); (void) SetImageVirtualPixelMethod(distort_image,BackgroundVirtualPixelMethod); rotate_image=DistortImage(distort_image,ScaleRotateTranslateDistortion,1, &degrees,MagickTrue,exception); distort_image=DestroyImage(distort_image); return(rotate_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p a r s e C o l o r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SparseColorImage(), given a set of coordinates, interpolates the colors % found at those coordinates, across the whole image, using various methods. % % The format of the SparseColorImage() method is: % % Image *SparseColorImage(const Image *image,const ChannelType channel, % const SparseColorMethod method,const size_t number_arguments, % const double *arguments,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to be filled in. % % o channel: Specify which color values (in RGBKA sequence) are being set. % This also determines the number of color_values in above. % % o method: the method to fill in the gradient between the control points. % % The methods used for SparseColor() are often simular to methods % used for DistortImage(), and even share the same code for determination % of the function coefficents, though with more dimensions (or resulting % values). % % o number_arguments: the number of arguments given. % % o arguments: array of floating point arguments for this method-- % x,y,color_values-- with color_values given as normalized values. % % o exception: return any errors or warnings in this structure % */ MagickExport Image *SparseColorImage(const Image *image, const ChannelType channel,const SparseColorMethod method, const size_t number_arguments,const double *arguments, ExceptionInfo *exception) { #define SparseColorTag "Distort/SparseColor" SparseColorMethod sparse_method; double *coeff; Image *sparse_image; size_t number_colors; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); /* Determine number of color values needed per control point */ number_colors=0; if ( channel & RedChannel ) number_colors++; if ( channel & GreenChannel ) number_colors++; if ( channel & BlueChannel ) number_colors++; if ( channel & IndexChannel ) number_colors++; if ( channel & OpacityChannel ) number_colors++; /* Convert input arguments into mapping coefficients, this this case we are mapping (distorting) colors, rather than coordinates. */ { DistortImageMethod distort_method; distort_method=(DistortImageMethod) method; if ( distort_method >= SentinelDistortion ) distort_method = ShepardsDistortion; /* Pretend to be Shepards */ coeff = GenerateCoefficients(image, &distort_method, number_arguments, arguments, number_colors, exception); if ( coeff == (double *) NULL ) return((Image *) NULL); /* Note some Distort Methods may fall back to other simpler methods, Currently the only fallback of concern is Bilinear to Affine (Barycentric), which is alaso sparse_colr method. This also ensures correct two and one color Barycentric handling. */ sparse_method = (SparseColorMethod) distort_method; if ( distort_method == ShepardsDistortion ) sparse_method = method; /* return non-distort methods to normal */ if ( sparse_method == InverseColorInterpolate ) coeff[0]=0.5; /* sqrt() the squared distance for inverse */ } /* Verbose output */ if ( GetImageArtifact(image,"verbose") != (const char *) NULL ) { switch (sparse_method) { case BarycentricColorInterpolate: { register ssize_t x=0; (void) FormatLocaleFile(stderr, "Barycentric Sparse Color:\n"); if ( channel & RedChannel ) (void) FormatLocaleFile(stderr, " -channel R -fx '%+lf*i %+lf*j %+lf' \\\n", coeff[x], coeff[x+1], coeff[x+2]),x+=3; if ( channel & GreenChannel ) (void) FormatLocaleFile(stderr, " -channel G -fx '%+lf*i %+lf*j %+lf' \\\n", coeff[x], coeff[x+1], coeff[x+2]),x+=3; if ( channel & BlueChannel ) (void) FormatLocaleFile(stderr, " -channel B -fx '%+lf*i %+lf*j %+lf' \\\n", coeff[x], coeff[x+1], coeff[x+2]),x+=3; if ( channel & IndexChannel ) (void) FormatLocaleFile(stderr, " -channel K -fx '%+lf*i %+lf*j %+lf' \\\n", coeff[x], coeff[x+1], coeff[x+2]),x+=3; if ( channel & OpacityChannel ) (void) FormatLocaleFile(stderr, " -channel A -fx '%+lf*i %+lf*j %+lf' \\\n", coeff[x], coeff[x+1], coeff[x+2]),x+=3; break; } case BilinearColorInterpolate: { register ssize_t x=0; (void) FormatLocaleFile(stderr, "Bilinear Sparse Color\n"); if ( channel & RedChannel ) (void) FormatLocaleFile(stderr, " -channel R -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n", coeff[ x ], coeff[x+1], coeff[x+2], coeff[x+3]),x+=4; if ( channel & GreenChannel ) (void) FormatLocaleFile(stderr, " -channel G -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n", coeff[ x ], coeff[x+1], coeff[x+2], coeff[x+3]),x+=4; if ( channel & BlueChannel ) (void) FormatLocaleFile(stderr, " -channel B -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n", coeff[ x ], coeff[x+1], coeff[x+2], coeff[x+3]),x+=4; if ( channel & IndexChannel ) (void) FormatLocaleFile(stderr, " -channel K -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n", coeff[ x ], coeff[x+1], coeff[x+2], coeff[x+3]),x+=4; if ( channel & OpacityChannel ) (void) FormatLocaleFile(stderr, " -channel A -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n", coeff[ x ], coeff[x+1], coeff[x+2], coeff[x+3]),x+=4; break; } default: /* sparse color method is too complex for FX emulation */ break; } } /* Generate new image for generated interpolated gradient. * ASIDE: Actually we could have just replaced the colors of the original * image, but IM Core policy, is if storage class could change then clone * the image. */ sparse_image=CloneImage(image,0,0,MagickTrue,exception); if (sparse_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(sparse_image,DirectClass) == MagickFalse) { /* if image is ColorMapped - change it to DirectClass */ InheritException(exception,&image->exception); sparse_image=DestroyImage(sparse_image); return((Image *) NULL); } { /* ----- MAIN CODE ----- */ CacheView *sparse_view; MagickBooleanType status; MagickOffsetType progress; ssize_t j; status=MagickTrue; progress=0; sparse_view=AcquireAuthenticCacheView(sparse_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,sparse_image,sparse_image->rows,1) #endif for (j=0; j < (ssize_t) sparse_image->rows; j++) { MagickBooleanType sync; MagickPixelPacket pixel; /* pixel to assign to distorted image */ register IndexPacket *restrict indexes; register ssize_t i; register PixelPacket *restrict q; q=GetCacheViewAuthenticPixels(sparse_view,0,j,sparse_image->columns, 1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(sparse_view); GetMagickPixelPacket(sparse_image,&pixel); for (i=0; i < (ssize_t) image->columns; i++) { SetMagickPixelPacket(image,q,indexes,&pixel); switch (sparse_method) { case BarycentricColorInterpolate: { register ssize_t x=0; if ( channel & RedChannel ) pixel.red = coeff[x]*i +coeff[x+1]*j +coeff[x+2], x+=3; if ( channel & GreenChannel ) pixel.green = coeff[x]*i +coeff[x+1]*j +coeff[x+2], x+=3; if ( channel & BlueChannel ) pixel.blue = coeff[x]*i +coeff[x+1]*j +coeff[x+2], x+=3; if ( channel & IndexChannel ) pixel.index = coeff[x]*i +coeff[x+1]*j +coeff[x+2], x+=3; if ( channel & OpacityChannel ) pixel.opacity = coeff[x]*i +coeff[x+1]*j +coeff[x+2], x+=3; break; } case BilinearColorInterpolate: { register ssize_t x=0; if ( channel & RedChannel ) pixel.red = coeff[x]*i + coeff[x+1]*j + coeff[x+2]*i*j + coeff[x+3], x+=4; if ( channel & GreenChannel ) pixel.green = coeff[x]*i + coeff[x+1]*j + coeff[x+2]*i*j + coeff[x+3], x+=4; if ( channel & BlueChannel ) pixel.blue = coeff[x]*i + coeff[x+1]*j + coeff[x+2]*i*j + coeff[x+3], x+=4; if ( channel & IndexChannel ) pixel.index = coeff[x]*i + coeff[x+1]*j + coeff[x+2]*i*j + coeff[x+3], x+=4; if ( channel & OpacityChannel ) pixel.opacity = coeff[x]*i + coeff[x+1]*j + coeff[x+2]*i*j + coeff[x+3], x+=4; break; } case InverseColorInterpolate: case ShepardsColorInterpolate: { /* Inverse (Squared) Distance weights average (IDW) */ size_t k; double denominator; if ( channel & RedChannel ) pixel.red = 0.0; if ( channel & GreenChannel ) pixel.green = 0.0; if ( channel & BlueChannel ) pixel.blue = 0.0; if ( channel & IndexChannel ) pixel.index = 0.0; if ( channel & OpacityChannel ) pixel.opacity = 0.0; denominator = 0.0; for(k=0; k<number_arguments; k+=2+number_colors) { register ssize_t x=(ssize_t) k+2; double weight = ((double)i-arguments[ k ])*((double)i-arguments[ k ]) + ((double)j-arguments[k+1])*((double)j-arguments[k+1]); weight = pow(weight,coeff[0]); /* inverse of power factor */ weight = ( weight < 1.0 ) ? 1.0 : 1.0/weight; if ( channel & RedChannel ) pixel.red += arguments[x++]*weight; if ( channel & GreenChannel ) pixel.green += arguments[x++]*weight; if ( channel & BlueChannel ) pixel.blue += arguments[x++]*weight; if ( channel & IndexChannel ) pixel.index += arguments[x++]*weight; if ( channel & OpacityChannel ) pixel.opacity += arguments[x++]*weight; denominator += weight; } if ( channel & RedChannel ) pixel.red /= denominator; if ( channel & GreenChannel ) pixel.green /= denominator; if ( channel & BlueChannel ) pixel.blue /= denominator; if ( channel & IndexChannel ) pixel.index /= denominator; if ( channel & OpacityChannel ) pixel.opacity /= denominator; break; } case VoronoiColorInterpolate: default: { size_t k; double minimum = MagickMaximumValue; /* Just use the closest control point you can find! */ for(k=0; k<number_arguments; k+=2+number_colors) { double distance = ((double)i-arguments[ k ])*((double)i-arguments[ k ]) + ((double)j-arguments[k+1])*((double)j-arguments[k+1]); if ( distance < minimum ) { register ssize_t x=(ssize_t) k+2; if ( channel & RedChannel ) pixel.red = arguments[x++]; if ( channel & GreenChannel ) pixel.green = arguments[x++]; if ( channel & BlueChannel ) pixel.blue = arguments[x++]; if ( channel & IndexChannel ) pixel.index = arguments[x++]; if ( channel & OpacityChannel ) pixel.opacity = arguments[x++]; minimum = distance; } } break; } } /* set the color directly back into the source image */ if ( channel & RedChannel ) pixel.red *= QuantumRange; if ( channel & GreenChannel ) pixel.green *= QuantumRange; if ( channel & BlueChannel ) pixel.blue *= QuantumRange; if ( channel & IndexChannel ) pixel.index *= QuantumRange; if ( channel & OpacityChannel ) pixel.opacity *= QuantumRange; SetPixelPacket(sparse_image,&pixel,q,indexes); q++; indexes++; } sync=SyncCacheViewAuthenticPixels(sparse_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SparseColorImage) #endif proceed=SetImageProgress(image,SparseColorTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sparse_view=DestroyCacheView(sparse_view); if (status == MagickFalse) sparse_image=DestroyImage(sparse_image); } coeff = (double *) RelinquishMagickMemory(coeff); return(sparse_image); }
GB_subassign_11.c
//------------------------------------------------------------------------------ // GB_subassign_11: C(I,J)<M,repl> += scalar ; using S //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Method 11: C(I,J)<M,repl> += scalar ; using S // M: present // Mask_comp: false // C_replace: true // accum: present // A: scalar // S: constructed // C, M: not bitmap #include "GB_unused.h" #include "GB_subassign_methods.h" GrB_Info GB_subassign_11 ( GrB_Matrix C, // input: const GrB_Index *I, const int64_t ni, const int64_t nI, const int Ikind, const int64_t Icolon [3], const GrB_Index *J, const int64_t nj, const int64_t nJ, const int Jkind, const int64_t Jcolon [3], const GrB_Matrix M, const bool Mask_struct, const GrB_BinaryOp accum, const void *scalar, const GrB_Type atype, GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (!GB_IS_BITMAP (C)) ; ASSERT (!GB_IS_FULL (C)) ; ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M //-------------------------------------------------------------------------- // S = C(I,J) //-------------------------------------------------------------------------- GB_EMPTY_TASKLIST ; GB_OK (GB_subassign_symbolic (S, C, I, ni, J, nj, true, Context)) ; //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GB_MATRIX_WAIT_IF_JUMBLED (M) ; GB_GET_C ; // C must not be bitmap GB_GET_MASK ; GB_GET_ACCUM_SCALAR ; GB_GET_S ; //-------------------------------------------------------------------------- // Method 11: C(I,J)<M,repl> += scalar ; using S //-------------------------------------------------------------------------- // Time: Optimal. All entries in M+S must be examined. All entries in S // are modified: if M(i,j)=1 then S(i,j) is used to write to the // corresponding entry in C. If M(i,j) is not present, or zero, then the // entry in C is cleared (because of C_replace). If S(i,j) is not present, // and M(i,j)=1, then the scalar is inserted into C. The only case that // can be skipped is if neither S nor M is present. As a result, this // method need not traverse all of IxJ. It can limit its traversal to the // pattern of M+S. // Method 09 and Method 11 are very similar. //-------------------------------------------------------------------------- // Parallel: M+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20) //-------------------------------------------------------------------------- if (M_is_bitmap) { // all of IxJ must be examined GB_SUBASSIGN_IXJ_SLICE ; } else { // traverse all M+S GB_SUBASSIGN_TWO_SLICE (M, S) ; } //-------------------------------------------------------------------------- // phase 1: create zombies, update entries, and count pending tuples //-------------------------------------------------------------------------- if (M_is_bitmap) { //---------------------------------------------------------------------- // phase1: M is bitmap //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iM_start, iM_end) ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t j = kfirst ; j <= klast ; j++) { //-------------------------------------------------------------- // get S(iM_start:iM_end,j) //-------------------------------------------------------------- GB_GET_VECTOR_FOR_IXJ (S, iM_start) ; int64_t pM_start = j * Mvlen ; //-------------------------------------------------------------- // do a 2-way merge of S(iM_start:iM_end,j) and M(ditto,j) //-------------------------------------------------------------- for (int64_t iM = iM_start ; iM < iM_end ; iM++) { int64_t pM = pM_start + iM ; bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iM) ; bool mij = Mb [pM] && GB_mcast (Mx, pM, msize) ; if (Sfound && !mij) { // S (i,j) is present but M (i,j) is false // ----[C A 0] or [X A 0]------------------------------- // [X A 0]: action: ( X ): still a zombie // [C A 0]: C_repl: action: ( delete ): becomes zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; GB_NEXT (S) ; } else if (!Sfound && mij) { // S (i,j) is not present, M (i,j) is true // ----[. A 1]------------------------------------------ // [. A 1]: action: ( insert ) task_pending++ ; } else if (Sfound && mij) { // S (i,j) present and M (i,j) is true GB_C_S_LOOKUP ; // ----[C A 1] or [X A 1]------------------------------- // [C A 1]: action: ( =C+A ): apply accum // [X A 1]: action: ( undelete ): zombie lives GB_withaccum_C_A_1_scalar ; GB_NEXT (S) ; } } } GB_PHASE1_TASK_WRAPUP ; } } else { //---------------------------------------------------------------------- // phase1: M is hypersparse, sparse, or full //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_TASK_DESCRIPTOR_PHASE1 ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t k = kfirst ; k <= klast ; k++) { //-------------------------------------------------------------- // get S(:,j) and M(:,j) //-------------------------------------------------------------- int64_t j = GBH (Zh, k) ; GB_GET_MAPPED (pM, pM_end, pA, pA_end, Mp, j, k, Z_to_X, Mvlen); GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen); //-------------------------------------------------------------- // do a 2-way merge of S(:,j) and M(:,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression // int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and M (:,j) have entries while (pS < pS_end && pM < pM_end) { int64_t iS = GBI (Si, pS, Svlen) ; int64_t iM = GBI (Mi, pM, Mvlen) ; if (iS < iM) { // S (i,j) is present but M (i,j) is not // ----[C A 0] or [X A 0]------------------------------- // [X A 0]: action: ( X ): still a zombie // [C A 0]: C_repl: action: ( delete ): becomes zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; GB_NEXT (S) ; } else if (iM < iS) { // S (i,j) is not present, M (i,j) is present if (GB_mcast (Mx, pM, msize)) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) task_pending++ ; } GB_NEXT (M) ; } else { // both S (i,j) and M (i,j) present GB_C_S_LOOKUP ; if (GB_mcast (Mx, pM, msize)) { // ----[C A 1] or [X A 1]--------------------------- // [C A 1]: action: ( =C+A ): apply accum // [X A 1]: action: ( undelete ): zombie lives GB_withaccum_C_A_1_scalar ; } else { // ----[C A 0] or [X A 0]--------------------------- // [X A 0]: action: ( X ): still a zombie // [C A 0]: C_repl: action: ( delete ): now zombie GB_DELETE_ENTRY ; } GB_NEXT (S) ; GB_NEXT (M) ; } } // while list S (:,j) has entries. List M (:,j) exhausted. while (pS < pS_end) { // S (i,j) is present but M (i,j) is not // ----[C A 0] or [X A 0]----------------------------------- // [X A 0]: action: ( X ): still a zombie // [C A 0]: C_repl: action: ( delete ): becomes zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; GB_NEXT (S) ; } // while list M (:,j) has entries. List S (:,j) exhausted. while (pM < pM_end) { // S (i,j) is not present, M (i,j) is present if (GB_mcast (Mx, pM, msize)) { // ----[. A 1]------------------------------------------ // [. A 1]: action: ( insert ) task_pending++ ; } GB_NEXT (M) ; } } GB_PHASE1_TASK_WRAPUP ; } } //-------------------------------------------------------------------------- // phase 2: insert pending tuples //-------------------------------------------------------------------------- GB_PENDING_CUMSUM ; if (M_is_bitmap) { //---------------------------------------------------------------------- // phase2: M is bitmap //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iM_start, iM_end) ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t j = kfirst ; j <= klast ; j++) { //-------------------------------------------------------------- // get S(iM_start:iM_end,j) //-------------------------------------------------------------- GB_GET_VECTOR_FOR_IXJ (S, iM_start) ; int64_t pM_start = j * Mvlen ; //-------------------------------------------------------------- // do a 2-way merge of S(iM_start:iM_end,j) and M(ditto,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; for (int64_t iM = iM_start ; iM < iM_end ; iM++) { int64_t pM = pM_start + iM ; bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iM) ; bool mij = Mb [pM] && GB_mcast (Mx, pM, msize) ; if (!Sfound && mij) { // S (i,j) is not present, M (i,j) is true // ----[. A 1]------------------------------------------ // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iM, Ikind, Icolon) ; GB_PENDING_INSERT (scalar) ; } else if (Sfound) { // S (i,j) present GB_NEXT (S) ; } } } GB_PHASE2_TASK_WRAPUP ; } } else { //---------------------------------------------------------------------- // phase2: M is hypersparse, sparse, or full //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_TASK_DESCRIPTOR_PHASE2 ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t k = kfirst ; k <= klast ; k++) { //-------------------------------------------------------------- // get S(:,j) and M(:,j) //-------------------------------------------------------------- int64_t j = GBH (Zh, k) ; GB_GET_MAPPED (pM, pM_end, pA, pA_end, Mp, j, k, Z_to_X, Mvlen); GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen); //-------------------------------------------------------------- // do a 2-way merge of S(:,j) and M(:,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and M (:,j) have entries while (pS < pS_end && pM < pM_end) { int64_t iS = GBI (Si, pS, Svlen) ; int64_t iM = GBI (Mi, pM, Mvlen) ; if (iS < iM) { // S (i,j) is present but M (i,j) is not GB_NEXT (S) ; } else if (iM < iS) { // S (i,j) is not present, M (i,j) is present if (GB_mcast (Mx, pM, msize)) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iM, Ikind, Icolon) ; GB_PENDING_INSERT (scalar) ; } GB_NEXT (M) ; } else { // both S (i,j) and M (i,j) present GB_NEXT (S) ; GB_NEXT (M) ; } } // while list M (:,j) has entries. List S (:,j) exhausted. while (pM < pM_end) { // S (i,j) is not present, M (i,j) is present if (GB_mcast (Mx, pM, msize)) { // ----[. A 1]------------------------------------------ // [. A 1]: action: ( insert ) int64_t iM = GBI (Mi, pM, Mvlen) ; int64_t iC = GB_ijlist (I, iM, Ikind, Icolon) ; GB_PENDING_INSERT (scalar) ; } GB_NEXT (M) ; } } GB_PHASE2_TASK_WRAPUP ; } } //-------------------------------------------------------------------------- // finalize the matrix and return result //-------------------------------------------------------------------------- GB_SUBASSIGN_WRAPUP ; }
cache.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/distribute-cache-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/registry.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/timer-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const Quantum *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static const void *GetVirtualMetacontentFromCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,Quantum *, ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,Quantum *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCacheMetacontent(CacheInfo *magick_restrict, NexusInfo *magick_restrict,ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCacheMetacontent(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static Quantum *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *magick_restrict,const MapMode, const ssize_t,const ssize_t,const size_t,const size_t, const MagickBooleanType,NexusInfo *magick_restrict,ExceptionInfo *) magick_hot_spot; #if defined(MAGICKCORE_OPENCL_SUPPORT) static void CopyOpenCLBuffer(CacheInfo *magick_restrict); #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; static ssize_t cache_anonymous_memory = (-1); static time_t cache_epoch = 0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *value; cache_info=(CacheInfo *) AcquireAlignedMemory(1,sizeof(*cache_info)); if (cache_info == (CacheInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->disk_mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); value=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } value=GetPolicyValue("cache:synchronize"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } cache_info->width_limit=GetMagickResourceLimit(WidthResource); cache_info->height_limit=GetMagickResourceLimit(HeightResource); cache_info->semaphore=AcquireSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AcquireSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickCoreSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory(2* number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *nexus_info=(NexusInfo *) AcquireQuantumMemory(2*number_threads, sizeof(**nexus_info)); if (*nexus_info == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(*nexus_info,0,2*number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) (2*number_threads); i++) { nexus_info[i]=(*nexus_info+i); if (i < (ssize_t) number_threads) nexus_info[i]->virtual_nexus=(*nexus_info+number_threads+i); nexus_info[i]->signature=MagickCoreSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % void *AcquirePixelCachePixels(const Image *image,size_t *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *AcquirePixelCachePixels(const Image *image,size_t *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); (void) exception; cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); *length=(size_t) cache_info->length; return(cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickPrivate MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickPrivate void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); /* no op-- nothing to destroy */ RelinquishSemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l i p P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPixelCacheNexus() clips the cache nexus as defined by the image clip % mask. The method returns MagickTrue if the pixel region is clipped, % otherwise MagickFalse. % % The format of the ClipPixelCacheNexus() method is: % % MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClipPixelCacheNexus(Image *image, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickSizeType number_pixels; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t n; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & WriteMaskChannel) == 0) return(MagickTrue); if ((nexus_info->region.width == 0) || (nexus_info->region.height == 0)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height, nexus_info->virtual_nexus,exception); q=nexus_info->pixels; number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (n=0; n < (ssize_t) number_pixels; n++) { double mask_alpha; register ssize_t i; if (p == (Quantum *) NULL) break; mask_alpha=QuantumScale*GetPixelWriteMask(image,p); if (fabs(mask_alpha) >= MagickEpsilon) { for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(MagickOver_((double) p[i],mask_alpha* GetPixelAlpha(image,p),(double) q[i],(double) GetPixelAlpha(image,q))); } SetPixelAlpha(image,GetPixelAlpha(image,p),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } return(n < (ssize_t) number_pixels ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickPrivate void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickCoreSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identical morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); if ((lseek(cache_info->file,0,SEEK_SET) < 0) || (lseek(clone_info->file,0,SEEK_SET) < 0)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads ((size_t) GetMagickResourceLimit(ThreadResource)) #define cache_number_threads(source,destination,chunk,multithreaded) \ num_threads((multithreaded) == 0 ? 1 : \ (((source)->type != MemoryCache) && ((source)->type != MapCache)) || \ (((destination)->type != MemoryCache) && ((destination)->type != MapCache)) ? \ MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1) : \ MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),(ssize_t) (chunk)/256),1)) MagickBooleanType optimize, status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); length=cache_info->number_channels*sizeof(*cache_info->channel_map); if ((cache_info->storage_class == clone_info->storage_class) && (cache_info->colorspace == clone_info->colorspace) && (cache_info->alpha_trait == clone_info->alpha_trait) && (cache_info->channels == clone_info->channels) && (cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) && (cache_info->metacontent_extent == clone_info->metacontent_extent)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->number_channels*cache_info->columns*cache_info->rows* sizeof(*cache_info->pixels)); if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) (void) memcpy(clone_info->metacontent,cache_info->metacontent, cache_info->columns*cache_info->rows* clone_info->metacontent_extent*sizeof(unsigned char)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(cache_info->number_threads); clone_nexus=AcquirePixelCacheNexus(clone_info->number_threads); length=cache_info->number_channels*sizeof(*cache_info->channel_map); optimize=(cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) ? MagickTrue : MagickFalse; length=(size_t) MagickMin(cache_info->number_channels*cache_info->columns, clone_info->number_channels*clone_info->columns); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; register ssize_t x; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,0,y, cache_info->columns,1,MagickFalse,cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,0,y, clone_info->columns,1,MagickFalse,clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; (void) memset(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); if (optimize != MagickFalse) (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length* sizeof(Quantum)); else { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; /* Mismatched pixel channel map. */ p=cache_nexus[id]->pixels; q=clone_nexus[id]->pixels; for (x=0; x < (ssize_t) cache_info->columns; x++) { register ssize_t i; if (x == (ssize_t) clone_info->columns) break; for (i=0; i < (ssize_t) clone_info->number_channels; i++) { PixelChannel channel; PixelTrait traits; channel=clone_info->channel_map[i].channel; traits=cache_info->channel_map[channel].traits; if (traits != UndefinedPixelTrait) *q=*(p+cache_info->channel_map[channel].offset); q++; } p+=cache_info->number_channels; } } status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) { /* Clone metacontent. */ length=(size_t) MagickMin(cache_info->metacontent_extent, clone_info->metacontent_extent); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,0,y, cache_info->columns,1,MagickFalse,cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCacheMetacontent(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,0,y, clone_info->columns,1,MagickFalse,clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; if ((clone_nexus[id]->metacontent != (void *) NULL) && (cache_nexus[id]->metacontent != (void *) NULL)) (void) memcpy(clone_nexus[id]->metacontent, cache_nexus[id]->metacontent,length*sizeof(unsigned char)); status=WritePixelCacheMetacontent(clone_info,clone_nexus[id],exception); } } clone_nexus=DestroyPixelCacheNexus(clone_nexus,clone_info->number_threads); cache_nexus=DestroyPixelCacheNexus(cache_nexus,cache_info->number_threads); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache != (void *) NULL) image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { #if defined(MAGICKCORE_OPENCL_SUPPORT) if (cache_info->opencl != (MagickCLCacheInfo) NULL) { cache_info->opencl=RelinquishMagickCLCacheInfo(cache_info->opencl, MagickTrue); cache_info->pixels=(Quantum *) NULL; break; } #endif if (cache_info->mapped == MagickFalse) cache_info->pixels=(Quantum *) RelinquishAlignedMemory( cache_info->pixels); else (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(Quantum *) NULL; if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->metacontent=(void *) NULL; } MagickPrivate Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickCoreSignature); cache_info=(CacheInfo *) RelinquishAlignedMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(Quantum *) NULL; nexus_info->pixels=(Quantum *) NULL; nexus_info->metacontent=(void *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickPrivate NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) (2*number_threads); i++) { if (nexus_info[i]->cache != (Quantum *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickCoreSignature); } *nexus_info=(NexusInfo *) RelinquishMagickMemory(*nexus_info); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontent() returns the authentic metacontent corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the associated pixels are not available. % % The format of the GetAuthenticMetacontent() method is: % % void *GetAuthenticMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void *GetAuthenticMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) { void *metacontent; metacontent=cache_info->methods. get_authentic_metacontent_from_handler(image); return(metacontent); } assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontentFromCache() returns the meta-content corresponding % with the last call to QueueAuthenticPixelsCache() or % GetAuthenticPixelsCache(). % % The format of the GetAuthenticMetacontentFromCache() method is: % % void *GetAuthenticMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *GetAuthenticMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticOpenCLBuffer() returns an OpenCL buffer used to execute OpenCL % operations. % % The format of the GetAuthenticOpenCLBuffer() method is: % % cl_mem GetAuthenticOpenCLBuffer(const Image *image, % MagickCLDevice device,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o device: the device to use. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate cl_mem GetAuthenticOpenCLBuffer(const Image *image, MagickCLDevice device,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(device != (const MagickCLDevice) NULL); cache_info=(CacheInfo *) image->cache; if ((cache_info->type == UndefinedCache) || (cache_info->reference_count > 1)) { SyncImagePixelCache((Image *) image,exception); cache_info=(CacheInfo *) image->cache; } if ((cache_info->type != MemoryCache) || (cache_info->mapped != MagickFalse)) return((cl_mem) NULL); LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->opencl != (MagickCLCacheInfo) NULL) && (cache_info->opencl->device->context != device->context)) cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); if (cache_info->opencl == (MagickCLCacheInfo) NULL) { assert(cache_info->pixels != (Quantum *) NULL); cache_info->opencl=AcquireMagickCLCacheInfo(device,cache_info->pixels, cache_info->length); } if (cache_info->opencl != (MagickCLCacheInfo) NULL) RetainOpenCLMemObject(cache_info->opencl->buffer); UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->opencl == (MagickCLCacheInfo) NULL) return((cl_mem) NULL); assert(cache_info->opencl->pixels == cache_info->pixels); return(cache_info->opencl->buffer); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (Quantum *) NULL) return((Quantum *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); if (cache_info->metacontent_extent != 0) if (ReadPixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % Quantum *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static Quantum *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated % corresponding with the last call to QueueAuthenticPixels() or % GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % Quantum *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Quantum *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a Quantum array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image has corresponding metacontent,call % GetAuthenticMetacontent() after invoking GetAuthenticPixels() to obtain the % meta-content corresponding to the region. Once the Quantum array has % been updated, the changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % Quantum *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { const CacheInfo *magick_restrict cache_info; const PixelChannelMap *magick_restrict p, *magick_restrict q; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; p=image->channel_map; q=cache_info->channel_map; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->alpha_trait != cache_info->alpha_trait) || (image->channels != cache_info->channels) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (image->number_channels != cache_info->number_channels) || (memcmp(p,q,image->number_channels*sizeof(*p)) != 0) || (image->metacontent_extent != cache_info->metacontent_extent) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cache_timelimit = MagickResourceInfinity, cpu_throttle = MagickResourceInfinity, cycles = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (cache_epoch == 0) { /* Set the expire time in seconds. */ cache_timelimit=GetMagickResourceLimit(TimeResource); cache_epoch=GetMagickTime(); } if ((cache_timelimit != MagickResourceInfinity) && ((MagickSizeType) (GetMagickTime()-cache_epoch) >= cache_timelimit)) { #if defined(ECANCELED) errno=ECANCELED; #endif cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AcquireSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { destroy=MagickTrue; image->cache=clone_info; } } RelinquishSemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ if (image->type != UndefinedType) image->type=UndefinedType; cache_info=(CacheInfo *) image->cache; if (image->colorspace != cache_info->colorspace) (void) RemoveImageProfile(image,"icc"); if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MemoryCache, MapCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType CopyPixel(const Image *image, const Quantum *source,Quantum *destination) { register ssize_t i; if (source == (const Quantum *) NULL) { destination[RedPixelChannel]=ClampToQuantum(image->background_color.red); destination[GreenPixelChannel]=ClampToQuantum( image->background_color.green); destination[BluePixelChannel]=ClampToQuantum( image->background_color.blue); destination[BlackPixelChannel]=ClampToQuantum( image->background_color.black); destination[AlphaPixelChannel]=ClampToQuantum( image->background_color.alpha); return(MagickFalse); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); destination[channel]=source[i]; } return(MagickTrue); } MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict q; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y,pixel,exception)); q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,Quantum *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); q=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,cache_info->nexus_info[id], exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelInfo() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixelInfo() method is: % % MagickBooleanType GetOneVirtualPixelInfo(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelInfo *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixelInfo(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelInfo *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); GetPixelInfo(image,pixel); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (p == (const Quantum *) NULL) return(MagickFalse); GetPixelInfoPixel(image,p,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the colorspace of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheFilename() returns the filename associated with the pixel % cache. % % The format of the GetPixelCacheFilename() method is: % % const char *GetPixelCacheFilename(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetPixelCacheFilename(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->cache_filename); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) memset(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_metacontent_from_handler= GetVirtualMetacontentFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_metacontent_from_handler= GetAuthenticMetacontentFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated % corresponding with the last call to SetPixelCacheNexusPixels() or % GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickPrivate MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=cache_info->length; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickPrivate ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimized cache tile width in pixels. % % o height: the optimized cache tile height in pixels. % */ MagickPrivate void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *width=2048UL/(MagickMax(cache_info->number_channels,1)*sizeof(Quantum)); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/(MagickMax(cache_info->number_channels,1)*sizeof(Quantum)); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromCache() returns the meta-content corresponding with % the last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualMetacontentFromCache() method is: % % void *GetVirtualMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const void *GetVirtualMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromNexus() returns the meta-content for the specified % cache nexus. % % The format of the GetVirtualMetacontentFromNexus() method is: % % const void *GetVirtualMetacontentFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the meta-content. % */ MagickPrivate const void *GetVirtualMetacontentFromNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((void *) NULL); return(nexus_info->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontent() returns the virtual metacontent corresponding with % the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the meta-content are not available. % % The format of the GetVirtualMetacontent() method is: % % const void *GetVirtualMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const void *GetVirtualMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); metacontent=cache_info->methods.get_virtual_metacontent_from_handler(image); if (metacontent != (void *) NULL) return(metacontent); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCacheNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCacheNexus() method is: % % Quantum *GetVirtualPixelCacheNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; modulo.quotient=offset/((ssize_t) extent); modulo.remainder=offset % ((ssize_t) extent); if ((modulo.remainder != 0) && ((offset ^ ((ssize_t) extent)) < 0)) { modulo.quotient-=1; modulo.remainder+=((ssize_t) extent); } return(modulo); } MagickPrivate const Quantum *GetVirtualPixelCacheNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo *magick_restrict virtual_nexus; Quantum *magick_restrict pixels, virtual_pixel[MaxPixelChannels]; register const Quantum *magick_restrict p; register const void *magick_restrict r; register Quantum *magick_restrict q; register ssize_t i, u; register unsigned char *magick_restrict s; ssize_t v; void *magick_restrict virtual_metacontent; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((const Quantum *) NULL); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,x,y,columns,rows, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); if (pixels == (Quantum *) NULL) return((const Quantum *) NULL); q=pixels; offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns-1) < (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows-1) < (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(q); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); if (cache_info->metacontent_extent != 0) { status=ReadPixelCacheMetacontent(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); } return(q); } /* Pixel request is outside cache extents. */ virtual_nexus=nexus_info->virtual_nexus; s=(unsigned char *) nexus_info->metacontent; (void) memset(virtual_pixel,0,cache_info->number_channels* sizeof(*virtual_pixel)); virtual_metacontent=(void *) NULL; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: case EdgeVirtualPixelMethod: case CheckerTileVirtualPixelMethod: case HorizontalTileVirtualPixelMethod: case VerticalTileVirtualPixelMethod: { if (cache_info->metacontent_extent != 0) { /* Acquire a metacontent buffer. */ virtual_metacontent=(void *) AcquireQuantumMemory(1, cache_info->metacontent_extent); if (virtual_metacontent == (void *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), CacheError,"UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) memset(virtual_metacontent,0,cache_info->metacontent_extent); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case GrayVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange/2, virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case TransparentVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,TransparentAlpha,virtual_pixel); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } default: { SetPixelRed(image,ClampToQuantum(image->background_color.red), virtual_pixel); SetPixelGreen(image,ClampToQuantum(image->background_color.green), virtual_pixel); SetPixelBlue(image,ClampToQuantum(image->background_color.blue), virtual_pixel); SetPixelBlack(image,ClampToQuantum(image->background_color.black), virtual_pixel); SetPixelAlpha(image,ClampToQuantum(image->background_color.alpha), virtual_pixel); break; } } break; } default: break; } for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info, nexus_info->virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=virtual_pixel; r=virtual_metacontent; break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=virtual_pixel; r=virtual_metacontent; break; } p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } } if (p == (const Quantum *) NULL) break; (void) memcpy(q,p,(size_t) (cache_info->number_channels*length* sizeof(*p))); q+=cache_info->number_channels; if ((s != (void *) NULL) && (r != (const void *) NULL)) { (void) memcpy(s,r,(size_t) cache_info->metacontent_extent); s+=cache_info->metacontent_extent; } continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,virtual_nexus,exception); if (p == (const Quantum *) NULL) break; r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); (void) memcpy(q,p,(size_t) (cache_info->number_channels*length* sizeof(*p))); q+=cache_info->number_channels*length; if ((r != (void *) NULL) && (s != (const void *) NULL)) { (void) memcpy(s,r,(size_t) length); s+=length*cache_info->metacontent_extent; } } if (u < (ssize_t) columns) break; } /* Free resources. */ if (virtual_metacontent != (void *) NULL) virtual_metacontent=(void *) RelinquishMagickMemory(virtual_metacontent); if (v < (ssize_t) rows) return((const Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const Quantum *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const Quantum *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const Quantum *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const Quantum *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % access the meta-content (of type void) corresponding to the % region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const Quantum *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const Quantum *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated corresponding with the % last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % Quantum *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const Quantum *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const Quantum *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickPrivate const Quantum *GetVirtualPixelsNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((Quantum *) NULL); return((const Quantum *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a s k P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaskPixelCacheNexus() masks the cache nexus as defined by the image mask. % The method returns MagickTrue if the pixel region is masked, otherwise % MagickFalse. % % The format of the MaskPixelCacheNexus() method is: % % MagickBooleanType MaskPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum ApplyPixelCompositeMask(const Quantum p, const MagickRealType alpha,const Quantum q,const MagickRealType beta) { double mask_alpha; Quantum pixel; if (fabs(alpha-OpaqueAlpha) < MagickEpsilon) return(p); mask_alpha=1.0-QuantumScale*QuantumScale*alpha*beta; mask_alpha=PerceptibleReciprocal(mask_alpha); pixel=ClampToQuantum(mask_alpha*MagickOver_((double) p,alpha,(double) q, beta)); return(pixel); } static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickSizeType number_pixels; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t n; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & CompositeMaskChannel) == 0) return(MagickTrue); if ((nexus_info->region.width == 0) || (nexus_info->region.height == 0)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height, nexus_info->virtual_nexus,exception); q=nexus_info->pixels; number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (n=0; n < (ssize_t) number_pixels; n++) { double mask_alpha; register ssize_t i; if (p == (Quantum *) NULL) break; mask_alpha=(double) GetPixelCompositeMask(image,p); for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyPixelCompositeMask(p[i],mask_alpha,q[i],(MagickRealType) GetPixelAlpha(image,q)); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } if (n < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % metacontent, and memory mapping the cache if it is disk based. The cache % nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->disk_mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; cache_info->disk_mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),offset+i); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MagickPathExtent], message[MagickPathExtent]; (void) FormatMagickSize(length,MagickFalse,"B",MagickPathExtent,format); (void) FormatLocaleString(message,MagickPathExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); if (count != 1) return(MagickFalse); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) if (posix_fallocate(cache_info->file,offset+1,extent-offset) != 0) return(MagickFalse); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *hosts, *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (cache_anonymous_memory < 0) { char *value; /* Does the security policy require anonymous mapping for pixel cache? */ cache_anonymous_memory=0; value=GetPolicyValue("pixel-cache-memory"); if (value == (char *) NULL) value=GetPolicyValue("cache:memory-map"); if (LocaleCompare(value,"anonymous") == 0) { #if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS) cache_anonymous_memory=1; #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn", "'%s' (policy requires anonymous memory mapping)",image->filename); #endif } value=DestroyString(value); } if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (((MagickSizeType) image->columns > cache_info->width_limit) || ((MagickSizeType) image->rows > cache_info->height_limit)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); length=GetImageListLength(image); if (AcquireMagickResource(ListLengthResource,length) == MagickFalse) ThrowBinaryException(ResourceLimitError,"ListLengthExceedsLimit", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) image->scene); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->channels=image->channels; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,(MagickSizeType) cache_info->columns*cache_info->rows); if (cache_info->mode == PersistMode) status=MagickFalse; length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)) && ((cache_info->type == UndefinedCache) || (cache_info->type == MemoryCache))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (status != MagickFalse) { status=MagickTrue; if (cache_anonymous_memory <= 0) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); } else { cache_info->mapped=MagickTrue; cache_info->pixels=(Quantum *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } if (cache_info->pixels == (Quantum *) NULL) { cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; } else { /* Create memory pixel cache. */ cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ cache_info->number_channels*number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } cache_info->storage_class=image->storage_class; if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } } status=AcquireMagickResource(DiskResource,cache_info->length); hosts=(const char *) GetImageRegistry(StringRegistryType,"cache:hosts", exception); if ((status == MagickFalse) && (hosts != (const char *) NULL)) { DistributeCacheInfo *server_info; /* Distribute the pixel cache to a remote server. */ server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ status=MagickTrue; cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } /* Create pixel cache on disk. */ if (status == MagickFalse) { cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode) && (cache_info->mode != PersistMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { cache_info->type=UndefinedCache; ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { cache_info->type=UndefinedCache; ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if (status == MagickFalse) cache_info->type=DiskCache; else if ((cache_info->type != MapCache) && (cache_info->type != MemoryCache)) { cache_info->type=DiskCache; RelinquishMagickResource(MapResource,cache_info->length); } else { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; RelinquishMagickResource(MapResource,cache_info->length); } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ cache_info->number_channels*number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MagickPathExtent); cache_info->type=MapCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(MagickTrue); } /* Clone persistent pixel cache. */ status=AcquireMagickResource(DiskResource,cache_info->length); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } clone_info=(CacheInfo *) ClonePixelCache(cache_info); clone_info->type=DiskCache; (void) CopyMagickString(clone_info->cache_filename,filename,MagickPathExtent); clone_info->file=(-1); clone_info->storage_class=cache_info->storage_class; clone_info->colorspace=cache_info->colorspace; clone_info->alpha_trait=cache_info->alpha_trait; clone_info->channels=cache_info->channels; clone_info->columns=cache_info->columns; clone_info->rows=cache_info->rows; clone_info->number_channels=cache_info->number_channels; clone_info->metacontent_extent=cache_info->metacontent_extent; clone_info->mode=PersistMode; clone_info->length=cache_info->length; (void) memcpy(clone_info->channel_map,cache_info->channel_map, MaxPixelChannels*sizeof(*cache_info->channel_map)); clone_info->offset=(*offset); status=ClonePixelCacheRepository(clone_info,cache_info,exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % Quantum *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; Quantum *magick_restrict pixels; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((Quantum *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((Quantum *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((Quantum *) NULL); /* Return pixel cache. */ pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,x,y,columns,rows, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a Quantum array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % obtain the meta-content (of type void) corresponding to the region. % Once the Quantum (and/or Quantum) array has been updated, the % changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.queue_authentic_pixels_handler(image,x,y, columns,rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheMetacontent() reads metacontent from the specified region of % the pixel cache. % % The format of the ReadPixelCacheMetacontent() method is: % % MagickBooleanType ReadPixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the metacontent. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),offset+i); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheMetacontent( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register ssize_t y; register unsigned char *magick_restrict q; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; q=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict p; /* Read meta-content from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->metacontent_extent*cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } break; } case DiskCache: { /* Read meta content from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read metacontent from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register Quantum *magick_restrict q; register ssize_t y; size_t number_channels, rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; number_channels=cache_info->number_channels; length=(MagickSizeType) number_channels*nexus_info->region.width* sizeof(Quantum); if ((length/number_channels/sizeof(Quantum)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); y=0; q=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+cache_info->number_channels*offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*q),length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickPrivate Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheChannels() resets the pixel cache channels. % % The format of the ResetPixelCacheChannels method is: % % void ResetPixelCacheChannels(Image *) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate void ResetPixelCacheChannels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); cache_info->number_channels=GetPixelChannels(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t C a c h e A n o n y m o u s M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetCacheAnonymousMemory() resets the anonymous_memory value. % % The format of the ResetCacheAnonymousMemory method is: % % void ResetCacheAnonymousMemory(void) % */ MagickPrivate void ResetCacheAnonymousMemory(void) { cache_anonymous_memory=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e E p o c h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheEpoch() resets the pixel cache epoch. % % The format of the ResetPixelCacheEpoch method is: % % void ResetPixelCacheEpoch(void) % */ MagickPrivate void ResetPixelCacheEpoch(void) { cache_epoch=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_metacontent_from_handler != (GetVirtualMetacontentFromHandler) NULL) cache_info->methods.get_virtual_metacontent_from_handler= cache_methods->get_virtual_metacontent_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) cache_info->methods.get_authentic_metacontent_from_handler= cache_methods->get_authentic_metacontent_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % Quantum SetPixelCacheNexusPixels( % const CacheInfo *magick_restrict cache_info,const MapMode mode, % const ssize_t x,const ssize_t y,const size_t width,const size_t height, % const MagickBooleanType buffered,NexusInfo *magick_restrict nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o x,y,width,height: define the region of this particular cache nexus. % % o buffered: if true, nexus pixels are buffered. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,const MagickSizeType length, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { if (length != (MagickSizeType) ((size_t) length)) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"PixelCacheAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } nexus_info->length=0; nexus_info->mapped=MagickFalse; if (cache_anonymous_memory <= 0) { nexus_info->cache=(Quantum *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) length)); if (nexus_info->cache != (Quantum *) NULL) (void) memset(nexus_info->cache,0,(size_t) length); } else { nexus_info->cache=(Quantum *) MapBlob(-1,IOMode,0,(size_t) length); if (nexus_info->cache != (Quantum *) NULL) nexus_info->mapped=MagickTrue; } if (nexus_info->cache == (Quantum *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"PixelCacheAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } nexus_info->length=length; return(MagickTrue); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { if (nexus_info->length < CACHE_LINE_SIZE) return; if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE, 0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE,1,1); } static Quantum *SetPixelCacheNexusPixels( const CacheInfo *magick_restrict cache_info,const MapMode mode, const ssize_t x,const ssize_t y,const size_t width,const size_t height, const MagickBooleanType buffered,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((Quantum *) NULL); assert(nexus_info->signature == MagickCoreSignature); (void) memset(&nexus_info->region,0,sizeof(nexus_info->region)); if ((width == 0) || (height == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "NoPixelsDefinedInCache","`%s'",cache_info->filename); return((Quantum *) NULL); } if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && (buffered == MagickFalse)) { if (((x >= 0) && (y >= 0) && (((ssize_t) height+y-1) < (ssize_t) cache_info->rows)) && (((x == 0) && (width == cache_info->columns)) || ((height == 1) && (((ssize_t) width+x-1) < (ssize_t) cache_info->columns)))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) y*cache_info->columns+x; nexus_info->pixels=cache_info->pixels+cache_info->number_channels* offset; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(unsigned char *) cache_info->metacontent+ offset*cache_info->metacontent_extent; nexus_info->region.width=width; nexus_info->region.height=height; nexus_info->region.x=x; nexus_info->region.y=y; nexus_info->authentic_pixel_cache=MagickTrue; PrefetchPixelCacheNexusPixels(nexus_info,mode); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ if (((MagickSizeType) width > cache_info->width_limit) || ((MagickSizeType) height > cache_info->height_limit)) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "WidthOrHeightExceedsLimit","`%s'",cache_info->filename); return((Quantum *) NULL); } number_pixels=(MagickSizeType) width*height; length=MagickMax(number_pixels,MagickMax(cache_info->columns, cache_info->rows))*cache_info->number_channels*sizeof(*nexus_info->pixels); if (cache_info->metacontent_extent != 0) length+=number_pixels*cache_info->metacontent_extent; status=MagickTrue; if (nexus_info->cache == (Quantum *) NULL) status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception); else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception); } if (status == MagickFalse) return((Quantum *) NULL); nexus_info->pixels=nexus_info->cache; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(void *) (nexus_info->pixels+ cache_info->number_channels*number_pixels); nexus_info->region.width=width; nexus_info->region.height=height; nexus_info->region.x=x; nexus_info->region.y=y; nexus_info->authentic_pixel_cache=cache_info->type == PingCache ? MagickTrue : MagickFalse; PrefetchPixelCacheNexusPixels(nexus_info,mode); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { 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++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } status=SyncCacheViewAuthenticPixels(image_view,exception); } image_view=DestroyCacheView(image_view); return(status); } MagickPrivate VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); if ((IsPixelInfoGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); break; } case TransparentVirtualPixelMethod: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); break; } default: break; } return(method); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticOpenCLBuffer() makes sure that all the OpenCL operations have % been completed and updates the host memory. % % The format of the SyncAuthenticOpenCLBuffer() method is: % % void SyncAuthenticOpenCLBuffer(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void CopyOpenCLBuffer(CacheInfo *magick_restrict cache_info) { assert(cache_info != (CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->type != MemoryCache) || (cache_info->opencl == (MagickCLCacheInfo) NULL)) return; /* Ensure single threaded access to OpenCL environment. */ LockSemaphoreInfo(cache_info->semaphore); cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); UnlockSemaphoreInfo(cache_info->semaphore); } MagickPrivate void SyncAuthenticOpenCLBuffer(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); cache_info=(CacheInfo *) image->cache; CopyOpenCLBuffer(cache_info); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if (image->mask_trait != UpdatePixelTrait) { if (((image->channels & WriteMaskChannel) != 0) && (ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (((image->channels & CompositeMaskChannel) != 0) && (MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); } if (nexus_info->authentic_pixel_cache != MagickFalse) { if (image->taint == MagickFalse) image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickCoreSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->metacontent_extent != 0) && (WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if ((status != MagickFalse) && (image->taint == MagickFalse)) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(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 SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) { status=cache_info->methods.sync_authentic_pixels_handler(image, exception); return(status); } assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheMetacontent() writes the meta-content to the specified region % of the pixel cache. % % The format of the WritePixelCacheMetacontent() method is: % % MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the meta-content. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const unsigned char *magick_restrict p; register ssize_t y; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=(MagickSizeType) length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict q; /* Write associated pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width*cache_info->metacontent_extent; q+=cache_info->columns*cache_info->metacontent_extent; } break; } case DiskCache: { /* Write associated pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write metacontent to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const Quantum *magick_restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) cache_info->number_channels*nexus_info->region.width* sizeof(Quantum); extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+cache_info->number_channels*offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*nexus_info->region.width; q+=cache_info->number_channels*cache_info->columns; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*p),length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
ompHelloWorld.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> int main (int argc, char **argv){ int i = 350; int sum = 0; int v= 0; #pragma omp parallel num_threads(20) reduction(+:v) { int rank = omp_get_thread_num(); int size = omp_get_num_threads(); printf("hello worldfrom OpenMP thread %d out of %d\n", rank,size); //printf("the sum is %d\n", sum); v=1; //printf("thread %d got i = %d\n",rank,i); } printf("the sum is %d\n", v); #pragma omp parallel num_threads(5) { printf("goodbye cruel world\n"); } }
mmp.c
#include "XSbench_header.h" #ifdef MPI #include<mpi.h> #endif int main( int argc, char* argv[] ) { // ===================================================================== // Initialization & Command Line Read-In // ===================================================================== int version = 19; int mype = 0; double omp_start, omp_end; int nprocs = 1; unsigned long long verification; #ifdef MPI MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &mype); #endif // Process CLI Fields -- store in "Inputs" structure Inputs in = read_CLI( argc, argv ); // Set number of OpenMP Threads #ifdef OPENMP omp_set_num_threads(in.nthreads); #endif // Print-out of Input Summary if( mype == 0 ) print_inputs( in, nprocs, version ); // ===================================================================== // Prepare Nuclide Energy Grids, Unionized Energy Grid, & Material Data // This is not reflective of a real Monte Carlo simulation workload, // therefore, do not profile this region! // ===================================================================== SimulationData SD; // If read from file mode is selected, skip initialization and load // all simulation data structures from file instead if( in.binary_mode == READ ) SD = binary_read(in); else SD = grid_init_do_not_profile( in, mype ); // If writing from file mode is selected, write all simulation data // structures to file if( in.binary_mode == WRITE && mype == 0 ) binary_write(in, SD); // ===================================================================== // Cross Section (XS) Parallel Lookup Simulation // This is the section that should be profiled, as it reflects a // realistic continuous energy Monte Carlo macroscopic cross section // lookup kernel. // ===================================================================== if( mype == 0 ) { printf("\n"); border_print(); center_print("SIMULATION", 79); border_print(); } // Start Simulation Timer omp_start = get_time(); // Run simulation if( in.simulation_method == EVENT_BASED ) { if( in.kernel_id == 0 ) verification = run_event_based_simulation(in, SD, mype); else if( in.kernel_id == 1 ) verification = run_event_based_simulation_optimization_1(in, SD, mype); else { printf("Error: No kernel ID %d found!\n", in.kernel_id); exit(1); } } else verification = run_history_based_simulation(in, SD, mype); if( mype == 0) { printf("\n" ); printf("Simulation complete.\n" ); } // End Simulation Timer omp_end = get_time(); // ===================================================================== // Output Results & Finalize // ===================================================================== // Final Hash Step verification = verification % 999983; // Print / Save Results and Exit int is_invalid_result = print_results( in, mype, omp_end-omp_start, nprocs, verification ); #ifdef MPI MPI_Finalize(); #endif return is_invalid_result; } //io.c // Prints program logo void logo(int version) { border_print(); printf( " __ __ ___________ _ \n" " \\ \\ / // ___| ___ \\ | | \n" " \\ V / \\ `--.| |_/ / ___ _ __ ___| |__ \n" " / \\ `--. \\ ___ \\/ _ \\ '_ \\ / __| '_ \\ \n" " / /^\\ \\/\\__/ / |_/ / __/ | | | (__| | | | \n" " \\/ \\/\\____/\\____/ \\___|_| |_|\\___|_| |_| \n\n" ); border_print(); center_print("Developed at Argonne National Laboratory", 79); char v[100]; sprintf(v, "Version: %d", version); center_print(v, 79); border_print(); } // Prints Section titles in center of 80 char terminal void center_print(const char *s, int width) { int length = strlen(s); int i; for (i=0; i<=(width-length)/2; i++) { fputs(" ", stdout); } fputs(s, stdout); fputs("\n", stdout); } int print_results( Inputs in, int mype, double runtime, int nprocs, unsigned long long vhash ) { // Calculate Lookups per sec int lookups = 0; if( in.simulation_method == HISTORY_BASED ) lookups = in.lookups * in.particles; else if( in.simulation_method == EVENT_BASED ) lookups = in.lookups; int lookups_per_sec = (int) ((double) lookups / runtime); // If running in MPI, reduce timing statistics and calculate average #ifdef MPI int total_lookups = 0; MPI_Barrier(MPI_COMM_WORLD); MPI_Reduce(&lookups_per_sec, &total_lookups, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); #endif int is_invalid_result = 1; // Print output if( mype == 0 ) { border_print(); center_print("RESULTS", 79); border_print(); // Print the results printf("Threads: %d\n", in.nthreads); #ifdef MPI printf("MPI ranks: %d\n", nprocs); #endif #ifdef MPI printf("Total Lookups/s: "); fancy_int(total_lookups); printf("Avg Lookups/s per MPI rank: "); fancy_int(total_lookups / nprocs); #else printf("Runtime: %.3lf seconds\n", runtime); printf("Lookups: "); fancy_int(lookups); printf("Lookups/s: "); fancy_int(lookups_per_sec); #endif } unsigned long long large = 0; unsigned long long small = 0; if( in.simulation_method == EVENT_BASED ) { small = 945990; large = 952131; } else if( in.simulation_method == HISTORY_BASED ) { small = 941535; large = 954318; } if( strcmp(in.HM, "large") == 0 ) { if( vhash == large ) is_invalid_result = 0; } else if( strcmp(in.HM, "small") == 0 ) { if( vhash == small ) is_invalid_result = 0; } if(mype == 0 ) { if( is_invalid_result ) printf("Verification checksum: %llu (WARNING - INAVALID CHECKSUM!)\n", vhash); else printf("Verification checksum: %llu (Valid)\n", vhash); border_print(); } return is_invalid_result; } void print_inputs(Inputs in, int nprocs, int version ) { // Calculate Estimate of Memory Usage int mem_tot = estimate_mem_usage( in ); logo(version); center_print("INPUT SUMMARY", 79); border_print(); if( in.simulation_method == EVENT_BASED ) printf("Simulation Method: Event Based\n"); else printf("Simulation Method: History Based\n"); if( in.grid_type == NUCLIDE ) printf("Grid Type: Nuclide Grid\n"); else if( in.grid_type == UNIONIZED ) printf("Grid Type: Unionized Grid\n"); else printf("Grid Type: Hash\n"); printf("Materials: %d\n", 12); printf("H-M Benchmark Size: %s\n", in.HM); printf("Total Nuclides: %ld\n", in.n_isotopes); printf("Gridpoints (per Nuclide): "); fancy_int(in.n_gridpoints); if( in.grid_type == HASH ) { printf("Hash Bins: "); fancy_int(in.hash_bins); } if( in.grid_type == UNIONIZED ) { printf("Unionized Energy Gridpoints: "); fancy_int(in.n_isotopes*in.n_gridpoints); } if( in.simulation_method == HISTORY_BASED ) { printf("Particle Histories: "); fancy_int(in.particles); printf("XS Lookups per Particle: "); fancy_int(in.lookups); } printf("Total XS Lookups: "); fancy_int(in.lookups); #ifdef MPI printf("MPI Ranks: %d\n", nprocs); printf("OMP Threads per MPI Rank: %d\n", in.nthreads); printf("Mem Usage per MPI Rank (MB): "); fancy_int(mem_tot); #else printf("Threads: %d\n", in.nthreads); printf("Est. Memory Usage (MB): "); fancy_int(mem_tot); #endif printf("Binary File Mode: "); if( in.binary_mode == NONE ) printf("Off\n"); else if( in.binary_mode == READ) printf("Read\n"); else printf("Write\n"); border_print(); center_print("INITIALIZATION - DO NOT PROFILE", 79); border_print(); } void border_print(void) { printf( "===================================================================" "=============\n"); } // Prints comma separated integers - for ease of reading void fancy_int( long a ) { if( a < 1000 ) printf("%ld\n",a); else if( a >= 1000 && a < 1000000 ) printf("%ld,%03ld\n", a / 1000, a % 1000); else if( a >= 1000000 && a < 1000000000 ) printf("%ld,%03ld,%03ld\n",a / 1000000,(a % 1000000) / 1000,a % 1000 ); else if( a >= 1000000000 ) printf("%ld,%03ld,%03ld,%03ld\n", a / 1000000000, (a % 1000000000) / 1000000, (a % 1000000) / 1000, a % 1000 ); else printf("%ld\n",a); } void print_CLI_error(void) { printf("Usage: ./XSBench <options>\n"); printf("Options include:\n"); printf(" -m <simulation method> Simulation method (history, event)\n"); printf(" -t <threads> Number of OpenMP threads to run\n"); printf(" -s <size> Size of H-M Benchmark to run (small, large, XL, XXL)\n"); printf(" -g <gridpoints> Number of gridpoints per nuclide (overrides -s defaults)\n"); printf(" -G <grid type> Grid search type (unionized, nuclide, hash). Defaults to unionized.\n"); printf(" -p <particles> Number of particle histories\n"); printf(" -l <lookups> History Based: Number of Cross-section (XS) lookups per particle. Event Based: Total number of XS lookups.\n"); printf(" -h <hash bins> Number of hash bins (only relevant when used with \"-G hash\")\n"); printf(" -b <binary mode> Read or write all data structures to file. If reading, this will skip initialization phase. (read, write)\n"); printf(" -k <kernel ID> Specifies which kernel to run. 0 is baseline, 1, 2, etc are optimized variants. (0 is default.)\n"); printf("Default is equivalent to: -m history -s large -l 34 -p 500000 -G unionized\n"); printf("See readme for full description of default run values\n"); exit(4); } Inputs read_CLI( int argc, char * argv[] ) { Inputs input; // defaults to the history based simulation method input.simulation_method = HISTORY_BASED; // defaults to max threads on the system #ifdef OPENMP //input.nthreads = omp_get_num_procs(); input.nthreads = #P0; #else input.nthreads = 1; #endif // defaults to 355 (corresponding to H-M Large benchmark) input.n_isotopes = 355; // defaults to 11303 (corresponding to H-M Large benchmark) input.n_gridpoints = 11303; // defaults to 500,000 input.particles = 500000; // defaults to 34 input.lookups = 34; // default to unionized grid input.grid_type = UNIONIZED; // default to unionized grid input.hash_bins = 10000; // default to no binary read/write input.binary_mode = NONE; // defaults to baseline kernel input.kernel_id = 0; // defaults to H-M Large benchmark input.HM = (char *) malloc( 6 * sizeof(char) ); input.HM[0] = 'l' ; input.HM[1] = 'a' ; input.HM[2] = 'r' ; input.HM[3] = 'g' ; input.HM[4] = 'e' ; input.HM[5] = '\0'; // Check if user sets these int user_g = 0; int default_lookups = 1; int default_particles = 1; // Collect Raw Input for( int i = 1; i < argc; i++ ) { char * arg = argv[i]; // nthreads (-t) if( strcmp(arg, "-t") == 0 ) { if( ++i < argc ) input.nthreads = atoi(argv[i]); else print_CLI_error(); } // n_gridpoints (-g) else if( strcmp(arg, "-g") == 0 ) { if( ++i < argc ) { user_g = 1; input.n_gridpoints = atol(argv[i]); } else print_CLI_error(); } // Simulation Method (-m) else if( strcmp(arg, "-m") == 0 ) { char * sim_type; if( ++i < argc ) sim_type = argv[i]; else print_CLI_error(); if( strcmp(sim_type, "history") == 0 ) input.simulation_method = HISTORY_BASED; else if( strcmp(sim_type, "event") == 0 ) { input.simulation_method = EVENT_BASED; // Also resets default # of lookups if( default_lookups && default_particles ) { input.lookups = input.lookups * input.particles; input.particles = 0; } } else print_CLI_error(); } // lookups (-l) else if( strcmp(arg, "-l") == 0 ) { if( ++i < argc ) { input.lookups = atoi(argv[i]); default_lookups = 0; } else print_CLI_error(); } // hash bins (-h) else if( strcmp(arg, "-h") == 0 ) { if( ++i < argc ) input.hash_bins = atoi(argv[i]); else print_CLI_error(); } // particles (-p) else if( strcmp(arg, "-p") == 0 ) { if( ++i < argc ) { input.particles = atoi(argv[i]); default_particles = 0; } else print_CLI_error(); } // HM (-s) else if( strcmp(arg, "-s") == 0 ) { if( ++i < argc ) input.HM = argv[i]; else print_CLI_error(); } // grid type (-G) else if( strcmp(arg, "-G") == 0 ) { char * grid_type; if( ++i < argc ) grid_type = argv[i]; else print_CLI_error(); if( strcmp(grid_type, "unionized") == 0 ) input.grid_type = UNIONIZED; else if( strcmp(grid_type, "nuclide") == 0 ) input.grid_type = NUCLIDE; else if( strcmp(grid_type, "hash") == 0 ) input.grid_type = HASH; else print_CLI_error(); } // binary mode (-b) else if( strcmp(arg, "-b") == 0 ) { char * binary_mode; if( ++i < argc ) binary_mode = argv[i]; else print_CLI_error(); if( strcmp(binary_mode, "read") == 0 ) input.binary_mode = READ; else if( strcmp(binary_mode, "write") == 0 ) input.binary_mode = WRITE; else print_CLI_error(); } // kernel optimization selection (-k) else if( strcmp(arg, "-k") == 0 ) { if( ++i < argc ) { input.kernel_id = atoi(argv[i]); } else print_CLI_error(); } else print_CLI_error(); } // Validate Input // Validate nthreads if( input.nthreads < 1 ) print_CLI_error(); // Validate n_isotopes if( input.n_isotopes < 1 ) print_CLI_error(); // Validate n_gridpoints if( input.n_gridpoints < 1 ) print_CLI_error(); // Validate lookups if( input.lookups < 1 ) print_CLI_error(); // Validate Hash Bins if( input.hash_bins < 1 ) print_CLI_error(); // Validate HM size if( strcasecmp(input.HM, "small") != 0 && strcasecmp(input.HM, "large") != 0 && strcasecmp(input.HM, "XL") != 0 && strcasecmp(input.HM, "XXL") != 0 ) print_CLI_error(); // Set HM size specific parameters // (defaults to large) if( strcasecmp(input.HM, "small") == 0 ) input.n_isotopes = 68; else if( strcasecmp(input.HM, "XL") == 0 && user_g == 0 ) input.n_gridpoints = 238847; // sized to make 120 GB XS data else if( strcasecmp(input.HM, "XXL") == 0 && user_g == 0 ) input.n_gridpoints = 238847 * 2.1; // 252 GB XS data // Return input struct return input; } void binary_write( Inputs in, SimulationData SD ) { char * fname = "XS_data.dat"; printf("Writing all data structures to binary file %s...\n", fname); FILE * fp = fopen(fname, "w"); // Write SimulationData Object. Include pointers, even though we won't be using them. fwrite(&SD, sizeof(SimulationData), 1, fp); // Write heap arrays in SimulationData Object fwrite(SD.num_nucs, sizeof(int), SD.length_num_nucs, fp); fwrite(SD.concs, sizeof(double), SD.length_concs, fp); fwrite(SD.mats, sizeof(int), SD.length_mats, fp); fwrite(SD.nuclide_grid, sizeof(NuclideGridPoint), SD.length_nuclide_grid, fp); fwrite(SD.index_grid, sizeof(int), SD.length_index_grid, fp); fwrite(SD.unionized_energy_array, sizeof(double), SD.length_unionized_energy_array, fp); fclose(fp); } SimulationData binary_read( Inputs in ) { SimulationData SD; char * fname = "XS_data.dat"; printf("Reading all data structures from binary file %s...\n", fname); FILE * fp = fopen(fname, "r"); assert(fp != NULL); // Read SimulationData Object. Include pointers, even though we won't be using them. fread(&SD, sizeof(SimulationData), 1, fp); // Allocate space for arrays on heap SD.num_nucs = (int *) malloc(SD.length_num_nucs * sizeof(int)); SD.concs = (double *) malloc(SD.length_concs * sizeof(double)); SD.mats = (int *) malloc(SD.length_mats * sizeof(int)); SD.nuclide_grid = (NuclideGridPoint *) malloc(SD.length_nuclide_grid * sizeof(NuclideGridPoint)); SD.index_grid = (int *) malloc( SD.length_index_grid * sizeof(int)); SD.unionized_energy_array = (double *) malloc( SD.length_unionized_energy_array * sizeof(double)); // Read heap arrays into SimulationData Object fread(SD.num_nucs, sizeof(int), SD.length_num_nucs, fp); fread(SD.concs, sizeof(double), SD.length_concs, fp); fread(SD.mats, sizeof(int), SD.length_mats, fp); fread(SD.nuclide_grid, sizeof(NuclideGridPoint), SD.length_nuclide_grid, fp); fread(SD.index_grid, sizeof(int), SD.length_index_grid, fp); fread(SD.unionized_energy_array, sizeof(double), SD.length_unionized_energy_array, fp); fclose(fp); return SD; } //Simulation.c //////////////////////////////////////////////////////////////////////////////////// // BASELINE FUNCTIONS //////////////////////////////////////////////////////////////////////////////////// // All "baseline" code is at the top of this file. The baseline code is a simple // implementation of the algorithm, with only minor CPU optimizations in place. // Following these functions are a number of optimized variants, // which each deploy a different combination of optimizations strategies. By // default, XSBench will only run the baseline implementation. Optimized variants // must be specifically selected using the "-k <optimized variant ID>" command // line argument. //////////////////////////////////////////////////////////////////////////////////// unsigned long long run_event_based_simulation(Inputs in, SimulationData SD, int mype) { if( mype == 0) printf("Beginning event based simulation...\n"); //////////////////////////////////////////////////////////////////////////////// // SUMMARY: Simulation Data Structure Manifest for "SD" Object // Here we list all heap arrays (and lengths) in SD that would need to be // offloaded manually if using an accelerator with a seperate memory space //////////////////////////////////////////////////////////////////////////////// // int * num_nucs; // Length = length_num_nucs; // double * concs; // Length = length_concs // int * mats; // Length = length_mats // double * unionized_energy_array; // Length = length_unionized_energy_array // int * index_grid; // Length = length_index_grid // NuclideGridPoint * nuclide_grid; // Length = length_nuclide_grid // // Note: "unionized_energy_array" and "index_grid" can be of zero length // depending on lookup method. // // Note: "Lengths" are given as the number of objects in the array, not the // number of bytes. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Begin Actual Simulation Loop //////////////////////////////////////////////////////////////////////////////// unsigned long long verification = 0; #pragma omp parallel for schedule(dynamic,#P1) reduction(+:verification) for( int i = 0; i < in.lookups; i++ ) { // Set the initial seed value uint64_t seed = STARTING_SEED; // Forward seed to lookup index (we need 2 samples per lookup) seed = fast_forward_LCG(seed, 2*i); // Randomly pick an energy and material for the particle double p_energy = LCG_random_double(&seed); int mat = pick_mat(&seed); double macro_xs_vector[5] = {0}; // Perform macroscopic Cross Section Lookup calculate_macro_xs( p_energy, // Sampled neutron energy (in lethargy) mat, // Sampled material type index neutron is in in.n_isotopes, // Total number of isotopes in simulation in.n_gridpoints, // Number of gridpoints per isotope in simulation SD.num_nucs, // 1-D array with number of nuclides per material SD.concs, // Flattened 2-D array with concentration of each nuclide in each material SD.unionized_energy_array, // 1-D Unionized energy array SD.index_grid, // Flattened 2-D grid holding indices into nuclide grid for each unionized energy level SD.nuclide_grid, // Flattened 2-D grid holding energy levels and XS_data for all nuclides in simulation SD.mats, // Flattened 2-D array with nuclide indices defining composition of each type of material macro_xs_vector, // 1-D array with result of the macroscopic cross section (5 different reaction channels) in.grid_type, // Lookup type (nuclide, hash, or unionized) in.hash_bins, // Number of hash bins used (if using hash lookup type) SD.max_num_nucs // Maximum number of nuclides present in any material ); // For verification, and to prevent the compiler from optimizing // all work out, we interrogate the returned macro_xs_vector array // to find its maximum value index, then increment the verification // value by that index. In this implementation, we prevent thread // contention by using an OMP reduction on the verification value. // For accelerators, a different approach might be required // (e.g., atomics, reduction of thread-specific values in large // array via CUDA thrust, etc). double max = -1.0; int max_idx = 0; for(int j = 0; j < 5; j++ ) { if( macro_xs_vector[j] > max ) { max = macro_xs_vector[j]; max_idx = j; } } verification += max_idx+1; } return verification; } unsigned long long run_history_based_simulation(Inputs in, SimulationData SD, int mype) { if( mype == 0) printf("Beginning history based simulation...\n"); //////////////////////////////////////////////////////////////////////////////// // SUMMARY: Simulation Data Structure Manifest for "SD" Object // Here we list all heap arrays (and lengths) in SD that would need to be // offloaded manually if using an accelerator with a seperate memory space //////////////////////////////////////////////////////////////////////////////// // int * num_nucs; // Length = length_num_nucs; // double * concs; // Length = length_concs // int * mats; // Length = length_mats // double * unionized_energy_array; // Length = length_unionized_energy_array // int * index_grid; // Length = length_index_grid // NuclideGridPoint * nuclide_grid; // Length = length_nuclide_grid // // Note: "unionized_energy_array" and "index_grid" can be of zero length // depending on lookup method. // // Note: "Lengths" are given as the number of objects in the array, not the // number of bytes. //////////////////////////////////////////////////////////////////////////////// unsigned long long verification = 0; // Begin outer lookup loop over particles. This loop is independent. #pragma omp parallel for schedule(dynamic, #P1) reduction(+:verification) for( int p = 0; p < in.particles; p++ ) { // Set the initial seed value uint64_t seed = STARTING_SEED; // Forward seed to lookup index (we need 2 samples per lookup, and // we may fast forward up to 5 times after each lookup) seed = fast_forward_LCG(seed, p*in.lookups*2*5); // Randomly pick an energy and material for the particle double p_energy = LCG_random_double(&seed); int mat = pick_mat(&seed); // Inner XS Lookup Loop // This loop is dependent! // i.e., Next iteration uses data computed in previous iter. for( int i = 0; i < in.lookups; i++ ) { double macro_xs_vector[5] = {0}; // Perform macroscopic Cross Section Lookup calculate_macro_xs( p_energy, // Sampled neutron energy (in lethargy) mat, // Sampled material type neutron is in in.n_isotopes, // Total number of isotopes in simulation in.n_gridpoints, // Number of gridpoints per isotope in simulation SD.num_nucs, // 1-D array with number of nuclides per material SD.concs, // Flattened 2-D array with concentration of each nuclide in each material SD.unionized_energy_array, // 1-D Unionized energy array SD.index_grid, // Flattened 2-D grid holding indices into nuclide grid for each unionized energy level SD.nuclide_grid, // Flattened 2-D grid holding energy levels and XS_data for all nuclides in simulation SD.mats, // Flattened 2-D array with nuclide indices for each type of material macro_xs_vector, // 1-D array with result of the macroscopic cross section (5 different reaction channels) in.grid_type, // Lookup type (nuclide, hash, or unionized) in.hash_bins, // Number of hash bins used (if using hash lookups) SD.max_num_nucs // Maximum number of nuclides present in any material ); // For verification, and to prevent the compiler from optimizing // all work out, we interrogate the returned macro_xs_vector array // to find its maximum value index, then increment the verification // value by that index. In this implementation, we prevent thread // contention by using an OMP reduction on it. For other accelerators, // a different approach might be required (e.g., atomics, reduction // of thread-specific values in large array via CUDA thrust, etc) double max = -1.0; int max_idx = 0; for(int j = 0; j < 5; j++ ) { if( macro_xs_vector[j] > max ) { max = macro_xs_vector[j]; max_idx = j; } } verification += max_idx+1; // Randomly pick next energy and material for the particle // Also incorporates results from macro_xs lookup to // enforce loop dependency. // In a real MC app, this dependency is expressed in terms // of branching physics sampling, whereas here we are just // artificially enforcing this dependence based on fast // forwarding the LCG state uint64_t n_forward = 0; for( int j = 0; j < 5; j++ ) if( macro_xs_vector[j] > 1.0 ) n_forward++; if( n_forward > 0 ) seed = fast_forward_LCG(seed, n_forward); p_energy = LCG_random_double(&seed); mat = pick_mat(&seed); } } return verification; } // Calculates the microscopic cross section for a given nuclide & energy void calculate_micro_xs( double p_energy, int nuc, long n_isotopes, long n_gridpoints, double * restrict egrid, int * restrict index_data, NuclideGridPoint * restrict nuclide_grids, long idx, double * restrict xs_vector, int grid_type, int hash_bins ){ // Variables double f; NuclideGridPoint * low, * high; // If using only the nuclide grid, we must perform a binary search // to find the energy location in this particular nuclide's grid. if( grid_type == NUCLIDE ) { // Perform binary search on the Nuclide Grid to find the index idx = grid_search_nuclide( n_gridpoints, p_energy, &nuclide_grids[nuc*n_gridpoints], 0, n_gridpoints-1); // pull ptr from nuclide grid and check to ensure that // we're not reading off the end of the nuclide's grid if( idx == n_gridpoints - 1 ) low = &nuclide_grids[nuc*n_gridpoints + idx - 1]; else low = &nuclide_grids[nuc*n_gridpoints + idx]; } else if( grid_type == UNIONIZED) // Unionized Energy Grid - we already know the index, no binary search needed. { // pull ptr from energy grid and check to ensure that // we're not reading off the end of the nuclide's grid if( index_data[idx * n_isotopes + nuc] == n_gridpoints - 1 ) low = &nuclide_grids[nuc*n_gridpoints + index_data[idx * n_isotopes + nuc] - 1]; else low = &nuclide_grids[nuc*n_gridpoints + index_data[idx * n_isotopes + nuc]]; } else // Hash grid { // load lower bounding index int u_low = index_data[idx * n_isotopes + nuc]; // Determine higher bounding index int u_high; if( idx == hash_bins - 1 ) u_high = n_gridpoints - 1; else u_high = index_data[(idx+1)*n_isotopes + nuc] + 1; // Check edge cases to make sure energy is actually between these // Then, if things look good, search for gridpoint in the nuclide grid // within the lower and higher limits we've calculated. double e_low = nuclide_grids[nuc*n_gridpoints + u_low].energy; double e_high = nuclide_grids[nuc*n_gridpoints + u_high].energy; int lower; if( p_energy <= e_low ) lower = 0; else if( p_energy >= e_high ) lower = n_gridpoints - 1; else lower = grid_search_nuclide( n_gridpoints, p_energy, &nuclide_grids[nuc*n_gridpoints], u_low, u_high); if( lower == n_gridpoints - 1 ) low = &nuclide_grids[nuc*n_gridpoints + lower - 1]; else low = &nuclide_grids[nuc*n_gridpoints + lower]; } high = low + 1; // calculate the re-useable interpolation factor f = (high->energy - p_energy) / (high->energy - low->energy); // Total XS xs_vector[0] = high->total_xs - f * (high->total_xs - low->total_xs); // Elastic XS xs_vector[1] = high->elastic_xs - f * (high->elastic_xs - low->elastic_xs); // Absorbtion XS xs_vector[2] = high->absorbtion_xs - f * (high->absorbtion_xs - low->absorbtion_xs); // Fission XS xs_vector[3] = high->fission_xs - f * (high->fission_xs - low->fission_xs); // Nu Fission XS xs_vector[4] = high->nu_fission_xs - f * (high->nu_fission_xs - low->nu_fission_xs); } // Calculates macroscopic cross section based on a given material & energy void calculate_macro_xs( double p_energy, int mat, long n_isotopes, long n_gridpoints, int * restrict num_nucs, double * restrict concs, double * restrict egrid, int * restrict index_data, NuclideGridPoint * restrict nuclide_grids, int * restrict mats, double * restrict macro_xs_vector, int grid_type, int hash_bins, int max_num_nucs ){ int p_nuc; // the nuclide we are looking up long idx = -1; double conc; // the concentration of the nuclide in the material // cleans out macro_xs_vector for( int k = 0; k < 5; k++ ) macro_xs_vector[k] = 0; // If we are using the unionized energy grid (UEG), we only // need to perform 1 binary search per macroscopic lookup. // If we are using the nuclide grid search, it will have to be // done inside of the "calculate_micro_xs" function for each different // nuclide in the material. if( grid_type == UNIONIZED ) idx = grid_search( n_isotopes * n_gridpoints, p_energy, egrid); else if( grid_type == HASH ) { double du = 1.0 / hash_bins; idx = p_energy / du; } // Once we find the pointer array on the UEG, we can pull the data // from the respective nuclide grids, as well as the nuclide // concentration data for the material // Each nuclide from the material needs to have its micro-XS array // looked up & interpolatied (via calculate_micro_xs). Then, the // micro XS is multiplied by the concentration of that nuclide // in the material, and added to the total macro XS array. // (Independent -- though if parallelizing, must use atomic operations // or otherwise control access to the xs_vector and macro_xs_vector to // avoid simulataneous writing to the same data structure) for( int j = 0; j < num_nucs[mat]; j++ ) { double xs_vector[5]; p_nuc = mats[mat*max_num_nucs + j]; conc = concs[mat*max_num_nucs + j]; calculate_micro_xs( p_energy, p_nuc, n_isotopes, n_gridpoints, egrid, index_data, nuclide_grids, idx, xs_vector, grid_type, hash_bins ); for( int k = 0; k < 5; k++ ) macro_xs_vector[k] += xs_vector[k] * conc; } } // binary search for energy on unionized energy grid // returns lower index long grid_search( long n, double quarry, double * restrict A) { long lowerLimit = 0; long upperLimit = n-1; long examinationPoint; long length = upperLimit - lowerLimit; while( length > 1 ) { examinationPoint = lowerLimit + ( length / 2 ); if( A[examinationPoint] > quarry ) upperLimit = examinationPoint; else lowerLimit = examinationPoint; length = upperLimit - lowerLimit; } return lowerLimit; } // binary search for energy on nuclide energy grid long grid_search_nuclide( long n, double quarry, NuclideGridPoint * A, long low, long high) { long lowerLimit = low; long upperLimit = high; long examinationPoint; long length = upperLimit - lowerLimit; while( length > 1 ) { examinationPoint = lowerLimit + ( length / 2 ); if( A[examinationPoint].energy > quarry ) upperLimit = examinationPoint; else lowerLimit = examinationPoint; length = upperLimit - lowerLimit; } return lowerLimit; } // picks a material based on a probabilistic distribution int pick_mat( uint64_t * seed ) { // I have a nice spreadsheet supporting these numbers. They are // the fractions (by volume) of material in the core. Not a // *perfect* approximation of where XS lookups are going to occur, // but this will do a good job of biasing the system nonetheless. double dist[12]; dist[0] = 0.140; // fuel dist[1] = 0.052; // cladding dist[2] = 0.275; // cold, borated water dist[3] = 0.134; // hot, borated water dist[4] = 0.154; // RPV dist[5] = 0.064; // Lower, radial reflector dist[6] = 0.066; // Upper reflector / top plate dist[7] = 0.055; // bottom plate dist[8] = 0.008; // bottom nozzle dist[9] = 0.015; // top nozzle dist[10] = 0.025; // top of fuel assemblies dist[11] = 0.013; // bottom of fuel assemblies double roll = LCG_random_double(seed); // makes a pick based on the distro for( int i = 0; i < 12; i++ ) { double running = 0; for( int j = i; j > 0; j-- ) running += dist[j]; if( roll < running ) return i; } return 0; } double LCG_random_double(uint64_t * seed) { // LCG parameters const uint64_t m = 9223372036854775808ULL; // 2^63 const uint64_t a = 2806196910506780709ULL; const uint64_t c = 1ULL; *seed = (a * (*seed) + c) % m; return (double) (*seed) / (double) m; } uint64_t fast_forward_LCG(uint64_t seed, uint64_t n) { // LCG parameters const uint64_t m = 9223372036854775808ULL; // 2^63 uint64_t a = 2806196910506780709ULL; uint64_t c = 1ULL; n = n % m; uint64_t a_new = 1; uint64_t c_new = 0; while(n > 0) { if(n & 1) { a_new *= a; c_new = c_new * a + c; } c *= (a + 1); a *= a; n >>= 1; } return (a_new * seed + c_new) % m; } //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // OPTIMIZED VARIANT FUNCTIONS //////////////////////////////////////////////////////////////////////////////////// // This section contains a number of optimized variants of some of the above // functions, which each deploy a different combination of optimizations strategies. // By default, XSBench will not run any of these variants. They // must be specifically selected using the "-k <optimized variant ID>" command // line argument. // // As fast parallel sorting will be required for these optimizations, we will // first define a set of key-value parallel quicksort routines. //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // Parallel Quicksort Key-Value Sorting Algorithms //////////////////////////////////////////////////////////////////////////////////// // // These algorithms are based on the parallel quicksort implementation by // Eduard Lopez published at https://github.com/eduardlopez/quicksort-parallel // // Eduard's original version was for an integer type quicksort, but I have modified // it to form two different versions that can sort key-value pairs together without // having to bundle them into a separate object. Additionally, I have modified the // optimal chunk sizes and restricted the number of threads for the array sizing // that XSBench will be using by default. // // Eduard's original implementation carries the following license, which applies to // the following functions only: // // void quickSort_parallel_internal_i_d(int* key,double * value, int left, int right, int cutoff) // void quickSort_parallel_i_d(int* key,double * value, int lenArray, int numThreads) // void quickSort_parallel_internal_d_i(double* key,int * value, int left, int right, int cutoff) // void quickSort_parallel_d_i(double* key,int * value, int lenArray, int numThreads) // // The MIT License (MIT) // // Copyright (c) 2016 Eduard López // // 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. // //////////////////////////////////////////////////////////////////////////////////// void quickSort_parallel_internal_i_d(int* key,double * value, int left, int right, int cutoff) { int i = left, j = right; int tmp; int pivot = key[(left + right) / 2]; { while (i <= j) { while (key[i] < pivot) i++; while (key[j] > pivot) j--; if (i <= j) { tmp = key[i]; key[i] = key[j]; key[j] = tmp; double tmp_v = value[i]; value[i] = value[j]; value[j] = tmp_v; i++; j--; } } } if ( ((right-left)<cutoff) ){ if (left < j){ quickSort_parallel_internal_i_d(key, value, left, j, cutoff); } if (i < right){ quickSort_parallel_internal_i_d(key, value, i, right, cutoff); } }else{ #pragma omp task { quickSort_parallel_internal_i_d(key, value, left, j, cutoff); } #pragma omp task { quickSort_parallel_internal_i_d(key, value, i, right, cutoff); } } } void quickSort_parallel_i_d(int* key,double * value, int lenArray, int numThreads){ // Set minumum problem size to still spawn threads for int cutoff = 10000; // For this problem size, more than 16 threads on CPU is not helpful if( numThreads > 16 ) numThreads = 16; #pragma omp parallel num_threads(numThreads) { #pragma omp single nowait { quickSort_parallel_internal_i_d(key,value, 0, lenArray-1, cutoff); } } } void quickSort_parallel_internal_d_i(double* key,int * value, int left, int right, int cutoff) { int i = left, j = right; double tmp; double pivot = key[(left + right) / 2]; { while (i <= j) { while (key[i] < pivot) i++; while (key[j] > pivot) j--; if (i <= j) { tmp = key[i]; key[i] = key[j]; key[j] = tmp; int tmp_v = value[i]; value[i] = value[j]; value[j] = tmp_v; i++; j--; } } } if ( ((right-left)<cutoff) ){ if (left < j){ quickSort_parallel_internal_d_i(key, value, left, j, cutoff); } if (i < right){ quickSort_parallel_internal_d_i(key, value, i, right, cutoff); } }else{ #pragma omp task { quickSort_parallel_internal_d_i(key, value, left, j, cutoff); } #pragma omp task { quickSort_parallel_internal_d_i(key, value, i, right, cutoff); } } } void quickSort_parallel_d_i(double* key,int * value, int lenArray, int numThreads){ // Set minumum problem size to still spawn threads for int cutoff = 10000; // For this problem size, more than 16 threads on CPU is not helpful if( numThreads > 16 ) numThreads = 16; #pragma omp parallel num_threads(numThreads) { #pragma omp single nowait { quickSort_parallel_internal_d_i(key,value, 0, lenArray-1, cutoff); } } } //////////////////////////////////////////////////////////////////////////////////// // Optimization 1 -- Event-based Sample/XS Lookup kernel splitting + Sorting // lookups by material and energy //////////////////////////////////////////////////////////////////////////////////// // This kernel separates out the sampling and lookup regions of the event-based // model, and then sorts the lookups by material type and energy. The goal of this // optimization is to allow for greatly improved cache locality, and XS indices // loaded from memory may be re-used for multiple lookups. // // As efficienct sorting is key for performance, we also must implement an // efficient key-value parallel sorting algorithm. We also experimented with using // the C++ version of thrust for these purposes, but found that our own implemtation // was slightly faster than the thrust library version, so for speed and // simplicity we will do not add the thrust dependency. //////////////////////////////////////////////////////////////////////////////////// unsigned long long run_event_based_simulation_optimization_1(Inputs in, SimulationData SD, int mype) { char * optimization_name = "Optimization 1 - Kernel splitting + full material & energy sort"; if( mype == 0) printf("Simulation Kernel:\"%s\"\n", optimization_name); //////////////////////////////////////////////////////////////////////////////// // Allocate Additional Data Structures Needed by Optimized Kernel //////////////////////////////////////////////////////////////////////////////// if( mype == 0) printf("Allocating additional data required by optimized kernel...\n"); size_t sz; size_t total_sz = 0; double start, stop; sz = in.lookups * sizeof(double); SD.p_energy_samples = (double *) malloc(sz); total_sz += sz; SD.length_p_energy_samples = in.lookups; sz = in.lookups * sizeof(int); SD.mat_samples = (int *) malloc(sz); total_sz += sz; SD.length_mat_samples = in.lookups; if( mype == 0) printf("Allocated an additional %.0lf MB of data on GPU.\n", total_sz/1024.0/1024.0); //////////////////////////////////////////////////////////////////////////////// // Begin Actual Simulation //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Sample Materials and Energies //////////////////////////////////////////////////////////////////////////////// #pragma omp parallel for schedule(dynamic, #P1) for( int i = 0; i < in.lookups; i++ ) { // Set the initial seed value uint64_t seed = STARTING_SEED; // Forward seed to lookup index (we need 2 samples per lookup) seed = fast_forward_LCG(seed, 2*i); // Randomly pick an energy and material for the particle double p_energy = LCG_random_double(&seed); int mat = pick_mat(&seed); SD.p_energy_samples[i] = p_energy; SD.mat_samples[i] = mat; } if(mype == 0) printf("finished sampling...\n"); //////////////////////////////////////////////////////////////////////////////// // Sort by Material //////////////////////////////////////////////////////////////////////////////// start = get_time(); quickSort_parallel_i_d(SD.mat_samples, SD.p_energy_samples, in.lookups, in.nthreads); stop = get_time(); if(mype == 0) printf("Material sort took %.3lf seconds\n", stop-start); //////////////////////////////////////////////////////////////////////////////// // Sort by Energy //////////////////////////////////////////////////////////////////////////////// start = get_time(); // Count up number of each type of sample. int num_samples_per_mat[12] = {0}; for( int l = 0; l < in.lookups; l++ ) num_samples_per_mat[ SD.mat_samples[l] ]++; // Determine offsets int offsets[12] = {0}; for( int m = 1; m < 12; m++ ) offsets[m] = offsets[m-1] + num_samples_per_mat[m-1]; stop = get_time(); if(mype == 0) printf("Counting samples and offsets took %.3lf seconds\n", stop-start); start = stop; // Sort each material type by energy level int offset = 0; for( int m = 0; m < 12; m++ ) quickSort_parallel_d_i(SD.p_energy_samples + offsets[m],SD.mat_samples + offsets[m], num_samples_per_mat[m], in.nthreads); stop = get_time(); if(mype == 0) printf("Energy Sorts took %.3lf seconds\n", stop-start); //////////////////////////////////////////////////////////////////////////////// // Perform lookups for each material separately //////////////////////////////////////////////////////////////////////////////// start = get_time(); unsigned long long verification = 0; // Individual Materials offset = 0; for( int m = 0; m < 12; m++ ) { #pragma omp parallel for schedule(dynamic,#P1) reduction(+:verification) for( int i = offset; i < offset + num_samples_per_mat[m]; i++) { // load pre-sampled energy and material for the particle double p_energy = SD.p_energy_samples[i]; int mat = SD.mat_samples[i]; double macro_xs_vector[5] = {0}; // Perform macroscopic Cross Section Lookup calculate_macro_xs( p_energy, // Sampled neutron energy (in lethargy) mat, // Sampled material type index neutron is in in.n_isotopes, // Total number of isotopes in simulation in.n_gridpoints, // Number of gridpoints per isotope in simulation SD.num_nucs, // 1-D array with number of nuclides per material SD.concs, // Flattened 2-D array with concentration of each nuclide in each material SD.unionized_energy_array, // 1-D Unionized energy array SD.index_grid, // Flattened 2-D grid holding indices into nuclide grid for each unionized energy level SD.nuclide_grid, // Flattened 2-D grid holding energy levels and XS_data for all nuclides in simulation SD.mats, // Flattened 2-D array with nuclide indices defining composition of each type of material macro_xs_vector, // 1-D array with result of the macroscopic cross section (5 different reaction channels) in.grid_type, // Lookup type (nuclide, hash, or unionized) in.hash_bins, // Number of hash bins used (if using hash lookup type) SD.max_num_nucs // Maximum number of nuclides present in any material ); // For verification, and to prevent the compiler from optimizing // all work out, we interrogate the returned macro_xs_vector array // to find its maximum value index, then increment the verification // value by that index. In this implementation, we prevent thread // contention by using an OMP reduction on the verification value. // For accelerators, a different approach might be required // (e.g., atomics, reduction of thread-specific values in large // array via CUDA thrust, etc). double max = -1.0; int max_idx = 0; for(int j = 0; j < 5; j++ ) { if( macro_xs_vector[j] > max ) { max = macro_xs_vector[j]; max_idx = j; } } verification += max_idx+1; } offset += num_samples_per_mat[m]; } stop = get_time(); if(mype == 0) printf("XS Lookups took %.3lf seconds\n", stop-start); return verification; } //GridInit.c SimulationData grid_init_do_not_profile( Inputs in, int mype ) { // Structure to hold all allocated simuluation data arrays SimulationData SD; // Keep track of how much data we're allocating size_t nbytes = 0; // Set the initial seed value uint64_t seed = 42; //////////////////////////////////////////////////////////////////// // Initialize Nuclide Grids //////////////////////////////////////////////////////////////////// if(mype == 0) printf("Intializing nuclide grids...\n"); // First, we need to initialize our nuclide grid. This comes in the form // of a flattened 2D array that hold all the information we need to define // the cross sections for all isotopes in the simulation. // The grid is composed of "NuclideGridPoint" structures, which hold the // energy level of the grid point and all associated XS data at that level. // An array of structures (AOS) is used instead of // a structure of arrays, as the grid points themselves are accessed in // a random order, but all cross section interaction channels and the // energy level are read whenever the gridpoint is accessed, meaning the // AOS is more cache efficient. // Initialize Nuclide Grid SD.length_nuclide_grid = in.n_isotopes * in.n_gridpoints; SD.nuclide_grid = (NuclideGridPoint *) malloc( SD.length_nuclide_grid * sizeof(NuclideGridPoint)); assert(SD.nuclide_grid != NULL); nbytes += SD.length_nuclide_grid * sizeof(NuclideGridPoint); for( int i = 0; i < SD.length_nuclide_grid; i++ ) { SD.nuclide_grid[i].energy = LCG_random_double(&seed); SD.nuclide_grid[i].total_xs = LCG_random_double(&seed); SD.nuclide_grid[i].elastic_xs = LCG_random_double(&seed); SD.nuclide_grid[i].absorbtion_xs = LCG_random_double(&seed); SD.nuclide_grid[i].fission_xs = LCG_random_double(&seed); SD.nuclide_grid[i].nu_fission_xs = LCG_random_double(&seed); } // Sort so that each nuclide has data stored in ascending energy order. #P2 for( int i = 0; i < in.n_isotopes; i++ ) qsort( &SD.nuclide_grid[i*in.n_gridpoints], in.n_gridpoints, sizeof(NuclideGridPoint), NGP_compare); // error debug check /* #P2 for( int i = 0; i < in.n_isotopes; i++ ) { printf("NUCLIDE %d ==============================\n", i); for( int j = 0; j < in.n_gridpoints; j++ ) printf("E%d = %lf\n", j, SD.nuclide_grid[i * in.n_gridpoints + j].energy); } */ //////////////////////////////////////////////////////////////////// // Initialize Acceleration Structure //////////////////////////////////////////////////////////////////// if( in.grid_type == NUCLIDE ) { SD.length_unionized_energy_array = 0; SD.length_index_grid = 0; } if( in.grid_type == UNIONIZED ) { if(mype == 0) printf("Intializing unionized grid...\n"); // Allocate space to hold the union of all nuclide energy data SD.length_unionized_energy_array = in.n_isotopes * in.n_gridpoints; SD.unionized_energy_array = (double *) malloc( SD.length_unionized_energy_array * sizeof(double)); assert(SD.unionized_energy_array != NULL ); nbytes += SD.length_unionized_energy_array * sizeof(double); // Copy energy data over from the nuclide energy grid #P2 for( int i = 0; i < SD.length_unionized_energy_array; i++ ) SD.unionized_energy_array[i] = SD.nuclide_grid[i].energy; // Sort unionized energy array qsort( SD.unionized_energy_array, SD.length_unionized_energy_array, sizeof(double), double_compare); // Allocate space to hold the acceleration grid indices SD.length_index_grid = SD.length_unionized_energy_array * in.n_isotopes; SD.index_grid = (int *) malloc( SD.length_index_grid * sizeof(int)); assert(SD.index_grid != NULL); nbytes += SD.length_index_grid * sizeof(int); // Generates the double indexing grid int * idx_low = (int *) calloc( in.n_isotopes, sizeof(int)); assert(idx_low != NULL ); double * energy_high = (double *) malloc( in.n_isotopes * sizeof(double)); assert(energy_high != NULL ); #P2 for( int i = 0; i < in.n_isotopes; i++ ) energy_high[i] = SD.nuclide_grid[i * in.n_gridpoints + 1].energy; for( long e = 0; e < SD.length_unionized_energy_array; e++ ) { for( long i = 0; i < in.n_isotopes; i++ ) { double unionized_energy = SD.unionized_energy_array[e]; if( unionized_energy < energy_high[i] ) SD.index_grid[e * in.n_isotopes + i] = idx_low[i]; else if( idx_low[i] == in.n_gridpoints - 2 ) SD.index_grid[e * in.n_isotopes + i] = idx_low[i]; else { idx_low[i]++; SD.index_grid[e * in.n_isotopes + i] = idx_low[i]; energy_high[i] = SD.nuclide_grid[i * in.n_gridpoints + idx_low[i] + 1].energy; } } } free(idx_low); free(energy_high); } if( in.grid_type == HASH ) { if(mype == 0) printf("Intializing hash grid...\n"); SD.length_unionized_energy_array = 0; SD.length_index_grid = in.hash_bins * in.n_isotopes; SD.index_grid = (int *) malloc( SD.length_index_grid * sizeof(int)); assert(SD.index_grid != NULL); nbytes += SD.length_index_grid * sizeof(int); double du = 1.0 / in.hash_bins; // For each energy level in the hash table #pragma omp parallel for for( long e = 0; e < in.hash_bins; e++ ) { double energy = e * du; // We need to determine the bounding energy levels for all isotopes for( long i = 0; i < in.n_isotopes; i++ ) { SD.index_grid[e * in.n_isotopes + i] = grid_search_nuclide( in.n_gridpoints, energy, SD.nuclide_grid + i * in.n_gridpoints, 0, in.n_gridpoints-1); } } } //////////////////////////////////////////////////////////////////// // Initialize Materials and Concentrations //////////////////////////////////////////////////////////////////// if(mype == 0) printf("Intializing material data...\n"); // Set the number of nuclides in each material SD.num_nucs = load_num_nucs(in.n_isotopes); SD.length_num_nucs = 12; // There are always 12 materials in XSBench // Intialize the flattened 2D grid of material data. The grid holds // a list of nuclide indices for each of the 12 material types. The // grid is allocated as a full square grid, even though not all // materials have the same number of nuclides. SD.mats = load_mats(SD.num_nucs, in.n_isotopes, &SD.max_num_nucs); SD.length_mats = SD.length_num_nucs * SD.max_num_nucs; // Intialize the flattened 2D grid of nuclide concentration data. The grid holds // a list of nuclide concentrations for each of the 12 material types. The // grid is allocated as a full square grid, even though not all // materials have the same number of nuclides. SD.concs = load_concs(SD.num_nucs, SD.max_num_nucs); SD.length_concs = SD.length_mats; if(mype == 0) printf("Intialization complete. Allocated %.0lf MB of data.\n", nbytes/1024.0/1024.0 ); return SD; }
rmse.c
/*************************************************************************/ /** File: rmse.c **/ /** Description: calculate root mean squared error of particular **/ /** clustering. **/ /** Author: Sang-Ha Lee **/ /** University of Virginia. **/ /** **/ /** Note: euclid_dist_2() and find_nearest_point() adopted from **/ /** Minebench code. **/ /** **/ /*************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <float.h> #include <math.h> #include <omp.h> #include "kmeans.h" extern double wtime(void); /*----< euclid_dist_2() >----------------------------------------------------*/ /* multi-dimensional spatial Euclid distance square */ __inline float euclid_dist_2(float *pt1, float *pt2, int numdims) { int i; float ans=0.0; for (i=0; i<numdims; i++) ans += (pt1[i]-pt2[i]) * (pt1[i]-pt2[i]); return(ans); } /*----< find_nearest_point() >-----------------------------------------------*/ __inline int find_nearest_point(float *pt, /* [nfeatures] */ int nfeatures, float **pts, /* [npts][nfeatures] */ int npts) { int index, i; float max_dist=FLT_MAX; /* find the cluster center id with min distance to pt */ for (i=0; i<npts; i++) { float dist; dist = euclid_dist_2(pt, pts[i], nfeatures); /* no need square root */ if (dist < max_dist) { max_dist = dist; index = i; } } return(index); } /*----< rms_err(): calculates RMSE of clustering >-------------------------------------*/ float rms_err (float **feature, /* [npoints][nfeatures] */ int nfeatures, int npoints, float **cluster_centres, /* [nclusters][nfeatures] */ int nclusters) { int i; int nearest_cluster_index; /* cluster center id with min distance to pt */ float sum_euclid = 0.0; /* sum of Euclidean distance squares */ float ret; /* return value */ /* calculate and sum the sqaure of euclidean distance*/ /*#pragma omp parallel for \ shared(feature,cluster_centres) \ firstprivate(npoints,nfeatures,nclusters) \ private(i, nearest_cluster_index) \ schedule (static)*/ for (i=0; i<npoints; i++) { nearest_cluster_index = find_nearest_point(feature[i], nfeatures, cluster_centres, nclusters); sum_euclid += euclid_dist_2(feature[i], cluster_centres[nearest_cluster_index], nfeatures); } /* divide by n, then take sqrt */ ret = sqrt(sum_euclid / npoints); return(ret); }
interpolation_v2.c
//------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ #include <math.h> //------------------------------------------------------------------------------------------------------------------------------ static inline void interpolation_v2_block(level_type *level_f, int id_f, double prescale_f, level_type *level_c, int id_c, blockCopy_type *block){ // interpolate 3D array from read_i,j,k of read[] to write_i,j,k in write[] using volume averaged quadratic prolongation int write_dim_i = block->dim.i<<1; // calculate the dimensions of the resultant fine block int write_dim_j = block->dim.j<<1; int write_dim_k = block->dim.k<<1; int read_i = block->read.i; int read_j = block->read.j; int read_k = block->read.k; int read_jStride = block->read.jStride; int read_kStride = block->read.kStride; int write_i = block->write.i; int write_j = block->write.j; int write_k = block->write.k; int write_jStride = block->write.jStride; int write_kStride = block->write.kStride; const double * __restrict__ read = block->read.ptr; double * __restrict__ write = block->write.ptr; if(block->read.box >=0){ read_jStride = level_c->my_boxes[block->read.box ].jStride; read_kStride = level_c->my_boxes[block->read.box ].kStride; read = level_c->my_boxes[ block->read.box].vectors[id_c] + level_c->box_ghosts*(1+ read_jStride+ read_kStride); } if(block->write.box>=0){ write_jStride = level_f->my_boxes[block->write.box].jStride; write_kStride = level_f->my_boxes[block->write.box].kStride; write = level_f->my_boxes[block->write.box].vectors[id_f] + level_f->box_ghosts*(1+write_jStride+write_kStride); } #ifdef USE_NAIVE_INTERP // naive 27pt per fine grid cell int i,j,k; double c1 = 1.0/8.0; for(k=0;k<write_dim_k;k++){double c1k=c1;if(k&0x1){c1k=-c1;} for(j=0;j<write_dim_j;j++){double c1j=c1;if(j&0x1){c1j=-c1;} for(i=0;i<write_dim_i;i++){double c1i=c1;if(i&0x1){c1i=-c1;} int write_ijk = ((i )+write_i) + (((j )+write_j)*write_jStride) + (((k )+write_k)*write_kStride); int read_ijk = ((i>>1)+ read_i) + (((j>>1)+ read_j)* read_jStride) + (((k>>1)+ read_k)* read_kStride); // // | 1/8 | 1.0 | -1/8 | coarse grid // |---+---|---+---|---+---| // | | |???| | | | fine grid // write[write_ijk] = prescale_f*write[write_ijk] + + c1k*( + c1j*( c1i*read[read_ijk-1-read_jStride-read_kStride] + read[read_ijk-read_jStride-read_kStride] - c1i*read[read_ijk+1-read_jStride-read_kStride] ) + ( c1i*read[read_ijk-1 -read_kStride] + read[read_ijk -read_kStride] - c1i*read[read_ijk+1 -read_kStride] ) - c1j*( c1i*read[read_ijk-1+read_jStride-read_kStride] + read[read_ijk+read_jStride-read_kStride] - c1i*read[read_ijk+1+read_jStride-read_kStride] ) ) + ( + c1j*( c1i*read[read_ijk-1-read_jStride ] + read[read_ijk-read_jStride ] - c1i*read[read_ijk+1-read_jStride ] ) + ( c1i*read[read_ijk-1 ] + read[read_ijk ] - c1i*read[read_ijk+1 ] ) - c1j*( c1i*read[read_ijk-1+read_jStride ] + read[read_ijk+read_jStride ] - c1i*read[read_ijk+1+read_jStride ] ) ) - c1k*( + c1j*( c1i*read[read_ijk-1-read_jStride+read_kStride] + read[read_ijk-read_jStride+read_kStride] - c1i*read[read_ijk+1-read_jStride+read_kStride] ) + ( c1i*read[read_ijk-1 +read_kStride] + read[read_ijk +read_kStride] - c1i*read[read_ijk+1 +read_kStride] ) - c1j*( c1i*read[read_ijk-1+read_jStride+read_kStride] + read[read_ijk+read_jStride+read_kStride] - c1i*read[read_ijk+1+read_jStride+read_kStride] ) ); }}} #else int i,j,k; int ii,jj,kk; double c1 = 1.0/8.0; for(k=0,kk=0;k<write_dim_k;k+=2,kk++){ for(j=0,jj=0;j<write_dim_j;j+=2,jj++){ // compiler cannot infer/speculate write[ijk+write_jStride] is disjoint from write[ijk], so create a unique restrict pointers for each nonliteral offset... double * __restrict__ write00 = write + write_i + (write_j+j+0)*write_jStride + (write_k+k+0)*write_kStride; double * __restrict__ write10 = write + write_i + (write_j+j+1)*write_jStride + (write_k+k+0)*write_kStride; double * __restrict__ write01 = write + write_i + (write_j+j+0)*write_jStride + (write_k+k+1)*write_kStride; double * __restrict__ write11 = write + write_i + (write_j+j+1)*write_jStride + (write_k+k+1)*write_kStride; for(i=0,ii=0;i<write_dim_i;i+=2,ii++){ int read_ijk = (ii+ read_i) + (jj+ read_j)* read_jStride + (kk+ read_k)* read_kStride; // // | 1/8 | 1.0 | -1/8 | coarse grid // |---+---|---+---|---+---| // | | |???| | | | fine grid // // grab all coarse grid points... const double c000=read[read_ijk-1-read_jStride-read_kStride], c100=read[read_ijk -read_jStride-read_kStride], c200=read[read_ijk+1-read_jStride-read_kStride]; const double c010=read[read_ijk-1 -read_kStride], c110=read[read_ijk -read_kStride], c210=read[read_ijk+1 -read_kStride]; const double c020=read[read_ijk-1+read_jStride-read_kStride], c120=read[read_ijk +read_jStride-read_kStride], c220=read[read_ijk+1+read_jStride-read_kStride]; const double c001=read[read_ijk-1-read_jStride ], c101=read[read_ijk -read_jStride ], c201=read[read_ijk+1-read_jStride ]; const double c011=read[read_ijk-1 ], c111=read[read_ijk ], c211=read[read_ijk+1 ]; const double c021=read[read_ijk-1+read_jStride ], c121=read[read_ijk +read_jStride ], c221=read[read_ijk+1+read_jStride ]; const double c002=read[read_ijk-1-read_jStride+read_kStride], c102=read[read_ijk -read_jStride+read_kStride], c202=read[read_ijk+1-read_jStride+read_kStride]; const double c012=read[read_ijk-1 +read_kStride], c112=read[read_ijk +read_kStride], c212=read[read_ijk+1 +read_kStride]; const double c022=read[read_ijk-1+read_jStride+read_kStride], c122=read[read_ijk +read_jStride+read_kStride], c222=read[read_ijk+1+read_jStride+read_kStride]; // interpolate in i to create fine i / coarse jk points... // // +-------+-------+-------+ :.......+---+---+.......: // | | | | : | | | : // | c | c | c | : | f | f | : // | | | | : | | | : // +-------+-------+-------+ :.......+---+---+.......: // | | | | : | | | : // | c | c | c | -> : | f | f | : // | | | | : | | | : // +-------+-------+-------+ :.......+---+---+.......: // | | | | : | | | : // | c | c | c | : | f | f | : // | | | | : | | | : // +-------+-------+-------+ :.......+---+---+.......: // const double f0c00 = ( c100 + c1*(c000-c200) ); // same as original 3pt stencil... f0c00 = ( c1*c000 + c100 - c1*c200 ); const double f1c00 = ( c100 - c1*(c000-c200) ); const double f0c10 = ( c110 + c1*(c010-c210) ); const double f1c10 = ( c110 - c1*(c010-c210) ); const double f0c20 = ( c120 + c1*(c020-c220) ); const double f1c20 = ( c120 - c1*(c020-c220) ); const double f0c01 = ( c101 + c1*(c001-c201) ); const double f1c01 = ( c101 - c1*(c001-c201) ); const double f0c11 = ( c111 + c1*(c011-c211) ); const double f1c11 = ( c111 - c1*(c011-c211) ); const double f0c21 = ( c121 + c1*(c021-c221) ); const double f1c21 = ( c121 - c1*(c021-c221) ); const double f0c02 = ( c102 + c1*(c002-c202) ); const double f1c02 = ( c102 - c1*(c002-c202) ); const double f0c12 = ( c112 + c1*(c012-c212) ); const double f1c12 = ( c112 - c1*(c012-c212) ); const double f0c22 = ( c122 + c1*(c022-c222) ); const double f1c22 = ( c122 - c1*(c022-c222) ); // interpolate in j to create fine ij / coarse k points... // // :.......+---+---+.......: :.......:.......:.......: // : | | | : : : : : // : | | | : : : : : // : | | | : : : : : // :.......+---+---+.......: :.......+---+---+.......: // : | | | : : | | | : // : | | | : -> : +---+---+ : // : | | | : : | | | : // :.......+---+---+.......: :.......+---+---+.......: // : | | | : : : : : // : | | | : : : : : // : | | | : : : : : // :.......+---+---+.......: :.......:.......:.......: // const double f00c0 = ( f0c10 + c1*(f0c00-f0c20) ); const double f10c0 = ( f1c10 + c1*(f1c00-f1c20) ); const double f01c0 = ( f0c10 - c1*(f0c00-f0c20) ); const double f11c0 = ( f1c10 - c1*(f1c00-f1c20) ); const double f00c1 = ( f0c11 + c1*(f0c01-f0c21) ); const double f10c1 = ( f1c11 + c1*(f1c01-f1c21) ); const double f01c1 = ( f0c11 - c1*(f0c01-f0c21) ); const double f11c1 = ( f1c11 - c1*(f1c01-f1c21) ); const double f00c2 = ( f0c12 + c1*(f0c02-f0c22) ); const double f10c2 = ( f1c12 + c1*(f1c02-f1c22) ); const double f01c2 = ( f0c12 - c1*(f0c02-f0c22) ); const double f11c2 = ( f1c12 - c1*(f1c02-f1c22) ); // interpolate in k to create fine ijk points... const double f000 = ( f00c1 + c1*(f00c0-f00c2) ); const double f100 = ( f10c1 + c1*(f10c0-f10c2) ); const double f010 = ( f01c1 + c1*(f01c0-f01c2) ); const double f110 = ( f11c1 + c1*(f11c0-f11c2) ); const double f001 = ( f00c1 - c1*(f00c0-f00c2) ); const double f101 = ( f10c1 - c1*(f10c0-f10c2) ); const double f011 = ( f01c1 - c1*(f01c0-f01c2) ); const double f111 = ( f11c1 - c1*(f11c0-f11c2) ); // commit to memory... #if 0 // compiler cannot infer/speculate write[ijk+write_jStride] is disjoint from write[ijk], and thus cannot vectorize... int write_ijk = ( i+write_i) + ( j+write_j)*write_jStride + ( k+write_k)*write_kStride; write[write_ijk ] = prescale_f*write[write_ijk ] + f000; write[write_ijk+1 ] = prescale_f*write[write_ijk+1 ] + f100; write[write_ijk +write_jStride ] = prescale_f*write[write_ijk +write_jStride ] + f010; write[write_ijk+1+write_jStride ] = prescale_f*write[write_ijk+1+write_jStride ] + f110; write[write_ijk +write_kStride] = prescale_f*write[write_ijk +write_kStride] + f001; write[write_ijk+1 +write_kStride] = prescale_f*write[write_ijk+1 +write_kStride] + f101; write[write_ijk +write_jStride+write_kStride] = prescale_f*write[write_ijk +write_jStride+write_kStride] + f011; write[write_ijk+1+write_jStride+write_kStride] = prescale_f*write[write_ijk+1+write_jStride+write_kStride] + f111; #else // use a unique restrict pointer for each pencil... write00[i ] = prescale_f*write00[i ] + f000; write00[i+1] = prescale_f*write00[i+1] + f100; write10[i ] = prescale_f*write10[i ] + f010; write10[i+1] = prescale_f*write10[i+1] + f110; write01[i ] = prescale_f*write01[i ] + f001; write01[i+1] = prescale_f*write01[i+1] + f101; write11[i ] = prescale_f*write11[i ] + f011; write11[i+1] = prescale_f*write11[i+1] + f111; #endif }}} #endif } //------------------------------------------------------------------------------------------------------------------------------ // perform a (inter-level) volumetric quadratic interpolation on vector id_c of the coarse level and increments prescale_f*vector id_f on the fine level by the result // i.e. id_f = prescale_f*id_f + P*id_c // prescale_f is nominally 1.0 or 0.0 // quadratic interpolation requires a full ghost zone exchange and boundary condition // This is a rather bulk synchronous implementation which packs all MPI buffers before initiating any sends // Similarly, it waits for all remote data before copying any into local boxes. // It does however attempt to overlap local interpolation with MPI void interpolation_v2(level_type * level_f, int id_f, double prescale_f, level_type *level_c, int id_c){ exchange_boundary(level_c,id_c,STENCIL_SHAPE_BOX); apply_BCs_v2(level_c,id_c,STENCIL_SHAPE_BOX); double _timeCommunicationStart = getTime(); double _timeStart,_timeEnd; int buffer=0; int n; int my_tag = (level_f->tag<<4) | 0x7; #ifdef USE_MPI // by convention, level_f allocates a combined array of requests for both level_f recvs and level_c sends... int nMessages = level_c->interpolation.num_sends + level_f->interpolation.num_recvs; MPI_Request *recv_requests = level_f->interpolation.requests; MPI_Request *send_requests = level_f->interpolation.requests + level_f->interpolation.num_recvs; // loop through packed list of MPI receives and prepost Irecv's... if(level_f->interpolation.num_recvs>0){ _timeStart = getTime(); #ifdef USE_MPI_THREAD_MULTIPLE #pragma omp parallel for schedule(dynamic,1) #endif for(n=0;n<level_f->interpolation.num_recvs;n++){ MPI_Irecv(level_f->interpolation.recv_buffers[n], level_f->interpolation.recv_sizes[n], MPI_DOUBLE, level_f->interpolation.recv_ranks[n], my_tag, MPI_COMM_WORLD, &recv_requests[n] ); } _timeEnd = getTime(); level_f->timers.interpolation_recv += (_timeEnd-_timeStart); } // pack MPI send buffers... if(level_c->interpolation.num_blocks[0]>0){ _timeStart = getTime(); PRAGMA_THREAD_ACROSS_BLOCKS(level_f,buffer,level_c->interpolation.num_blocks[0]) for(buffer=0;buffer<level_c->interpolation.num_blocks[0];buffer++){ // !!! prescale==0 because you don't want to increment the MPI buffer interpolation_v2_block(level_f,id_f,0.0,level_c,id_c,&level_c->interpolation.blocks[0][buffer]); } _timeEnd = getTime(); level_f->timers.interpolation_pack += (_timeEnd-_timeStart); } // loop through MPI send buffers and post Isend's... if(level_c->interpolation.num_sends>0){ _timeStart = getTime(); #ifdef USE_MPI_THREAD_MULTIPLE #pragma omp parallel for schedule(dynamic,1) #endif for(n=0;n<level_c->interpolation.num_sends;n++){ MPI_Isend(level_c->interpolation.send_buffers[n], level_c->interpolation.send_sizes[n], MPI_DOUBLE, level_c->interpolation.send_ranks[n], my_tag, MPI_COMM_WORLD, &send_requests[n] ); } _timeEnd = getTime(); level_f->timers.interpolation_send += (_timeEnd-_timeStart); } #endif // perform local interpolation... try and hide within Isend latency... if(level_c->interpolation.num_blocks[1]>0){ _timeStart = getTime(); PRAGMA_THREAD_ACROSS_BLOCKS(level_f,buffer,level_c->interpolation.num_blocks[1]) for(buffer=0;buffer<level_c->interpolation.num_blocks[1];buffer++){ interpolation_v2_block(level_f,id_f,prescale_f,level_c,id_c,&level_c->interpolation.blocks[1][buffer]); } _timeEnd = getTime(); level_f->timers.interpolation_local += (_timeEnd-_timeStart); } // wait for MPI to finish... #ifdef USE_MPI if(nMessages>0){ _timeStart = getTime(); MPI_Waitall(nMessages,level_f->interpolation.requests,level_f->interpolation.status); _timeEnd = getTime(); level_f->timers.interpolation_wait += (_timeEnd-_timeStart); } // unpack MPI receive buffers if(level_f->interpolation.num_blocks[2]>0){ _timeStart = getTime(); PRAGMA_THREAD_ACROSS_BLOCKS(level_f,buffer,level_f->interpolation.num_blocks[2]) for(buffer=0;buffer<level_f->interpolation.num_blocks[2];buffer++){ IncrementBlock(level_f,id_f,prescale_f,&level_f->interpolation.blocks[2][buffer]); } _timeEnd = getTime(); level_f->timers.interpolation_unpack += (_timeEnd-_timeStart); } #endif level_f->timers.interpolation_total += (double)(getTime()-_timeCommunicationStart); }
solution-openmp.c
// Translate this file with // // g++ -O3 --std=c++11 assignment-2019.c -o assignment // // Run it with // // ./assignment // // There should be a result.pvd file that you can open with Paraview. // Sometimes, Paraview requires to select the representation "Point Gaussian" // to see something meaningful. // // (C) 2019 Tobias Weinzierl #include <fstream> #include <sstream> #include <iostream> #include <string> #include <cmath> #include <limits> #ifdef _OPENMP #include <omp.h> /* use OpenMP only if needed */ #endif double t = 0; double tFinal = 0; double tPlot = 0; double tPlotDelta = 0; int NumberOfBodies = 0; /** * Pointer to pointers. Each pointer in turn points to three coordinates, i.e. * each pointer represents one molecule/particle/body. You are allowed to make * AoS vs SoA optimisations. Just keep in mind that such modifications are often * time-consuming (be economic with your investments) and that the output of the * code may not change! */ double** x; /** * Equivalent to x storing the velocities. */ double** v; /** * Global time step size used. */ double timeStepSize = 0.0001; /** * Maximum velocity of all particles. */ double maxV; /** * Minimum distance between two elements. */ double minDx; /** * Set up scenario from the command line. * * This operation is not to be changed in the assignment. */ void setUp(int argc, char** argv) { NumberOfBodies = (argc-2) / 6; x = new double*[NumberOfBodies]; v = new double*[NumberOfBodies]; int readArgument = 1; tPlotDelta = std::stof(argv[readArgument]); readArgument++; tFinal = std::stof(argv[readArgument]); readArgument++; for (int i=0; i<NumberOfBodies; i++) { x[i] = new double[3]; v[i] = new double[3]; x[i][0] = std::stof(argv[readArgument]); readArgument++; x[i][1] = std::stof(argv[readArgument]); readArgument++; x[i][2] = std::stof(argv[readArgument]); readArgument++; v[i][0] = std::stof(argv[readArgument]); readArgument++; v[i][1] = std::stof(argv[readArgument]); readArgument++; v[i][2] = std::stof(argv[readArgument]); readArgument++; } std::cout << "created setup with " << NumberOfBodies << " bodies" << std::endl; if (tPlotDelta<=0.0) { std::cout << "plotting switched off" << std::endl; tPlot = tFinal + 1.0; } else { std::cout << "plot initial setup plus every " << tPlotDelta << " time units" << std::endl; tPlot = 0.0; } } std::ofstream videoFile; /** * This operation is not to be changed in the assignment. */ void openParaviewVideoFile() { videoFile.open( "result.pvd" ); videoFile << "<?xml version=\"1.0\"?>" << std::endl << "<VTKFile type=\"Collection\" version=\"0.1\" byte_order=\"LittleEndian\" compressor=\"vtkZLibDataCompressor\">" << std::endl << "<Collection>"; } /** * This operation is not to be changed in the assignment. */ void closeParaviewVideoFile() { videoFile << "</Collection>" << "</VTKFile>" << std::endl; } /** * The file format is documented at http://www.vtk.org/wp-content/uploads/2015/04/file-formats.pdf * * This operation is not to be changed in the assignment. */ void printParaviewSnapshot() { static int counter = -1; counter++; std::stringstream filename; filename << "result-" << counter << ".vtp"; std::ofstream out( filename.str().c_str() ); out << "<VTKFile type=\"PolyData\" >" << std::endl << "<PolyData>" << std::endl << " <Piece NumberOfPoints=\"" << NumberOfBodies << "\">" << std::endl << " <Points>" << std::endl << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">"; for (int i=0; i<NumberOfBodies; i++) { out << x[i][0] << " " << x[i][1] << " " << x[i][2] << " "; } out << " </DataArray>" << std::endl << " </Points>" << std::endl << " </Piece>" << std::endl << "</PolyData>" << std::endl << "</VTKFile>" << std::endl; videoFile << "<DataSet timestep=\"" << counter << "\" group=\"\" part=\"0\" file=\"" << filename.str() << "\"/>" << std::endl; } /** * This is the operation you should primarily change in the assignment. Please * keep to the method topology, i.e. do not subdivide further. Also try to have * as many modifications as possible in this part - some initialisation/clean up * likely goes somewhere else, but the main stuff should be done here. * * See array documentations, too. */ void updateBody() { maxV = 0.0; minDx = std::numeric_limits<double>::max(); const double sigma = 3.4e-10; const double epsilon = 1.64e-21; const double mass = 39.948; double* force0 = new double[NumberOfBodies]; double* force1 = new double[NumberOfBodies]; double* force2 = new double[NumberOfBodies]; #pragma omp parallel { // double tempDx = 0; #pragma omp for for (int i=0; i<NumberOfBodies; i++) { force0[i] = 0.0; force1[i] = 0.0; force2[i] = 0.0; #pragma omp parallel for reduction(min: minDx) for (int j=0; j<NumberOfBodies; j++) { if (i!=j) { const double distance = sqrt( (x[j][0]-x[i][0]) * (x[j][0]-x[i][0]) + (x[j][1]-x[i][1]) * (x[j][1]-x[i][1]) + (x[j][2]-x[i][2]) * (x[j][2]-x[i][2]) ); minDx = std::min( minDx,distance ); double quantity = 4.0 * epsilon * ( -12.0 * std::pow(sigma,12.0) / std::pow(distance,12.0) + 6.0 * std::pow(sigma,6.0) / std::pow(distance,6.0) ) / distance; force0[i] += (x[j][0]-x[i][0]) * quantity / distance ; force1[i] += (x[j][1]-x[i][1]) * quantity / distance ; force2[i] += (x[j][2]-x[i][2]) * quantity / distance ; } } } //#pragma omp critical // { // minDx = std::min(minDx,tempDx); // } } #pragma omp parallel for for (int i=0; i<NumberOfBodies; i++) { x[i][0] = x[i][0] + timeStepSize * v[i][0]; x[i][1] = x[i][1] + timeStepSize * v[i][1]; x[i][2] = x[i][2] + timeStepSize * v[i][2]; } //#pragma omp parallel // { // double tempV = 0; #pragma omp parallel for reduction(max: maxV) for (int i=0; i<NumberOfBodies; i++) { v[i][0] = v[i][0] + timeStepSize * force0[i] / mass; v[i][1] = v[i][1] + timeStepSize * force1[i] / mass; v[i][2] = v[i][2] + timeStepSize * force2[i] / mass; double thisV = std::sqrt( v[i][0]*v[i][0] + v[i][1]*v[i][1] + v[i][2]*v[i][2] ); maxV = std::max(maxV,thisV); } //#pragma omp critical // { // maxV = std::max(tempV,maxV); // } // } delete[] force0; delete[] force1; delete[] force2; t += timeStepSize; } /** * Main routine. * * Not to be changed in assignment. */ int main(int argc, char** argv) { if (argc==1) { std::cerr << "usage: " + std::string(argv[0]) + " snapshot final-time objects" << std::endl << " snapshot interval after how many time units to plot. Use 0 to switch off plotting" << std::endl << " final-time simulated time (greater 0)" << std::endl << std::endl << "Examples:" << std::endl << "10.0 10000.0 0 0 0 0 0 0 2e-9 0 0 0 0 0 0.9e-9 1e-9 0 0 0 0 \t Three body setup" << std::endl << std::endl; return -1; } else if ( (argc-3)%6!=0 ) { std::cerr << "error in arguments: each planet is given by six entries (position, velocity)" << std::endl; return -2; } setUp(argc,argv); openParaviewVideoFile(); int snapshotCounter = 0; if (t > tPlot) { printParaviewSnapshot(); std::cout << "plotted initial setup" << std::endl; tPlot = tPlotDelta; } int timeStepCounter = 0; while (t<=tFinal) { updateBody(); timeStepCounter++; if (t >= tPlot) { printParaviewSnapshot(); std::cout << "plot next snapshot" << ",\t time step=" << timeStepCounter << ",\t t=" << t << ",\t dt=" << timeStepSize << ",\t v_max=" << maxV << ",\t dx_min=" << minDx << std::endl; tPlot += tPlotDelta; } } closeParaviewVideoFile(); return 0; }
GB_unop__identity_uint64_uint8.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__identity_uint64_uint8) // op(A') function: GB (_unop_tran__identity_uint64_uint8) // C type: uint64_t // A type: uint8_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint64_t z = (uint64_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = (uint64_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_UINT64 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint64_uint8) ( uint64_t *Cx, // Cx and Ax may be aliased const uint8_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++) { uint8_t aij = Ax [p] ; uint64_t z = (uint64_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 ; uint8_t aij = Ax [p] ; uint64_t z = (uint64_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_uint64_uint8) ( 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
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-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] = 8; tile_size[3] = 32; 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 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=Nt-1;t1++) { lbp=ceild(t1+1,2); ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1,2),ceild(8*t2-Nz+5,8));t3<=min(floord(4*Nt+Ny-9,8),floord(4*t1+Ny-1,8));t3++) { for (t4=max(max(ceild(t1-6,8),ceild(8*t2-Nz-19,32)),ceild(8*t3-Ny-19,32));t4<=min(min(floord(4*Nt+Nx-9,32),floord(4*t1+Nx-1,32)),floord(8*t3+Nx-5,32));t4++) { for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(32*t4-Nx+5,4)),t1);t5<=min(min(min(2*t3,Nt-1),t1+1),8*t4+6);t5++) { for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) { lbv=max(32*t4,4*t5+4); ubv=min(32*t4+31,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(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; }
nonNested.c
// OpenMP Non-Nested Example #include <omp.h> #include <stdio.h> #include <stdlib.h> int main( int argc, char** argv ) { // Not turning on nesting or turning off dynamic threads. // Outer Level Parallel Region - 2 Threads #pragma omp parallel num_threads( 2 ) { printf( "Outer Level - You will see this twice.\n" ); // Inner Level Parallel Region - 2 Threads Each #pragma omp parallel num_threads( 2 ) { printf( "Inner Level - You will NOT see this four times! Important steps are not complete!\n" ); } } return 0; } // End nonNested.c - EWG SDG
ch-placement-decluster-check.c
/* * Copyright (C) 2013 University of Chicago. * See COPYRIGHT notice in top-level directory. * */ #include <string.h> #include <assert.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <limits.h> #include <sys/time.h> #include "ch-placement-oid-gen.h" #include "ch-placement.h" struct options { unsigned int num_servers; unsigned int num_objs; unsigned int replication; char* placement; unsigned int virt_factor; unsigned int kill_svr; int seed; }; static int usage (char *exename); static struct options *parse_args(int argc, char *argv[]); int main( int argc, char **argv) { struct options *ig_opts = NULL; unsigned long total_byte_count = 0; unsigned long total_obj_count = 0; struct obj* total_objs = NULL; unsigned int i; struct ch_placement_instance *instance; unsigned long *replica_targets; ig_opts = parse_args(argc, argv); if(!ig_opts) { usage(argv[0]); return(-1); } replica_targets = malloc(ig_opts->num_servers*sizeof(*replica_targets)); if(!replica_targets) { perror("malloc"); return(-1); } memset(replica_targets, 0, ig_opts->num_servers*sizeof(*replica_targets)); instance = ch_placement_initialize(ig_opts->placement, ig_opts->num_servers, ig_opts->virt_factor, ig_opts->seed); /* generate random set of objects for testing */ printf("# Generating random object IDs...\n"); oid_gen("random", instance, ig_opts->num_objs, ULONG_MAX, ig_opts->seed, ig_opts->replication+1, ig_opts->num_servers, NULL, &total_byte_count, &total_obj_count, &total_objs); printf("# Done.\n"); printf("# Object population consuming approximately %lu MiB of memory.\n", (ig_opts->num_objs*sizeof(*total_objs))/(1024*1024)); assert(total_obj_count == ig_opts->num_objs); printf("# Calculating placement for each object ID...\n"); #pragma omp parallel for for(i=0; i<ig_opts->num_objs; i++) { ch_placement_find_closest(instance, total_objs[i].oid, ig_opts->replication+1, total_objs[i].server_idxs); } printf("# Done.\n"); #pragma omp parallel for for(i=0; i<ig_opts->num_objs; i++) { int j; for(j=0; j<ig_opts->replication; j++) { if(total_objs[i].server_idxs[j] == ig_opts->kill_svr) { replica_targets[total_objs[i].server_idxs[ig_opts->replication]]++; break; } } } printf("# Simulating failure of server %u out of %u\n", ig_opts->kill_svr, ig_opts->num_servers); printf("# Total objects: %u\n", ig_opts->num_objs); printf("# <svr_idx>\t<num new replicas>\n"); for(i=0; i<ig_opts->num_servers; i++) { printf("%u\t%lu\n", i, replica_targets[i]); } /* we don't need the global list any more */ free(total_objs); total_obj_count = 0; total_byte_count = 0; free(replica_targets); return(0); } static int usage (char *exename) { fprintf(stderr, "Usage: %s [options]\n", exename); fprintf(stderr, " -s <number of servers>\n"); fprintf(stderr, " -o <number of objects>\n"); fprintf(stderr, " -r <replication factor>\n"); fprintf(stderr, " -p <placement algorithm>\n"); fprintf(stderr, " -v <virtual nodes per physical node>\n"); fprintf(stderr, " -k <server to kill>\n"); fprintf(stderr, " -z <random seed/hash salt>\n"); exit(1); } static struct options *parse_args(int argc, char *argv[]) { struct options *opts = NULL; int ret = -1; int one_opt = 0; opts = (struct options*)malloc(sizeof(*opts)); if(!opts) return(NULL); memset(opts, 0, sizeof(*opts)); while((one_opt = getopt(argc, argv, "s:o:r:hp:v:k:z:")) != EOF) { switch(one_opt) { case 'k': ret = sscanf(optarg, "%u", &opts->kill_svr); if(ret != 1) return(NULL); break; case 's': ret = sscanf(optarg, "%u", &opts->num_servers); if(ret != 1) return(NULL); break; case 'o': ret = sscanf(optarg, "%u", &opts->num_objs); if(ret != 1) return(NULL); break; case 'v': ret = sscanf(optarg, "%u", &opts->virt_factor); if(ret != 1) return(NULL); break; case 'z': ret = sscanf(optarg, "%d", &opts->seed); if(ret != 1) return(NULL); break; case 'r': ret = sscanf(optarg, "%u", &opts->replication); if(ret != 1) return(NULL); break; case 'p': opts->placement = strdup(optarg); if(!opts->placement) return(NULL); break; case '?': usage(argv[0]); exit(1); } } if(opts->replication < 2) return(NULL); if(opts->num_servers < (opts->replication+1)) return(NULL); if(opts->num_objs < 1) return(NULL); if(opts->virt_factor < 1) return(NULL); if(!opts->placement) return(NULL); if(opts->kill_svr >= opts->num_servers) return(NULL); assert((opts->replication+1) <= CH_MAX_REPLICATION); return(opts); } /* * Local variables: * c-indent-level: 4 * c-basic-offset: 4 * End: * * vim: ft=c ts=8 sts=4 sw=4 expandtab */
r_numint.c
/* Copyright 2014-2018 The PySCF Developers. 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. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <stdio.h> #include <complex.h> #include "config.h" #include "gto/grid_ao_drv.h" #include "np_helper/np_helper.h" #include "vhf/fblas.h" #include <assert.h> #define BOXSIZE 56 int VXCao_empty_blocks(int8_t *empty, uint8_t *non0table, int *shls_slice, int *ao_loc); static void dot_ao_dm(double complex *vm, double complex *ao, double complex *dm, int nao, int nocc, int ngrids, int bgrids, uint8_t *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; int8_t empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double complex Z1 = 1; double complex beta = 0; if (has0) { int box_id, blen, i, j; size_t b0; for (box_id = 0; box_id < nbox; box_id++) { if (!empty[box_id]) { b0 = box_id * BOXSIZE; blen = MIN(nao-b0, BOXSIZE); zgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &blen, &Z1, ao+b0*ngrids, &ngrids, dm+b0*nocc, &nocc, &beta, vm, &ngrids); beta = 1.0; } } if (beta == 0) { // all empty for (i = 0; i < nocc; i++) { for (j = 0; j < bgrids; j++) { vm[i*ngrids+j] = 0; } } } } else { zgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &nao, &Z1, ao, &ngrids, dm, &nocc, &beta, vm, &ngrids); } } /* vm[nocc,ngrids] = ao[i,ngrids] * dm[i,nocc] */ void VXCzdot_ao_dm(double complex *vm, double complex *ao, double complex *dm, int nao, int nocc, int ngrids, int nbas, uint8_t *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; #pragma omp parallel { int ip, ib; #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_dm(vm+ip, ao+ip, dm, nao, nocc, ngrids, MIN(ngrids-ip, BLKSIZE), non0table+ib*nbas, shls_slice, ao_loc); } } } /* conj(vv[n,m]) = ao1[n,ngrids] * conj(ao2[m,ngrids]) */ static void dot_ao_ao(double complex *vv, double complex *ao1, double complex *ao2, int nao, int ngrids, int bgrids, int hermi, uint8_t *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; int8_t empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_C = 'C'; const char TRANS_N = 'N'; const double complex Z1 = 1; if (has0) { int ib, jb, leni, lenj; int j1 = nbox; size_t b0i, b0j; for (ib = 0; ib < nbox; ib++) { if (!empty[ib]) { b0i = ib * BOXSIZE; leni = MIN(nao-b0i, BOXSIZE); if (hermi) { j1 = ib + 1; } for (jb = 0; jb < j1; jb++) { if (!empty[jb]) { b0j = jb * BOXSIZE; lenj = MIN(nao-b0j, BOXSIZE); zgemm_(&TRANS_C, &TRANS_N, &lenj, &leni, &bgrids, &Z1, ao2+b0j*ngrids, &ngrids, ao1+b0i*ngrids, &ngrids, &Z1, vv+b0i*nao+b0j, &nao); } } } } } else { zgemm_(&TRANS_C, &TRANS_N, &nao, &nao, &bgrids, &Z1, ao2, &ngrids, ao1, &ngrids, &Z1, vv, &nao); } } /* vv[nao,nao] = conj(ao1[i,nao]) * ao2[i,nao] */ void VXCzdot_ao_ao(double complex *vv, double complex *ao1, double complex *ao2, int nao, int ngrids, int nbas, int hermi, uint8_t *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; size_t Nao = nao; NPzset0(vv, Nao * Nao); #pragma omp parallel { int ip, ib; double complex *v_priv = calloc(nao*nao+2, sizeof(double complex)); #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_ao(v_priv, ao1+ip, ao2+ip, nao, ngrids, MIN(ngrids-ip, BLKSIZE), hermi, non0table+ib*nbas, shls_slice, ao_loc); } #pragma omp critical { for (ip = 0; ip < nao*nao; ip++) { vv[ip] += conj(v_priv[ip]); } } free(v_priv); } if (hermi != 0) { NPzhermi_triu(nao, vv, hermi); } } void VXC_zscale_ao(double complex *aow, double complex *ao, double *wv, int comp, int nao, int ngrids) { #pragma omp parallel { size_t Ngrids = ngrids; size_t ao_size = nao * Ngrids; int i, j, ic; double complex *pao = ao; #pragma omp for schedule(static) for (i = 0; i < nao; i++) { pao = ao + i * Ngrids; for (j = 0; j < Ngrids; j++) { aow[i*Ngrids+j] = pao[j] * wv[j]; } for (ic = 1; ic < comp; ic++) { for (j = 0; j < Ngrids; j++) { aow[i*Ngrids+j] += pao[ic*ao_size+j] * wv[ic*Ngrids+j]; } } } } } // 'ip,ip->p' void VXC_zcontract_rho(double *rho, double complex *bra, double complex *ket, int nao, int ngrids) { #pragma omp parallel { size_t Ngrids = ngrids; int nthread = omp_get_num_threads(); int blksize = MAX((Ngrids+nthread-1) / nthread, 1); int ib, b0, b1, i, j; #pragma omp for for (ib = 0; ib < nthread; ib++) { b0 = ib * blksize; b1 = MIN(b0 + blksize, ngrids); for (j = b0; j < b1; j++) { rho[j] = creal(bra[j]) * creal(ket[j]) + cimag(bra[j]) * cimag(ket[j]); } for (i = 1; i < nao; i++) { for (j = b0; j < b1; j++) { rho[j] += creal(bra[i*Ngrids+j]) * creal(ket[i*Ngrids+j]) + cimag(bra[i*Ngrids+j]) * cimag(ket[i*Ngrids+j]); } } } } }
lock.c
// RUN: %libomp-compile-and-run | FileCheck %s // REQUIRES: ompt #include "callback.h" #include <omp.h> int main() { //need to use an OpenMP construct so that OMPT will be initialized #pragma omp parallel num_threads(1) print_ids(0); omp_lock_t lock; printf("%" PRIu64 ": &lock: %" PRIu64 "\n", ompt_get_thread_data()->value, (ompt_wait_id_t)(uintptr_t) &lock); omp_init_lock(&lock); print_fuzzy_address(1); omp_set_lock(&lock); print_fuzzy_address(2); omp_unset_lock(&lock); print_fuzzy_address(3); omp_destroy_lock(&lock); print_fuzzy_address(4); // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_acquire' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_acquired' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_released' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_nest_lock' // CHECK: 0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: &lock: [[WAIT_ID:[0-9]+]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_init_lock: wait_id=[[WAIT_ID]], hint={{[0-9]+}}, impl={{[0-9]+}}, codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_lock: wait_id=[[WAIT_ID]], hint={{[0-9]+}}, impl={{[0-9]+}}, codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_acquired_lock: wait_id=[[WAIT_ID]], codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_release_lock: wait_id=[[WAIT_ID]], codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_destroy_lock: wait_id=[[WAIT_ID]], codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] return 0; }
GB_unop__identity_fp32_uint16.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_fp32_uint16 // op(A') function: GB_unop_tran__identity_fp32_uint16 // C type: float // A type: uint16_t // cast: float cij = (float) aij // unaryop: cij = aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_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) \ float z = (float) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = (float) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_fp32_uint16 ( float *Cx, // Cx and Ax may be aliased const uint16_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++) { uint16_t aij = Ax [p] ; float z = (float) 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_fp32_uint16 ( 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
main.c
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #define N 1000 #define Eps 1e-7 #pragma omp declare target void func_1v(float*, float*, unsigned); void func_2v(float*, float*, unsigned); void func_3v(float*, float*, unsigned); #pragma omp end declare target int main(){ float a[N], t1[N], t2[N], s = 0; unsigned i; unsigned nErr = 0; srand((unsigned int)time(NULL)); #pragma omp parallel for for(i=0; i<N; ++i){ a[i]=rand()%100; } func_1v(a,t1,N); func_3v(a,t2,N); #pragma omp parallel for reduction(+:s) for(i=0; i<N; ++i) s += t1[i]; if(s < Eps){ printf("Check 0: All elemets are zeros!\n"); return -1; } for(i=0; i<N; ++i){ if(fabs(t1[i]-t2[i]) >= Eps){ ++nErr; printf("Check 1: error at %d: %e >= %e\n",i,fabs(t1[i]-t2[i]),Eps); } } func_2v(t1,t2,N); for(i=0; i<N; ++i){ if(fabs(a[i]-t2[i]) >= Eps){ ++nErr; printf("Check 2: error at %d: %e >= %e\n",i,fabs(a[i]-t2[i]),Eps); } } if(!nErr) printf("Success\n"); return nErr; }
MyMiscellany.h
/* Copyright (c) 2017, Michael Kazhdan All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Johns Hopkins University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef MY_MISCELLANY_INCLUDED #define MY_MISCELLANY_INCLUDED #include "PreProcessor.h" ////////////////// // OpenMP Stuff // ////////////////// #ifdef _OPENMP #include <omp.h> #endif // _OPENMP //////////////// // Time Stuff // //////////////// #include <string.h> #include <sys/timeb.h> #ifndef WIN32 #include <sys/time.h> #endif // WIN32 inline double Time( void ) { #ifdef WIN32 struct _timeb t; _ftime( &t ); return double( t.time ) + double( t.millitm ) / 1000.0; #else // WIN32 struct timeval t; gettimeofday( &t , NULL ); return t.tv_sec + double( t.tv_usec ) / 1000000; #endif // WIN32 } #include <cstdio> #include <ctime> #include <chrono> struct Timer { Timer( void ){ _startCPUClock = std::clock() , _startWallClock = std::chrono::system_clock::now(); } double cpuTime( void ) const{ return (std::clock() - _startCPUClock) / (double)CLOCKS_PER_SEC; }; double wallTime( void ) const{ std::chrono::duration<double> diff = (std::chrono::system_clock::now() - _startWallClock) ; return diff.count(); } protected: std::clock_t _startCPUClock; std::chrono::time_point< std::chrono::system_clock > _startWallClock; }; /////////////// // I/O Stuff // /////////////// #if defined( _WIN32 ) || defined( _WIN64 ) const char FileSeparator = '\\'; #else // !_WIN const char FileSeparator = '/'; #endif // _WIN #ifndef SetTempDirectory #if defined( _WIN32 ) || defined( _WIN64 ) #define SetTempDirectory( tempDir , sz ) GetTempPath( (sz) , (tempDir) ) #else // !_WIN32 && !_WIN64 #define SetTempDirectory( tempDir , sz ) if( std::getenv( "TMPDIR" ) ) strcpy( tempDir , std::getenv( "TMPDIR" ) ); #endif // _WIN32 || _WIN64 #endif // !SetTempDirectory #include <stdarg.h> #include <vector> #include <string> struct MessageWriter { char* outputFile; bool echoSTDOUT; MessageWriter( void ){ outputFile = NULL , echoSTDOUT = true; } void operator() ( const char* format , ... ) { if( outputFile ) { FILE* fp = fopen( outputFile , "a" ); va_list args; va_start( args , format ); vfprintf( fp , format , args ); fclose( fp ); va_end( args ); } if( echoSTDOUT ) { va_list args; va_start( args , format ); vprintf( format , args ); va_end( args ); } } void operator() ( std::vector< char* >& messages , const char* format , ... ) { if( outputFile ) { FILE* fp = fopen( outputFile , "a" ); va_list args; va_start( args , format ); vfprintf( fp , format , args ); fclose( fp ); va_end( args ); } if( echoSTDOUT ) { va_list args; va_start( args , format ); vprintf( format , args ); va_end( args ); } // [WARNING] We are not checking the string is small enough to fit in 1024 characters messages.push_back( new char[1024] ); char* str = messages.back(); va_list args; va_start( args , format ); vsprintf( str , format , args ); va_end( args ); if( str[strlen(str)-1]=='\n' ) str[strlen(str)-1] = 0; } void operator() ( std::vector< std::string >& messages , const char* format , ... ) { if( outputFile ) { FILE* fp = fopen( outputFile , "a" ); va_list args; va_start( args , format ); vfprintf( fp , format , args ); fclose( fp ); va_end( args ); } if( echoSTDOUT ) { va_list args; va_start( args , format ); vprintf( format , args ); va_end( args ); } // [WARNING] We are not checking the string is small enough to fit in 1024 characters char message[1024]; va_list args; va_start( args , format ); vsprintf( message , format , args ); va_end( args ); if( message[strlen(message)-1]=='\n' ) message[strlen(message)-1] = 0; messages.push_back( std::string( message ) ); } }; ///////////////////////////////////// // Exception, Warnings, and Errors // ///////////////////////////////////// #include <exception> #include <string> #include <iostream> #include <sstream> #include <algorithm> namespace MKExceptions { template< typename ... Arguments > void _AddToMessageStream( std::stringstream &stream , Arguments ... arguments ); inline void _AddToMessageStream( std::stringstream &stream ){ return; } template< typename Argument , typename ... Arguments > void _AddToMessageStream( std::stringstream &stream , Argument argument , Arguments ... arguments ) { stream << argument; _AddToMessageStream( stream , arguments ... ); } template< typename ... Arguments > std::string MakeMessageString( std::string header , std::string fileName , int line , std::string functionName , Arguments ... arguments ) { size_t headerSize = header.size(); std::stringstream stream; // The first line is the header, the file name , and the line number stream << header << " " << fileName << " (Line " << line << ")" << std::endl; // Inset the second line by the size of the header and write the function name for( size_t i=0 ; i<=headerSize ; i++ ) stream << " "; stream << functionName << std::endl; // Inset the third line by the size of the header and write the rest for( size_t i=0 ; i<=headerSize ; i++ ) stream << " "; _AddToMessageStream( stream , arguments ... ); return stream.str(); } struct Exception : public std::exception { const char *what( void ) const noexcept { return _message.c_str(); } template< typename ... Args > Exception( const char *fileName , int line , const char *functionName , const char *format , Args ... args ) { _message = MakeMessageString( "[EXCEPTION]" , fileName , line , functionName , format , args ... ); } private: std::string _message; }; template< typename ... Args > void Throw( const char *fileName , int line , const char *functionName , const char *format , Args ... args ){ throw Exception( fileName , line , functionName , format , args ... ); } template< typename ... Args > void Warn( const char *fileName , int line , const char *functionName , const char *format , Args ... args ) { std::cerr << MakeMessageString( "[WARNING]" , fileName , line , functionName , format , args ... ) << std::endl; } template< typename ... Args > void ErrorOut( const char *fileName , int line , const char *functionName , const char *format , Args ... args ) { std::cerr << MakeMessageString( "[ERROR]" , fileName , line , functionName , format , args ... ) << std::endl; exit( 0 ); } } #ifndef WARN #define WARN( ... ) MKExceptions::Warn( __FILE__ , __LINE__ , __FUNCTION__ , __VA_ARGS__ ) #endif // WARN #ifndef WARN_ONCE #define WARN_ONCE( ... ) { static bool firstTime = true ; if( firstTime ) MKExceptions::Warn( __FILE__ , __LINE__ , __FUNCTION__ , __VA_ARGS__ ) ; firstTime = false; } #endif // WARN_ONCE #ifndef THROW #define THROW( ... ) MKExceptions::Throw( __FILE__ , __LINE__ , __FUNCTION__ , __VA_ARGS__ ) #endif // THROW #ifndef ERROR_OUT #define ERROR_OUT( ... ) MKExceptions::ErrorOut( __FILE__ , __LINE__ , __FUNCTION__ , __VA_ARGS__ ) #endif // ERROR_OUT #include <signal.h> #if defined(_WIN32) || defined( _WIN64 ) #else // !WINDOWS #include <execinfo.h> #include <unistd.h> #include <cxxabi.h> #include <mutex> #endif // WINDOWS struct StackTracer { static const char *exec; #if defined(_WIN32) || defined( _WIN64 ) static void Trace( void ) { } #else // !WINDOWS static void Trace( void ) { static std::mutex mutex; std::lock_guard< std::mutex > lock(mutex); // Code borrowed from: // https://stackoverflow.com/questions/77005/how-to-automatically-generate-a-stacktrace-when-my-program-crashes // and // https://stackoverflow.com/questions/15129089/is-there-a-way-to-dump-stack-trace-with-line-number-from-a-linux-release-binary/15130037 void * trace[128]; int size = backtrace( trace , 128 ); char ** messages = backtrace_symbols( trace , size ); for( int i=1 ; i< size && messages!=NULL ; ++i ) { char *mangled_name=0 , *offset_begin=0 , *offset_end=0; char syscom[1024]; sprintf( syscom , "addr2line %p -e %s" , trace[i] , exec ); //last parameter is the name of this app if( !system( syscom ) ){} // find parantheses and +address offset surrounding mangled name for( char *p=messages[i] ; *p ; ++p ) { if ( *p=='(' ) mangled_name = p; else if( *p=='+' ) offset_begin = p; else if( *p==')' ) { offset_end = p; break; } } // if the line could be processed, attempt to demangle the symbol if( mangled_name && offset_begin && offset_end && mangled_name<offset_begin ) { *mangled_name++ = '\0'; *offset_begin++ = '\0'; *offset_end++ = '\0'; int status; char * real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status); // if demangling is successful, output the demangled function name if( !status ) { std::cerr << "\t(" << i << ") " << messages[i] << " : " << real_name << "+" << offset_begin << offset_end << std::endl; std::cout << "\t(" << i << ") " << messages[i] << " : " << real_name << "+" << offset_begin << offset_end << std::endl; } // otherwise, output the mangled function name else { std::cerr << "\t(" << i << ") " << messages[i] << " : " << mangled_name << "+" << offset_begin << offset_end << std::endl; std::cout << "\t(" << i << ") " << messages[i] << " : " << mangled_name << "+" << offset_begin << offset_end << std::endl; } free( real_name ); } // otherwise, print the whole line else { std::cerr << "\t(" << i << ") " << messages[i] << std::endl; std::cout << "\t(" << i << ") " << messages[i] << std::endl; } } free( messages ); } #endif // WINDOWS }; const char *StackTracer::exec; inline void SignalHandler( int signal ) { printf( "Signal: %d\n" , signal ); StackTracer::Trace(); exit( 0 ); }; template< typename Value > bool SetAtomic( volatile Value *value , Value newValue , Value oldValue ); template< typename Data > void AddAtomic( Data& a , Data b ); //////////////////// // MKThread Stuff // //////////////////// #include <thread> #include <mutex> #include <vector> #include <atomic> #include <condition_variable> #include <functional> #include <chrono> #include <future> #include <memory> struct ThreadPool { enum ParallelType { #ifdef _OPENMP OPEN_MP , #endif // _OPENMP THREAD_POOL , ASYNC , NONE }; static const std::vector< std::string > ParallelNames; enum ScheduleType { STATIC , DYNAMIC }; static const std::vector< std::string > ScheduleNames; static size_t DefaultChunkSize; static ScheduleType DefaultSchedule; template< typename ... Functions > static void ParallelSections( const Functions & ... functions ) { std::vector< std::future< void > > futures( sizeof...(Functions) ); _ParallelSections( &futures[0] , functions ... ); for( size_t t=0 ; t<futures.size() ; t++ ) futures[t].get(); } static void Parallel_for( size_t begin , size_t end , const std::function< void ( unsigned int , size_t ) > &iterationFunction , ScheduleType schedule=DefaultSchedule , size_t chunkSize=DefaultChunkSize ) { if( begin>=end ) return; size_t range = end - begin; size_t chunks = ( range + chunkSize - 1 ) / chunkSize; unsigned int threads = (unsigned int)NumThreads(); std::atomic< size_t > index; index.store( 0 ); if( range<chunkSize || _ParallelType==NONE || threads==1 ) { for( size_t i=begin ; i<end ; i++ ) iterationFunction( 0 , i ); return; } auto _ChunkFunction = [ &iterationFunction , begin , end , chunkSize ]( unsigned int thread , size_t chunk ) { const size_t _begin = begin + chunkSize*chunk; const size_t _end = std::min< size_t >( end , _begin+chunkSize ); for( size_t i=_begin ; i<_end ; i++ ) iterationFunction( thread , i ); }; auto _StaticThreadFunction = [ &_ChunkFunction , chunks , threads ]( unsigned int thread ) { for( size_t chunk=thread ; chunk<chunks ; chunk+=threads ) _ChunkFunction( thread , chunk ); }; auto _DynamicThreadFunction = [ &_ChunkFunction , chunks , &index ]( unsigned int thread ) { size_t chunk; while( ( chunk=index.fetch_add(1) )<chunks ) _ChunkFunction( thread , chunk ); }; if ( schedule==STATIC ) _ThreadFunction = _StaticThreadFunction; else if( schedule==DYNAMIC ) _ThreadFunction = _DynamicThreadFunction; if( false ){} #ifdef _OPENMP else if( _ParallelType==OPEN_MP ) { if( schedule==STATIC ) #pragma omp parallel for num_threads( threads ) schedule( static , 1 ) for( int c=0 ; c<chunks ; c++ ) _ChunkFunction( omp_get_thread_num() , c ); else if( schedule==DYNAMIC ) #pragma omp parallel for num_threads( threads ) schedule( dynamic , 1 ) for( int c=0 ; c<chunks ; c++ ) _ChunkFunction( omp_get_thread_num() , c ); } #endif // _OPENMP else if( _ParallelType==ASYNC ) { static std::vector< std::future< void > > futures; futures.resize( threads-1 ); for( unsigned int t=1 ; t<threads ; t++ ) futures[t-1] = std::async( std::launch::async , _ThreadFunction , t ); _ThreadFunction( 0 ); for( unsigned int t=1 ; t<threads ; t++ ) futures[t-1].get(); } else if( _ParallelType==THREAD_POOL ) { unsigned int targetTasks = 0; if( !SetAtomic( &_RemainingTasks , threads-1 , targetTasks ) ) { WARN( "nested for loop, reverting to serial" ); for( size_t i=begin ; i<end ; i++ ) iterationFunction( 0 , i ); } else { _WaitingForWorkOrClose.notify_all(); { std::unique_lock< std::mutex > lock( _Mutex ); _DoneWithWork.wait( lock , [&]( void ){ return _RemainingTasks==0; } ); } } } } static unsigned int NumThreads( void ){ return (unsigned int)_Threads.size()+1; } static void Init( ParallelType parallelType , unsigned int numThreads=std::thread::hardware_concurrency() ) { _ParallelType = parallelType; if( _Threads.size() && !_Close ) { _Close = true; _WaitingForWorkOrClose.notify_all(); for( unsigned int t=0 ; t<_Threads.size() ; t++ ) _Threads[t].join(); } _Close = true; numThreads--; _Threads.resize( numThreads ); if( _ParallelType==THREAD_POOL ) { _RemainingTasks = 0; _Close = false; for( unsigned int t=0 ; t<numThreads ; t++ ) _Threads[t] = std::thread( _ThreadInitFunction , t ); } } static void Terminate( void ) { if( _Threads.size() && !_Close ) { _Close = true; _WaitingForWorkOrClose.notify_all(); for( unsigned int t=0 ; t<_Threads.size() ; t++ ) _Threads[t].join(); _Threads.resize( 0 ); } } private: ThreadPool( const ThreadPool & ){} ThreadPool &operator = ( const ThreadPool & ){ return *this; } template< typename Function > static void _ParallelSections( std::future< void > *futures , const Function &function ){ *futures = std::async( std::launch::async , function ); } template< typename Function , typename ... Functions > static void _ParallelSections( std::future< void > *futures , const Function &function , const Functions& ... functions ) { *futures = std::async( std::launch::async , function ); _ParallelSections( futures+1 , functions ... ); } static void _ThreadInitFunction( unsigned int thread ) { // Wait for the first job to come in std::unique_lock< std::mutex > lock( _Mutex ); _WaitingForWorkOrClose.wait( lock ); while( !_Close ) { lock.unlock(); // do the job _ThreadFunction( thread ); // Notify and wait for the next job lock.lock(); _RemainingTasks--; if( !_RemainingTasks ) _DoneWithWork.notify_all(); _WaitingForWorkOrClose.wait( lock ); } } static bool _Close; static volatile unsigned int _RemainingTasks; static std::mutex _Mutex; static std::condition_variable _WaitingForWorkOrClose , _DoneWithWork; static std::vector< std::thread > _Threads; static std::function< void ( unsigned int ) > _ThreadFunction; static ParallelType _ParallelType; }; size_t ThreadPool::DefaultChunkSize = 128; ThreadPool::ScheduleType ThreadPool::DefaultSchedule = ThreadPool::DYNAMIC; bool ThreadPool::_Close; volatile unsigned int ThreadPool::_RemainingTasks; std::mutex ThreadPool::_Mutex; std::condition_variable ThreadPool::_WaitingForWorkOrClose; std::condition_variable ThreadPool::_DoneWithWork; std::vector< std::thread > ThreadPool::_Threads; std::function< void ( unsigned int ) > ThreadPool::_ThreadFunction; ThreadPool::ParallelType ThreadPool::_ParallelType; const std::vector< std::string >ThreadPool::ParallelNames = { #ifdef _OPENMP "open mp" , #endif // _OPENMP "thread pool" , "async" , "none" }; const std::vector< std::string >ThreadPool::ScheduleNames = { "static" , "dynamic" }; #include <mutex> #if defined( _WIN32 ) || defined( _WIN64 ) #include <windows.h> #endif // _WIN32 || _WIN64 template< typename Value > bool SetAtomic32( volatile Value *value , Value newValue , Value oldValue ) { #if defined( _WIN32 ) || defined( _WIN64 ) long &_oldValue = *(long *)&oldValue; long &_newValue = *(long *)&newValue; return InterlockedCompareExchange( (long*)value , _newValue , _oldValue )==_oldValue; #else // !_WIN32 && !_WIN64 uint32_t &_oldValue = *(uint32_t *)&oldValue; uint32_t &_newValue = *(uint32_t *)&newValue; // return __sync_bool_compare_and_swap( (uint32_t *)value , _oldValue , _newValue ); return __atomic_compare_exchange_n( (uint32_t *)value , (uint32_t *)&oldValue , _newValue , false , __ATOMIC_SEQ_CST , __ATOMIC_SEQ_CST ); #endif // _WIN32 || _WIN64 } template< typename Value > bool SetAtomic64( volatile Value *value , Value newValue , Value oldValue ) { #if defined( _WIN32 ) || defined( _WIN64 ) __int64 &_oldValue = *(__int64 *)&oldValue; __int64 &_newValue = *(__int64 *)&newValue; return InterlockedCompareExchange64( (__int64*)value , _newValue , _oldValue )==_oldValue; #else // !_WIN32 && !_WIN64 uint64_t &_oldValue = *(uint64_t *)&oldValue; uint64_t &_newValue = *(uint64_t *)&newValue; // return __sync_bool_compare_and_swap ( (uint64_t *)&value , _oldValue , _newValue ); return __atomic_compare_exchange_n( (uint64_t *)value , (uint64_t *)&oldValue , _newValue , false , __ATOMIC_SEQ_CST , __ATOMIC_SEQ_CST ); #endif // _WIN32 || _WIN64 } template< typename Number > void AddAtomic32( Number &a , Number b ) { #if 0 Number current = a; Number sum = current+b; while( !SetAtomic32( &a , sum , current ) ) current = a , sum = a+b; #else #if defined( _WIN32 ) || defined( _WIN64 ) Number current = a; Number sum = current+b; long &_current = *(long *)&current; long &_sum = *(long *)&sum; while( InterlockedCompareExchange( (long*)&a , _sum , _current )!=_current ) current = a , sum = a+b; #else // !_WIN32 && !_WIN64 Number current = a; Number sum = current+b; uint32_t &_current = *(uint32_t *)&current; uint32_t &_sum = *(uint32_t *)&sum; while( __sync_val_compare_and_swap( (uint32_t *)&a , _current , _sum )!=_current ) current = a , sum = a+b; #endif // _WIN32 || _WIN64 #endif } template< typename Number > void AddAtomic64( Number &a , Number b ) { #if 1 Number current = a; Number sum = current+b; while( !SetAtomic64( &a , sum , current ) ) current = a , sum = a+b; #else #if defined( _WIN32 ) || defined( _WIN64 ) Number current = a; Number sum = current+b; __int64 &_current = *(__int64 *)&current; __int64 &_sum = *(__int64 *)&sum; while( InterlockedCompareExchange64( (__int64*)&a , _sum , _current )!=_current ) current = a , sum = a+b; #else // !_WIN32 && !_WIN64 Number current = a; Number sum = current+b; uint64_t &_current = *(uint64_t *)&current; uint64_t &_sum = *(uint64_t *)&sum; while( __sync_val_compare_and_swap( (uint64_t *)&a , _current , _sum )!=_current ) current = a , sum = a+b; #endif // _WIN32 || _WIN64 #endif } template< typename Value > bool SetAtomic( volatile Value *value , Value newValue , Value oldValue ) { switch( sizeof(Value) ) { case 4: return SetAtomic32( value , newValue , oldValue ); case 8: return SetAtomic64( value , newValue , oldValue ); default: WARN_ONCE( "should not use this function: " , sizeof(Value) ); static std::mutex setAtomicMutex; std::lock_guard< std::mutex > lock( setAtomicMutex ); if( *value==oldValue ){ *value = newValue ; return true; } else return false; } } template< typename Data > void AddAtomic( Data& a , Data b ) { switch( sizeof(Data) ) { case 4: return AddAtomic32( a , b ); case 8: return AddAtomic64( a , b ); default: WARN_ONCE( "should not use this function: " , sizeof(Data) ); static std::mutex addAtomicMutex; std::lock_guard< std::mutex > lock( addAtomicMutex ); a += b; } } ///////////////////////// // NumberWrapper Stuff // ///////////////////////// #include <vector> struct EmptyNumberWrapperClass{}; template< typename Number , typename Type=EmptyNumberWrapperClass , size_t I=0 > struct NumberWrapper { typedef Number type; Number n; NumberWrapper( Number _n=0 ) : n(_n){} NumberWrapper operator + ( NumberWrapper _n ) const { return NumberWrapper( n + _n.n ); } NumberWrapper operator - ( NumberWrapper _n ) const { return NumberWrapper( n - _n.n ); } NumberWrapper operator * ( NumberWrapper _n ) const { return NumberWrapper( n * _n.n ); } NumberWrapper operator / ( NumberWrapper _n ) const { return NumberWrapper( n / _n.n ); } NumberWrapper &operator += ( NumberWrapper _n ){ n += _n.n ; return *this; } NumberWrapper &operator -= ( NumberWrapper _n ){ n -= _n.n ; return *this; } NumberWrapper &operator *= ( NumberWrapper _n ){ n *= _n.n ; return *this; } NumberWrapper &operator /= ( NumberWrapper _n ){ n /= _n.n ; return *this; } bool operator == ( NumberWrapper _n ) const { return n==_n.n; } bool operator != ( NumberWrapper _n ) const { return n!=_n.n; } bool operator < ( NumberWrapper _n ) const { return n<_n.n; } bool operator > ( NumberWrapper _n ) const { return n>_n.n; } bool operator <= ( NumberWrapper _n ) const { return n<=_n.n; } bool operator >= ( NumberWrapper _n ) const { return n>=_n.n; } NumberWrapper operator ++ ( int ) { NumberWrapper _n(n) ; n++ ; return _n; } NumberWrapper operator -- ( int ) { NumberWrapper _n(n) ; n-- ; return _n; } NumberWrapper &operator ++ ( void ) { n++ ; return *this; } NumberWrapper &operator -- ( void ) { n-- ; return *this; } explicit operator Number () const { return n; } }; #if 0 template< typename Number , typename Type , size_t I > struct std::atomic< NumberWrapper< Number , Type , I > > { typedef Number type; std::atomic< Number > n; atomic( Number _n=0 ) : n(_n){} atomic( const std::atomic< Number > &_n ) : n(_n){} atomic( NumberWrapper< Number , Type , I > _n ) : n(_n.n){} atomic &operator = ( Number _n ){ n = _n ; return *this; } // atomic &operator = ( const atomic &a ){ n = a.n ; return *this; } // atomic &operator = ( const NumberWrapper< Number , Type , I > &_n ){ n = _n.n ; return *this; } atomic operator + ( atomic _n ) const { return atomic( n + _n.n ); } atomic operator - ( atomic _n ) const { return atomic( n * _n.n ); } atomic operator * ( atomic _n ) const { return atomic( n * _n.n ); } atomic operator / ( atomic _n ) const { return atomic( n / _n.n ); } atomic &operator += ( atomic _n ){ n += _n.n ; return *this; } atomic &operator -= ( atomic _n ){ n -= _n.n ; return *this; } atomic &operator *= ( atomic _n ){ n *= _n.n ; return *this; } atomic &operator /= ( atomic _n ){ n /= _n.n ; return *this; } bool operator == ( atomic _n ) const { return n==_n.n; } bool operator != ( atomic _n ) const { return n!=_n.n; } bool operator < ( atomic _n ) const { return n<_n.n; } bool operator > ( atomic _n ) const { return n>_n.n; } bool operator <= ( atomic _n ) const { return n<=_n.n; } bool operator >= ( atomic _n ) const { return n>=_n.n; } atomic operator ++ ( int ) { atomic _n(n) ; n++ ; return _n; } atomic operator -- ( int ) { atomic _n(n) ; n-- ; return _n; } atomic &operator ++ ( void ) { n++ ; return *this; } atomic &operator -- ( void ) { n-- ; return *this; } operator NumberWrapper< Number , Type , I >() const { return NumberWrapper< Number , Type , I >(n); } explicit operator Number () const { return n; } }; #endif namespace std { template< typename Number , typename Type , size_t I > struct hash< NumberWrapper< Number , Type , I > > { size_t operator()( NumberWrapper< Number , Type , I > n ) const { return std::hash< Number >{}( n.n ); } }; } template< typename Data , typename _NumberWrapper > struct VectorWrapper : public std::vector< Data > { VectorWrapper( void ){} VectorWrapper( size_t sz ) : std::vector< Data >( sz ){} VectorWrapper( size_t sz , Data d ) : std::vector< Data >( sz , d ){} // void resize( _NumberWrapper n ) { std::vector< Data >::resize( (size_t)(_NumberWrapper::type)n ); } // void resize( _NumberWrapper n , Data d ){ std::vector< Data >::resize( (size_t)(_NumberWrapper::type)n , d ); } typename std::vector< Data >::reference operator[]( _NumberWrapper n ){ return std::vector< Data >::operator[]( n.n ); } typename std::vector< Data >::const_reference operator[]( _NumberWrapper n ) const { return std::vector< Data >::operator[]( n.n ); } }; ////////////////// // Memory Stuff // ////////////////// size_t getPeakRSS( void ); size_t getCurrentRSS( void ); struct MemoryInfo { static size_t Usage( void ){ return getCurrentRSS(); } static int PeakMemoryUsageMB( void ){ return (int)( getPeakRSS()>>20 ); } }; #if defined( _WIN32 ) || defined( _WIN64 ) #include <Windows.h> #include <Psapi.h> inline void SetPeakMemoryMB( size_t sz ) { sz <<= 20; SIZE_T peakMemory = sz; HANDLE h = CreateJobObject( NULL , NULL ); AssignProcessToJobObject( h , GetCurrentProcess() ); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY; jeli.JobMemoryLimit = peakMemory; if( !SetInformationJobObject( h , JobObjectExtendedLimitInformation , &jeli , sizeof( jeli ) ) ) WARN( "Failed to set memory limit" ); } #else // !_WIN32 && !_WIN64 #include <sys/time.h> #include <sys/resource.h> inline void SetPeakMemoryMB( size_t sz ) { sz <<= 20; struct rlimit rl; getrlimit( RLIMIT_AS , &rl ); rl.rlim_cur = sz; setrlimit( RLIMIT_AS , &rl ); } #endif // _WIN32 || _WIN64 /* * Author: David Robert Nadeau * Site: http://NadeauSoftware.com/ * License: Creative Commons Attribution 3.0 Unported License * http://creativecommons.org/licenses/by/3.0/deed.en_US */ #if defined(_WIN32) || defined( _WIN64 ) #include <windows.h> #include <psapi.h> #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) #include <unistd.h> #include <sys/resource.h> #if defined(__APPLE__) && defined(__MACH__) #include <mach/mach.h> #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) #include <fcntl.h> #include <procfs.h> #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) #include <stdio.h> #endif #else #error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS." #endif /** * Returns the peak (maximum so far) resident set size (physical * memory use) measured in bytes, or zero if the value cannot be * determined on this OS. */ inline size_t getPeakRSS( ) { #if defined(_WIN32) /* Windows -------------------------------------------------- */ PROCESS_MEMORY_COUNTERS info; GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); return (size_t)info.PeakWorkingSetSize; #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) /* AIX and Solaris ------------------------------------------ */ struct psinfo psinfo; int fd = -1; if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 ) return (size_t)0L; /* Can't open? */ if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) ) { close( fd ); return (size_t)0L; /* Can't read? */ } close( fd ); return (size_t)(psinfo.pr_rssize * 1024L); #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) /* BSD, Linux, and OSX -------------------------------------- */ struct rusage rusage; getrusage( RUSAGE_SELF, &rusage ); #if defined(__APPLE__) && defined(__MACH__) return (size_t)rusage.ru_maxrss; #else return (size_t)(rusage.ru_maxrss * 1024L); #endif #else /* Unknown OS ----------------------------------------------- */ return (size_t)0L; /* Unsupported. */ #endif } /** * Returns the current resident set size (physical memory use) measured * in bytes, or zero if the value cannot be determined on this OS. */ inline size_t getCurrentRSS( ) { #if defined(_WIN32) || defined( _WIN64 ) /* Windows -------------------------------------------------- */ PROCESS_MEMORY_COUNTERS info; GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); return (size_t)info.WorkingSetSize; #elif defined(__APPLE__) && defined(__MACH__) /* OSX ------------------------------------------------------ */ struct mach_task_basic_info info; mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) return (size_t)0L; /* Can't access? */ return (size_t)info.resident_size; #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) /* Linux ---------------------------------------------------- */ long rss = 0L; FILE* fp = NULL; if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL ) return (size_t)0L; /* Can't open? */ if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) { fclose( fp ); return (size_t)0L; /* Can't read? */ } fclose( fp ); return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); #else /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ return (size_t)0L; /* Unsupported. */ #endif } #endif // MY_MISCELLANY_INCLUDED
deconvolution_pack4to8.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 deconvolution_pack4to8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_packed, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; const int maxk = kernel_w * kernel_h; const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { __m256 _sum = _mm256_setzero_ps(); if (bias_data_ptr) { _sum = _mm256_loadu_ps(bias_data_ptr + p * 8); } const float* kptr = weight_data_packed.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); for (int y = 0; y < kernel_h; y++) { int sys = (i + y * dilation_h - (kernel_extent_h - 1)); if (sys < 0 || sys % stride_h != 0) continue; int sy = sys / stride_h; if (sy >= h) continue; for (int x = 0; x < kernel_w; x++) { int sxs = (j + x * dilation_w - (kernel_extent_w - 1)); if (sxs < 0 || sxs % stride_w != 0) continue; int sx = sxs / stride_w; if (sx >= w) continue; const float* sptr = m.row(sy) + sx * 4; int k = (y * kernel_w + x) * 32; __m256 _val0 = _mm256_broadcast_ss(sptr); __m256 _val1 = _mm256_broadcast_ss(sptr + 1); __m256 _val2 = _mm256_broadcast_ss(sptr + 2); __m256 _val3 = _mm256_broadcast_ss(sptr + 3); __m256 _w0 = _mm256_load_ps(kptr + k); __m256 _w1 = _mm256_load_ps(kptr + k + 8); __m256 _w2 = _mm256_load_ps(kptr + k + 16); __m256 _w3 = _mm256_load_ps(kptr + k + 24); _sum = _mm256_comp_fmadd_ps(_val0, _w0, _sum); _sum = _mm256_comp_fmadd_ps(_val1, _w1, _sum); _sum = _mm256_comp_fmadd_ps(_val2, _w2, _sum); _sum = _mm256_comp_fmadd_ps(_val3, _w3, _sum); } } kptr += maxk * 32; } _sum = activation_avx(_sum, activation_type, activation_params); _mm256_storeu_ps(outptr, _sum); outptr += 8; } } } }
omp_detach_taskwait.c
// RUN: %libomp-compile -fopenmp-version=50 && env OMP_NUM_THREADS='3' %libomp-run // RUN: %libomp-compile -fopenmp-version=50 && env OMP_NUM_THREADS='1' %libomp-run // Checked gcc 10.1 still does not support detach clause on task construct. // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8, gcc-9, gcc-10 // clang supports detach clause since version 11. // UNSUPPORTED: clang-10, clang-9, clang-8, clang-7 // icc compiler does not support detach clause. // UNSUPPORTED: icc // REQUIRES: !abt #include <omp.h> int main() { #pragma omp parallel #pragma omp master { omp_event_handle_t event; #pragma omp task detach(event) { omp_fulfill_event(event); } #pragma omp taskwait } return 0; }
target_x86.h
/***************************************************************************** * * target_x86.h * * Edinburgh Soft Matter and Statistical Physics Group and * Edinburgh Parallel Computing Centre * * (c) 2018-2021 The University of Edinburgh * * Contributing authors: * Alan Gray (alang@epcc.ed.ac.uk) * Kevin Stratford (kevin@epcc.ed.ac.uk) * *****************************************************************************/ #ifndef LUDWIG_TARGET_X86_H #define LUDWIG_TARGET_X86_H typedef enum tdpFuncCache_enum { tdpFuncCachePreferNone = 0, tdpFuncCachePreferShared = 1, tdpFuncCachePreferL1 = 2, tdpFuncCachePreferEqual = 3} tdpFuncCache; typedef enum tdpMemcpyKind_enum { tdpMemcpyHostToHost = 0, tdpMemcpyHostToDevice = 1, tdpMemcpyDeviceToHost = 2, tdpMemcpyDeviceToDevice = 3, tdpMemcpyDefault = 4} tdpMemcpyKind; /* Device attributes (potentially a lot of them) */ typedef enum tdpDeviceAttr_enum { tdpDevAttrMaxThreadsPerBlock = 1, tdpDevAttrMaxBlockDimX = 2, tdpDevAttrMaxBlockDimY = 3, tdpDevAttrMaxBlockDimZ = 4, tdpDevAttrMaxGridDimX = 5, tdpDevAttrMaxGridDimY = 6, tdpDevAttrMaxGridDimZ = 7, tdpDevAttrManagedMemory = 83 } tdpDeviceAttr; /* tdpGetLastError() can return... */ enum tdpError { tdpSuccess = 0, tdpErrorMissingConfiguration = 1, tdpErrorMemoryAllocation = 2, tdpErrorInitializationError = 3, tdpErrorLaunchFailure = 4, tdpErrorLaunchTimeout = 6, tdpErrorLaunchOutOfResources = 7, tdpErrorInvalidDeviceFunction = 8, tdpErrorInvalidConfiguration = 9, tdpErrorInvalidDevice = 10, tdpErrorInvalidValue = 11, tdpErrorInvalidPitchValue = 12, tdpErrorInvalidSymbol = 13, tdpErrorUnmapBufferObjectFailed = 15, tdpErrorInvalidHostPointer = 16, tdpErrorInvalidDevicePointer = 17, tdpErrorInvalidTexture = 18, tdpErrorInvalidTextureBinding = 19, tdpErrorInvalidChannelDescriptor = 20, tdpErrorInvalidMemcpyDirection = 21, tdpErrorInvalidFilterSetting = 26, tdpErrorUnknown = 30, tdpErrorInvalidResourceHandle = 33, tdpErrorInsufficientDriver = 35, tdpErrorSetOnActiveProcess = 36, tdpErrorInvalidSurface = 37, tdpErrorNoDevice = 38, tdpErrorStartupFailure = 0x7f }; #define tdpHostAllocDefault 0x00 #define tdpHostAllocMapped 0x02 #define tdpHostAllocPortable 0x01 #define tdpHostAllocWriteCombined 0x04 #define tdpMemAttachGlobal 0x01 #define tdpMemAttachHost 0x02 #define tdpMemAttachSingle 0x04 /* Device memory qualifiers / executation space qualifiers */ #define __host__ #define __global__ #define __shared__ static #define __device__ #define __constant__ #if (__STDC__VERSION__ >= 19901) #define __forceinline__ #define __noinline__ #else #define __forceinline__ #define __noinline__ #endif /* Built-in variable implementation. */ typedef struct tdp_uint3_s uint3; typedef struct tdp_dim3_s dim3; struct tdp_uint3_s { unsigned int x; unsigned int y; unsigned int z; }; struct tdp_dim3_s { int x; int y; int z; }; extern dim3 gridDim; extern dim3 blockDim; extern dim3 threadIdx; extern dim3 blockIdx; /* Other vector types (as required) */ typedef struct tdp_double3_s double3; struct tdp_double3_s { double x; double y; double z; }; #ifdef _OPENMP /* These names are reserved and must be ... */ #pragma omp threadprivate(gridDim, blockDim, threadIdx, blockIdx) #endif typedef enum tdpError tdpError_t; /* an enum type */ typedef int * tdpStream_t; /* an opaque handle */ /* Incomplete. */ struct tdpDeviceProp { int maxThreadsPerBlock; int maxThreadsDim[3]; }; #define tdpSymbol(x) &(x) void tdp_x86_prelaunch(dim3 nblocks, dim3 nthreads); void tdp_x86_postlaunch(void); #ifdef _OPENMP /* Help to expand OpenMP clauses which need to be retained as strings */ #define xstr(a) str(a) #define str(a) #a /* Have OpenMP */ #include <omp.h> #define TARGET_MAX_THREADS_PER_BLOCK 256 #define TARGET_PAD 8 #define __syncthreads() _Pragma("omp barrier") #define __threadfence() /* only __syncthreads() is a barrier */ /* Kernel launch is a __VA_ARGS__ macro, thus: */ #define tdpLaunchKernel(kernel, nblocks, nthreads, shmem, stream, ...) \ _Pragma("omp parallel") \ { \ tdp_x86_prelaunch(nblocks, nthreads); \ kernel(__VA_ARGS__); \ tdp_x86_postlaunch(); \ } /* OpenMP work sharing */ #define for_simt_parallel(index, ndata, stride) \ _Pragma("omp for nowait") \ for (index = 0; index < (ndata); index += (stride)) /* SIMD safe loops */ #define for_simd_v(iv, nsimdvl) \ _Pragma("omp simd") \ for (iv = 0; iv < (nsimdvl); ++iv) #define for_simd_v_reduction(iv, nsimdvl, clause) \ _Pragma(xstr(omp simd reduction(clause))) \ for (iv = 0; iv < nsimdvl; ++iv) #else /* Not OPENMP */ #define TARGET_MAX_THREADS_PER_BLOCK 1 #define TARGET_PAD 1 #define omp_get_num_threads() 1 #define omp_get_thread_num() 0 #define omp_get_max_threads() 1 #define omp_set_num_threads(n) #define __syncthreads() #define __threadfence() /* NULL implementation */ /* Kernel launch is a __VA_ARGS__ macro, thus: */ #define tdpLaunchKernel(kernel, nblocks, nthreads, shmem, stream, ...) \ tdp_x86_prelaunch(nblocks, nthreads); \ kernel(__VA_ARGS__); \ tdp_x86_postlaunch(); /* "Worksharing" is provided by a loop */ #define for_simt_parallel(index, ndata, stride) \ for (index = 0; index < (ndata); index += (stride)) /* Vectorised loops */ #define for_simd_v(iv, nsimdvl) for (iv = 0; iv < (nsimdvl); iv++) #define for_simd_v_reduction(iv, nsimdvl, clause) \ for (iv = 0; iv < nsimdvl; iv++) #endif /* _OPENMP */ #define tdp_get_max_threads() omp_get_max_threads() /* For "critical section" it's handy to use atomicCAS() and atomicExch() * in place (togther with __threadfence()); until some better mechanism * is available */ #define atomicCAS(address, old, new) (old) #define atomicExch(address, val) #endif
convolution_pack8_fp16s.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 convolution_pack8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data_fp16, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const __fp16* bias_data_ptr = bias_data_fp16; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { float16x8_t _sum = vdupq_n_f16((__fp16)0.f); if (bias_data_ptr) { _sum = vld1q_f16(bias_data_ptr + p * 8); } const __fp16* kptr = weight_data_fp16.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const __fp16* sptr = m.row<const __fp16>(i * stride_h) + j * stride_w * 8; for (int k = 0; k < maxk; k++) { float16x8_t _val = vld1q_f16(sptr + space_ofs[k] * 8); float16x8_t _w0 = vld1q_f16(kptr); float16x8_t _w1 = vld1q_f16(kptr + 8); float16x8_t _w2 = vld1q_f16(kptr + 16); float16x8_t _w3 = vld1q_f16(kptr + 24); float16x8_t _w4 = vld1q_f16(kptr + 32); float16x8_t _w5 = vld1q_f16(kptr + 40); float16x8_t _w6 = vld1q_f16(kptr + 48); float16x8_t _w7 = vld1q_f16(kptr + 56); _sum = vfmaq_laneq_f16(_sum, _w0, _val, 0); _sum = vfmaq_laneq_f16(_sum, _w1, _val, 1); _sum = vfmaq_laneq_f16(_sum, _w2, _val, 2); _sum = vfmaq_laneq_f16(_sum, _w3, _val, 3); _sum = vfmaq_laneq_f16(_sum, _w4, _val, 4); _sum = vfmaq_laneq_f16(_sum, _w5, _val, 5); _sum = vfmaq_laneq_f16(_sum, _w6, _val, 6); _sum = vfmaq_laneq_f16(_sum, _w7, _val, 7); kptr += 64; } } _sum = activation_ps(_sum, activation_type, activation_params); vst1q_f16(outptr + j * 8, _sum); } outptr += outw * 8; } } }
cg_glm_get_Beta_ResSS.c
#ifndef lint static char sccsid[]="@(#)cg_glm_get_Beta_ResSS.c 1.01 Christian Gaser 07/09/09"; #endif #include <math.h> #include <memory.h> #include "mex.h" #include "spm_mapping.h" #ifdef _OPENMP #include "omp.h" #endif typedef struct{ int n_subj; int n_beta; int ini; int fin; double* Beta; double* ResSS; double* X; double* pKX; double* TH; double* W; MAPTYPE* maps; MAPTYPE* map_mask; } myargument; void ThreadFunc( myargument arg ) { int i, j, k, z, ind1, ind2, n_slices_x_values; int n_subj, n_values, n_slices, n_beta, ini, fin; double *estimates, *image, *mask; double *Beta, *ResSS, *X, *pKX, *W, *TH; MAPTYPE *maps, *map_mask; double sum, ival; double mat[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; n_subj = arg.n_subj; n_beta = arg.n_beta; Beta = arg.Beta; ResSS = arg.ResSS; maps = arg.maps; map_mask = arg.map_mask; n_values = maps[0].dim[0]*maps[0].dim[1]; n_slices = maps[0].dim[2]; X = arg.X; pKX = arg.pKX; TH = arg.TH; W = arg.W; ini = arg.ini; fin = arg.fin; #pragma omp critical (MALLOC) { estimates = (double *)malloc(n_values*n_subj*sizeof(double)); image = (double *)malloc(n_values*sizeof(double)); mask = (double *)malloc(n_values*sizeof(double)); } n_slices_x_values = n_slices*n_values; for(z=ini; z<fin; z++) { mat[14] = z + 1.0; ind2 = z*n_values; /* load mask */ slice(mat, mask, map_mask[0].dim[0],map_mask[0].dim[1], &map_mask[0], 0, 0.0); for(i=0; i<n_subj; i++) { slice(mat, image, maps[i].dim[0],maps[i].dim[1], &maps[i], 0, 0.0); for(j=0; j<n_values; j++) { ival = W[i]*image[j]; if ((mask[j] > 0) & (ival>TH[i])) { /* initialize estimates with image values */ estimates[j + (i*n_values)] = ival; /* calculate betas */ for(k=0; k<n_beta; k++) Beta[j + ind2 + (k*n_slices_x_values)] += pKX[k + (i*n_beta)] * ival; } } } /* get estimates */ for(i=0; i<n_subj; i++) { ind1 = i*n_values; for(j=0; j<n_values; j++) { ival = W[i]*image[j]; if ((mask[j] > 0) & (ival>TH[i])) { sum = 0.0; /* calculate difference between estimates and original values */ for(k=0; k<n_beta; k++) sum += (X[i + (k*n_subj)] * Beta[j + ind2 + (k*n_slices_x_values)]); estimates[j + ind1] -= sum; } } } /* calculate sum of residual squares */ for(j=0; j<n_values; j++) { if (mask[j] > 0) { sum = 0.0; for(i=0; i<n_subj; i++) { ind1 = j + (i*n_values); sum += estimates[ind1] * estimates[ind1]; } ResSS[j + ind2] = sum; } } } free((char *)estimates); free((char *)mask); free((char *)image); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int n_subj, n_beta, n_slices, n_values, ini, fin; int n, i, j, k, z, Nthreads; double *Beta, *ResSS, *X, *pKX, *TH, *W; MAPTYPE *maps, *map_mask, *get_maps(); myargument *ThreadArgs; if (nrhs != 6) mexErrMsgTxt("Six input arguments required."); if (nlhs != 2) mexErrMsgTxt("Two output arguments required."); n_subj = mxGetM(prhs[2]); n_beta = mxGetN(prhs[2]); map_mask = get_maps(prhs[1], &n); if (n!=1) { free_maps(map_mask, n); mexErrMsgTxt("Only one single file as mask allowed."); } maps = get_maps(prhs[0], &n); if (n!=n_subj) { free_maps(maps, n); free_maps(map_mask, 1); mexErrMsgTxt("Different number of scans in design matrix."); } for(i=1; i<n_subj; i++) { if ( maps[i].dim[0] != maps[0].dim[0] || maps[i].dim[1] != maps[0].dim[1] || maps[i].dim[2] != maps[0].dim[2]) { free_maps(maps, n_subj); mexErrMsgTxt("Incompatible image dimensions."); } } n_slices = maps[0].dim[2]; n_values = maps[0].dim[0]*maps[0].dim[1]; if ((n_slices!=map_mask[0].dim[2]) || (n_values!=map_mask[0].dim[0]*map_mask[0].dim[1])) { free_maps(maps, n); free_maps(map_mask, 1); mexErrMsgTxt("Incompatible dimensions between mask and images."); } X = (double*)mxGetPr(prhs[2]); pKX = (double*)mxGetPr(prhs[3]); TH = (double*)mxGetPr(prhs[4]); W = (double*)mxGetPr(prhs[5]); n_subj = mxGetM(prhs[2]); if (n_subj!=mxGetM(prhs[4])) { free_maps(maps, n); free_maps(map_mask, 1); mexErrMsgTxt("Incompatible dimensions of thresholds."); } for(i=0; i<n_subj; i++) if (mxIsInf(TH[i])) TH[i] = -1e15; plhs[0] = mxCreateDoubleMatrix(n_slices*n_values, n_beta, mxREAL); Beta = (double*)mxGetPr(plhs[0]); plhs[1] = mxCreateDoubleMatrix(n_slices*n_values, 1, mxREAL); ResSS = (double*)mxGetPr(plhs[1]); /* initialize Beta and ResSS with zeros */ memset(ResSS, 0, sizeof(double)*n_slices*n_values); memset(Beta, 0, sizeof(double)*n_slices*n_values*n_beta); Nthreads = 1; #ifdef _OPENMP Nthreads = omp_get_num_procs(); omp_set_num_threads(Nthreads); #endif /* Reserve room for handles of threads in ThreadList */ ThreadArgs = (myargument*) malloc( Nthreads*sizeof(myargument)); #ifdef _OPENMP # pragma omp parallel for default(shared) private(i,ini,fin) #endif for (i = 0; i<Nthreads; i++) { /* Make Thread Structure */ ini = (int)(i*n_slices)/Nthreads; fin = (int)((i+1)*n_slices)/Nthreads; ThreadArgs[i].n_subj = n_subj; ThreadArgs[i].n_beta = n_beta; ThreadArgs[i].Beta = Beta; ThreadArgs[i].ResSS = ResSS; ThreadArgs[i].maps = maps; ThreadArgs[i].map_mask = map_mask; ThreadArgs[i].X = X; ThreadArgs[i].pKX = pKX; ThreadArgs[i].TH = TH; ThreadArgs[i].W = W; ThreadArgs[i].ini = ini; ThreadArgs[i].fin = fin; (void)ThreadFunc(ThreadArgs[i]); } free(ThreadArgs); free_maps(maps, n_subj); free_maps(map_mask, 1); }
monte_carlo.h
#pragma once #include <iomanip> #if _OPENMP #include <omp.h> #endif #include <iostream> #include "3d/geometry/event_generator.h" #include "3d/geometry/event.h" #include "3d/geometry/point.h" namespace PET3D { namespace Hybrid { /// Drives Monte-Carlo system matrix construction template <class ScannerClass, class MatrixClass> class MonteCarlo { using Scanner = ScannerClass; using Event = typename Scanner::Event; using Matrix = MatrixClass; using F = typename Scanner::F; using S = typename Scanner::S; using SS = typename std::make_signed<S>::type; using LOR = typename Matrix::LOR; using Point = PET3D::Point<F>; static_assert(std::is_same<typename Matrix::S, S>::value, "matrix SType must be the same as detector SType"); public: MonteCarlo(const Scanner& scanner, Matrix& matrix, F pixel_size, S start_pixel = static_cast<S>(0)) : scanner(scanner), matrix(matrix), pixel_size(pixel_size), start_pixel(start_pixel) {} /// Executes Monte-Carlo system matrix generation for given detector ring template <class RNG, class AcceptanceModel, class ProgressCallback> void operator()( F z, ///< z position for calculations RNG& rng, ///< random number generator AcceptanceModel model, ///< acceptance model int n_emissions, ///< number of emissions generated ProgressCallback& progress, ///< progress callback bool o_collect_mc_matrix = true, ///< enable matrix generation bool o_collect_pixel_stats = true ///< enable pixel stats ) { if (n_emissions <= 0) return; const auto pixel_fov_radius = scanner.barrel.fov_radius() / pixel_size; const int pixel_fov_radius2 = pixel_fov_radius * pixel_fov_radius; util::random::uniform_real_distribution<F> one_dis(0, 1); util::random::uniform_real_distribution<F> phi_dis(0, F(M_PI)); Distribution::SphericalDistribution<F> direction; matrix.add_emissions(n_emissions); #if _OPENMP && !_MSC_VER // We need to try catch inside OpenMP thread, otherwise we will not see the // error thrown. #define TRY try { #define CATCH \ } \ catch (std::string & ex) { \ std::cerr << ex << std::endl; \ throw(ex); \ } #else #define TRY #define CATCH #endif #if _OPENMP // OpenMP uses passed random generator as seed source for // thread local random generators RNG* mp_rngs = new (alloca(sizeof(RNG) * omp_get_max_threads())) RNG[omp_get_max_threads()]; for (auto t = 0; t < omp_get_max_threads(); ++t) { mp_rngs[t].seed(rng()); } #pragma omp parallel for schedule(dynamic) #endif // iterating only triangular matrix, // being upper right part or whole system matrix // NOTE: we must iterate pixel indices instead of x, y since we need proper // thread distribution when issuing on MIC for (int i_pixel = 0; i_pixel < matrix.total_n_pixels_in_triangle; ++i_pixel) { progress(i_pixel); TRY; auto pixel = matrix.pixel_at_index(i_pixel); if (pixel.x < start_pixel || pixel.y < start_pixel || pixel.distance_from_origin2() > pixel_fov_radius2) continue; int pixel_hit_count = 0; for (auto n = 0; n < n_emissions; ++n) { #if _OPENMP auto& l_rng = mp_rngs[omp_get_thread_num()]; #else auto& l_rng = rng; #endif auto rx = (pixel.x + one_dis(l_rng)) * pixel_size; auto ry = (pixel.y + one_dis(l_rng)) * pixel_size; // ensure we are within a triangle, so we got only half hits on diagonal if (rx > ry) continue; auto rz = z + one_dis(l_rng) * pixel_size; typename ScannerClass::Response response; Event event(PET3D::Point<float>(rx, ry, rz), direction(l_rng)); auto hits = scanner.detect(l_rng, model, event, response); // do we have hit on both sides? if (hits >= 2) { if (o_collect_mc_matrix) { if (response.lor.first == response.lor.second) { std::ostringstream msg; msg << __FUNCTION__ << " invalid LOR in Monte-Carlo (" << response.lor.first << ", " << response.lor.second << ")"; throw(msg.str()); } matrix.hit_lor(response.lor, 0, i_pixel, 1); } if (o_collect_pixel_stats) { matrix.hit(i_pixel); } pixel_hit_count++; } // if (hits>=2) } // loop over emmisions from pixel matrix.compact_pixel_index(i_pixel); CATCH; } } private: const Scanner& scanner; Matrix& matrix; F pixel_size; F tof_step; S start_pixel; }; } // Hybrid } // PET3D
GB_unop__one_uint32_uint32.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__one_uint32_uint32 // op(A') function: GB_unop_tran__one_uint32_uint32 // C type: uint32_t // A type: uint32_t // cast: ; // unaryop: cij = 1 #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1 ; // casting #define GB_CAST(z, aij) \ ; ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ ; ; \ /* Cx [pC] = op (cast (aij)) */ \ ; ; \ Cx [pC] = 1 ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ONE || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__one_uint32_uint32 ( uint32_t *Cx, // Cx and Ax may be aliased const uint32_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++) { ; ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__one_uint32_uint32 ( 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
GB_binop__pair_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__pair_int16) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__pair_int16) // C+=b function (dense accum): GB (_Cdense_accumb__pair_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pair_int16) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: int16_t // A type: int16_t // A pattern? 1 // B type: int16_t // B pattern? 1 // BinaryOp: cij = 1 #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) \ ; // true if values of A are not used #define GB_A_IS_PATTERN \ 1 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ ; // true if values of B are not used #define GB_B_IS_PATTERN \ 1 \ // 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 = 1 ; // 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_PAIR || GxB_NO_INT16 || GxB_NO_PAIR_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__pair_int16) ( 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__pair_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__pair_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 //------------------------------------------------------------------------------ #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 int16_t *restrict Cx = (int16_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 int16_t *restrict Cx = (int16_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__pair_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 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) ; int16_t alpha_scalar ; int16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int16_t *) alpha_scalar_in)) ; beta_scalar = (*((int16_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else 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 ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; 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 ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ 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 } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
omp50_taskwait_depend.c
// RUN: %libomp-compile-and-run // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8 // clang does not yet support taskwait with depend clause // clang-12 introduced parsing, but no codegen // TODO: update expected result when codegen in clang is added // icc does not yet support taskwait with depend clause // TODO: update expected result when support for icc is added // XFAIL: clang, icc #include <stdio.h> #include <stdlib.h> #include <omp.h> #include "omp_my_sleep.h" int a = 0, b = 0; int task_grabbed = 0, task_can_proceed = 0; int task2_grabbed = 0, task2_can_proceed = 0; static void wait_on_flag(int *flag) { int flag_value; int timelimit = 30; int secs = 0; do { #pragma omp atomic read flag_value = *flag; my_sleep(1.0); secs++; if (secs == timelimit) { fprintf(stderr, "error: timeout in wait_on_flag()\n"); exit(EXIT_FAILURE); } } while (flag_value == 0); } static void signal_flag(int *flag) { #pragma omp atomic (*flag)++; } int main(int argc, char** argv) { // Ensure two threads are running int num_threads = omp_get_max_threads(); if (num_threads < 2) omp_set_num_threads(2); #pragma omp parallel shared(a) { int a_value; // Let us be extra safe here if (omp_get_num_threads() > 1) { #pragma omp single nowait { // Schedule independent child task that // waits to be flagged after sebsequent taskwait depend() #pragma omp task { signal_flag(&task_grabbed); wait_on_flag(&task_can_proceed); } // Let another worker thread grab the task to execute wait_on_flag(&task_grabbed); // This should be ignored since the task above has // no dependency information #pragma omp taskwait depend(inout: a) // Signal the independent task to proceed signal_flag(&task_can_proceed); // Schedule child task with dependencies that taskwait does // not care about #pragma omp task depend(inout: b) { signal_flag(&task2_grabbed); wait_on_flag(&task2_can_proceed); #pragma omp atomic b++; } // Let another worker thread grab the task to execute wait_on_flag(&task2_grabbed); // This should be ignored since the task above has // dependency information on b instead of a #pragma omp taskwait depend(inout: a) // Signal the task to proceed signal_flag(&task2_can_proceed); // Generate one child task for taskwait #pragma omp task shared(a) depend(inout: a) { my_sleep(1.0); #pragma omp atomic a++; } #pragma omp taskwait depend(inout: a) #pragma omp atomic read a_value = a; if (a_value != 1) { fprintf(stderr, "error: dependent task was not executed before " "taskwait finished\n"); exit(EXIT_FAILURE); } } // #pragma omp single } // if (num_threads > 1) } // #pragma omp parallel return EXIT_SUCCESS; }
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] = 4; tile_size[1] = 4; tile_size[2] = 24; tile_size[3] = 128; 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; }
timestep_opt2.c
#include <math.h> #include "timestep.h" #define REAL_CELL 1 double timestep(int ncells, double g, double sigma, int* celltype, double* H, double* U, double* V, double* dx, double* dy){ double wavespeed, xspeed, yspeed, dt; double mymindt = 1.0e20; #pragma omp simd private(wavespeed, xspeed, yspeed, dt) reduction(min:mymindt) for (int ic=0; ic<ncells ; ic++) { if (celltype[ic] == REAL_CELL) { wavespeed = sqrt(g*H[ic]); xspeed = (fabs(U[ic])+wavespeed)/dx[ic]; yspeed = (fabs(V[ic])+wavespeed)/dy[ic]; dt=sigma/(xspeed+yspeed); if (dt < mymindt) mymindt = dt; } } return(mymindt); }
floram_util.c
#include "floram_util.h" #include <omp.h> #include <unistd.h> void get_random_bytes(void *buf, size_t bytes) { //only supported on recent linuxes, unfortunately. //getrandom(buf, bytes, 0); FILE *fp = fopen("/dev/urandom", "r"); if (fread(buf, 1, bytes, fp) != bytes) { fprintf(stderr,"Could not read random bytes."); exit(1); } fclose(fp); } int floram_pma(void** dst, size_t alignment, size_t size) { return posix_memalign(dst, alignment, size); } int floram_zpma(void** dst, size_t alignment, size_t size) { int res = posix_memalign(dst, alignment, size); memset(*dst, 0, size); return res; } uint32_t floram_atomic_read(uint32_t * x) { return __atomic_load_n(x, __ATOMIC_RELAXED); } void floram_atomic_inc(uint32_t * x) { return __atomic_fetch_add(x, 1, __ATOMIC_RELAXED); } int floram_usleep(uint64_t x) { return usleep(x); } void floram_set_procs_for_data_size(size_t dsize) { #ifndef FLORAM_DISABLE_AUTO_THREAD_COUNT size_t recommended_cores = (dsize + CACHE_PER_CORE - 1) / CACHE_PER_CORE; size_t actual_cores = MIN(omp_get_num_procs(), MAX(1, recommended_cores)); omp_set_num_threads(actual_cores); #endif } #ifdef __AES__ #include <wmmintrin.h> #include <tmmintrin.h> #define KE(NK,OK,RND) NK = OK; \ NK = _mm_xor_si128(NK, _mm_slli_si128(NK, 4)); \ NK = _mm_xor_si128(NK, _mm_slli_si128(NK, 4)); \ NK = _mm_xor_si128(NK, _mm_slli_si128(NK, 4)); \ OK = _mm_xor_si128(NK, _mm_shuffle_epi32(_mm_aeskeygenassist_si128(OK, RND), 0xff)); #define KE2(NK,OK,RND) NK = OK; \ NK = _mm_xor_si128(NK, _mm_slli_si128(NK, 4)); \ NK = _mm_xor_si128(NK, _mm_slli_si128(NK, 4)); \ NK = _mm_xor_si128(NK, _mm_slli_si128(NK, 4)); \ NK = _mm_xor_si128(NK, _mm_shuffle_epi32(_mm_aeskeygenassist_si128(OK, RND), 0xff)); void offline_prg_init() { // Do nothing return; } void * offline_prg_keyschedule(uint8_t * src) { __m128i * r = malloc(11*sizeof(__m128i)); r[0] = _mm_load_si128((__m128i *) src); KE2(r[1], r[0], 0x01) KE2(r[2], r[1], 0x02) KE2(r[3], r[2], 0x04) KE2(r[4], r[3], 0x08) KE2(r[5], r[4], 0x10) KE2(r[6], r[5], 0x20) KE2(r[7], r[6], 0x40) KE2(r[8], r[7], 0x80) KE2(r[9], r[8], 0x1b) KE2(r[10], r[9], 0x36) return r; } void offline_prg(uint8_t * dest, uint8_t * src, void * ri) { __m128i or, mr; __m128i * r = ri; or = _mm_load_si128((__m128i *) src); mr = or; mr = _mm_xor_si128(mr, r[0]); mr = _mm_aesenc_si128(mr, r[1]); mr = _mm_aesenc_si128(mr, r[2]); mr = _mm_aesenc_si128(mr, r[3]); mr = _mm_aesenc_si128(mr, r[4]); mr = _mm_aesenc_si128(mr, r[5]); mr = _mm_aesenc_si128(mr, r[6]); mr = _mm_aesenc_si128(mr, r[7]); mr = _mm_aesenc_si128(mr, r[8]); mr = _mm_aesenc_si128(mr, r[9]); mr = _mm_aesenclast_si128(mr, r[10]); mr = _mm_xor_si128(mr, or); _mm_storeu_si128((__m128i*) dest, mr); } void offline_prg_oct(uint8_t * dest1, uint8_t * dest2, uint8_t * dest3, uint8_t * dest4, uint8_t * dest5, uint8_t * dest6, uint8_t * dest7, uint8_t * dest8, uint8_t * src1, uint8_t * src2, uint8_t * src3, uint8_t * src4, uint8_t * src5, uint8_t * src6, uint8_t * src7, uint8_t * src8, void * ri1, void * ri2 , void * ri3 , void * ri4, void * ri5, void * ri6 , void * ri7 , void * ri8 ) { __m128i * mr1 = dest1; __m128i * mr2 = dest2; __m128i * mr3 = dest3; __m128i * mr4 = dest4; __m128i * mr5 = dest5; __m128i * mr6 = dest6; __m128i * mr7 = dest7; __m128i * mr8 = dest8; __m128i * r1 = ri1; __m128i * r2 = ri2; __m128i * r3 = ri3; __m128i * r4 = ri4; __m128i * r5 = ri5; __m128i * r6 = ri6; __m128i * r7 = ri7; __m128i * r8 = ri8; *mr1 = _mm_load_si128((__m128i *) src1); *mr2 = _mm_load_si128((__m128i *) src2); *mr3 = _mm_load_si128((__m128i *) src3); *mr4 = _mm_load_si128((__m128i *) src4); *mr5 = _mm_load_si128((__m128i *) src5); *mr6 = _mm_load_si128((__m128i *) src6); *mr7 = _mm_load_si128((__m128i *) src7); *mr8 = _mm_load_si128((__m128i *) src8); *mr1 = _mm_xor_si128(*mr1, r1[0]); *mr2 = _mm_xor_si128(*mr2, r2[0]); *mr3 = _mm_xor_si128(*mr3, r3[0]); *mr4 = _mm_xor_si128(*mr4, r4[0]); *mr5 = _mm_xor_si128(*mr5, r5[0]); *mr6 = _mm_xor_si128(*mr6, r6[0]); *mr7 = _mm_xor_si128(*mr7, r7[0]); *mr8 = _mm_xor_si128(*mr8, r8[0]); *mr1 = _mm_aesenc_si128(*mr1, r1[1]); *mr2 = _mm_aesenc_si128(*mr2, r2[1]); *mr3 = _mm_aesenc_si128(*mr3, r3[1]); *mr4 = _mm_aesenc_si128(*mr4, r4[1]); *mr5 = _mm_aesenc_si128(*mr5, r5[1]); *mr6 = _mm_aesenc_si128(*mr6, r6[1]); *mr7 = _mm_aesenc_si128(*mr7, r7[1]); *mr8 = _mm_aesenc_si128(*mr8, r8[1]); *mr1 = _mm_aesenc_si128(*mr1, r1[2]); *mr2 = _mm_aesenc_si128(*mr2, r2[2]); *mr3 = _mm_aesenc_si128(*mr3, r3[2]); *mr4 = _mm_aesenc_si128(*mr4, r4[2]); *mr5 = _mm_aesenc_si128(*mr5, r5[2]); *mr6 = _mm_aesenc_si128(*mr6, r6[2]); *mr7 = _mm_aesenc_si128(*mr7, r7[2]); *mr8 = _mm_aesenc_si128(*mr8, r8[2]); *mr1 = _mm_aesenc_si128(*mr1, r1[3]); *mr2 = _mm_aesenc_si128(*mr2, r2[3]); *mr3 = _mm_aesenc_si128(*mr3, r3[3]); *mr4 = _mm_aesenc_si128(*mr4, r4[3]); *mr5 = _mm_aesenc_si128(*mr5, r5[3]); *mr6 = _mm_aesenc_si128(*mr6, r6[3]); *mr7 = _mm_aesenc_si128(*mr7, r7[3]); *mr8 = _mm_aesenc_si128(*mr8, r8[3]); *mr1 = _mm_aesenc_si128(*mr1, r1[4]); *mr2 = _mm_aesenc_si128(*mr2, r2[4]); *mr3 = _mm_aesenc_si128(*mr3, r3[4]); *mr4 = _mm_aesenc_si128(*mr4, r4[4]); *mr5 = _mm_aesenc_si128(*mr5, r5[4]); *mr6 = _mm_aesenc_si128(*mr6, r6[4]); *mr7 = _mm_aesenc_si128(*mr7, r7[4]); *mr8 = _mm_aesenc_si128(*mr8, r8[4]); *mr1 = _mm_aesenc_si128(*mr1, r1[5]); *mr2 = _mm_aesenc_si128(*mr2, r2[5]); *mr3 = _mm_aesenc_si128(*mr3, r3[5]); *mr4 = _mm_aesenc_si128(*mr4, r4[5]); *mr5 = _mm_aesenc_si128(*mr5, r5[5]); *mr6 = _mm_aesenc_si128(*mr6, r6[5]); *mr7 = _mm_aesenc_si128(*mr7, r7[5]); *mr8 = _mm_aesenc_si128(*mr8, r8[5]); *mr1 = _mm_aesenc_si128(*mr1, r1[6]); *mr2 = _mm_aesenc_si128(*mr2, r2[6]); *mr3 = _mm_aesenc_si128(*mr3, r3[6]); *mr4 = _mm_aesenc_si128(*mr4, r4[6]); *mr5 = _mm_aesenc_si128(*mr5, r5[6]); *mr6 = _mm_aesenc_si128(*mr6, r6[6]); *mr7 = _mm_aesenc_si128(*mr7, r7[6]); *mr8 = _mm_aesenc_si128(*mr8, r8[6]); *mr1 = _mm_aesenc_si128(*mr1, r1[7]); *mr2 = _mm_aesenc_si128(*mr2, r2[7]); *mr3 = _mm_aesenc_si128(*mr3, r3[7]); *mr4 = _mm_aesenc_si128(*mr4, r4[7]); *mr5 = _mm_aesenc_si128(*mr5, r5[7]); *mr6 = _mm_aesenc_si128(*mr6, r6[7]); *mr7 = _mm_aesenc_si128(*mr7, r7[7]); *mr8 = _mm_aesenc_si128(*mr8, r8[7]); *mr1 = _mm_aesenc_si128(*mr1, r1[8]); *mr2 = _mm_aesenc_si128(*mr2, r2[8]); *mr3 = _mm_aesenc_si128(*mr3, r3[8]); *mr4 = _mm_aesenc_si128(*mr4, r4[8]); *mr5 = _mm_aesenc_si128(*mr5, r5[8]); *mr6 = _mm_aesenc_si128(*mr6, r6[8]); *mr7 = _mm_aesenc_si128(*mr7, r7[8]); *mr8 = _mm_aesenc_si128(*mr8, r8[8]); *mr1 = _mm_aesenc_si128(*mr1, r1[9]); *mr2 = _mm_aesenc_si128(*mr2, r2[9]); *mr3 = _mm_aesenc_si128(*mr3, r3[9]); *mr4 = _mm_aesenc_si128(*mr4, r4[9]); *mr5 = _mm_aesenc_si128(*mr5, r5[9]); *mr6 = _mm_aesenc_si128(*mr6, r6[9]); *mr7 = _mm_aesenc_si128(*mr7, r7[9]); *mr8 = _mm_aesenc_si128(*mr8, r8[9]); *mr1 = _mm_aesenclast_si128(*mr1, r1[10]); *mr2 = _mm_aesenclast_si128(*mr2, r2[10]); *mr3 = _mm_aesenclast_si128(*mr3, r3[10]); *mr4 = _mm_aesenclast_si128(*mr4, r4[10]); *mr5 = _mm_aesenclast_si128(*mr5, r5[10]); *mr6 = _mm_aesenclast_si128(*mr6, r6[10]); *mr7 = _mm_aesenclast_si128(*mr7, r7[10]); *mr8 = _mm_aesenclast_si128(*mr8, r8[10]); *mr1 = _mm_xor_si128(*mr1, _mm_load_si128((__m128i *) src1)); *mr2 = _mm_xor_si128(*mr2, _mm_load_si128((__m128i *) src2)); *mr3 = _mm_xor_si128(*mr3, _mm_load_si128((__m128i *) src3)); *mr4 = _mm_xor_si128(*mr4, _mm_load_si128((__m128i *) src4)); *mr5 = _mm_xor_si128(*mr5, _mm_load_si128((__m128i *) src5)); *mr6 = _mm_xor_si128(*mr6, _mm_load_si128((__m128i *) src6)); *mr7 = _mm_xor_si128(*mr7, _mm_load_si128((__m128i *) src7)); *mr8 = _mm_xor_si128(*mr8, _mm_load_si128((__m128i *) src8)); } void offline_expand_from(uint8_t * dest, uint8_t * src, size_t i, size_t n) { // this version handles the case when n!=2 using a loop __m128i seed; seed = _mm_load_si128((__m128i *) src); __m128i r1,r2,r3,r4,r5,r6,r7,r8,r9,r10; // next key __m128i mr, ok; ok = seed; KE2(r1, ok, 0x01) KE2(r2, r1, 0x02) KE2(r3, r2, 0x04) KE2(r4, r3, 0x08) KE2(r5, r4, 0x10) KE2(r6, r5, 0x20) KE2(r7, r6, 0x40) KE2(r8, r7, 0x80) KE2(r9, r8, 0x1b) KE2(r10, r9, 0x36) __m128i mask = _mm_set_epi64((__m64)0x08090a0b0c0d0e0fULL, (__m64)0x0001020304050607ULL ); floram_set_procs_for_data_size(n*BLOCKSIZE); #pragma omp parallel for schedule(guided) for(size_t li=0; li<n-n%4; li+=4) { __m128i mr1, mr2, mr3, mr4; mr1 = _mm_set_epi64((__m64)(li+i),(__m64)0l); mr2 = _mm_set_epi64((__m64)(li+i+1),(__m64)0l); mr3 = _mm_set_epi64((__m64)(li+i+2),(__m64)0l); mr4 = _mm_set_epi64((__m64)(li+i+3),(__m64)0l); mr1 = _mm_shuffle_epi8 (mr1, mask); mr2 = _mm_shuffle_epi8 (mr2, mask); mr3 = _mm_shuffle_epi8 (mr3, mask); mr4 = _mm_shuffle_epi8 (mr4, mask); mr1 = _mm_xor_si128(mr1, ok); mr2 = _mm_xor_si128(mr2, ok); mr3 = _mm_xor_si128(mr3, ok); mr4 = _mm_xor_si128(mr4, ok); mr1 = _mm_aesenc_si128(mr1, r1); mr2 = _mm_aesenc_si128(mr2, r1); mr3 = _mm_aesenc_si128(mr3, r1); mr4 = _mm_aesenc_si128(mr4, r1); mr1 = _mm_aesenc_si128(mr1, r2); mr2 = _mm_aesenc_si128(mr2, r2); mr3 = _mm_aesenc_si128(mr3, r2); mr4 = _mm_aesenc_si128(mr4, r2); mr1 = _mm_aesenc_si128(mr1, r3); mr2 = _mm_aesenc_si128(mr2, r3); mr3 = _mm_aesenc_si128(mr3, r3); mr4 = _mm_aesenc_si128(mr4, r3); mr1 = _mm_aesenc_si128(mr1, r4); mr2 = _mm_aesenc_si128(mr2, r4); mr3 = _mm_aesenc_si128(mr3, r4); mr4 = _mm_aesenc_si128(mr4, r4); mr1 = _mm_aesenc_si128(mr1, r5); mr2 = _mm_aesenc_si128(mr2, r5); mr3 = _mm_aesenc_si128(mr3, r5); mr4 = _mm_aesenc_si128(mr4, r5); mr1 = _mm_aesenc_si128(mr1, r6); mr2 = _mm_aesenc_si128(mr2, r6); mr3 = _mm_aesenc_si128(mr3, r6); mr4 = _mm_aesenc_si128(mr4, r6); mr1 = _mm_aesenc_si128(mr1, r7); mr2 = _mm_aesenc_si128(mr2, r7); mr3 = _mm_aesenc_si128(mr3, r7); mr4 = _mm_aesenc_si128(mr4, r7); mr1 = _mm_aesenc_si128(mr1, r8); mr2 = _mm_aesenc_si128(mr2, r8); mr3 = _mm_aesenc_si128(mr3, r8); mr4 = _mm_aesenc_si128(mr4, r8); mr1 = _mm_aesenc_si128(mr1, r9); mr2 = _mm_aesenc_si128(mr2, r9); mr3 = _mm_aesenc_si128(mr3, r9); mr4 = _mm_aesenc_si128(mr4, r9); mr1 = _mm_aesenclast_si128(mr1, r10); mr2 = _mm_aesenclast_si128(mr2, r10); mr3 = _mm_aesenclast_si128(mr3, r10); mr4 = _mm_aesenclast_si128(mr4, r10); uint8_t* pp1 = dest+(li*16); uint8_t* pp2 = dest+((li+1)*16); uint8_t* pp3 = dest+((li+2)*16); uint8_t* pp4 = dest+((li+3)*16); _mm_storeu_si128((__m128i*) pp1, mr1); _mm_storeu_si128((__m128i*) pp2, mr2); _mm_storeu_si128((__m128i*) pp3, mr3); _mm_storeu_si128((__m128i*) pp4, mr4); } for(size_t li = n-n%4; li<n; li++) { mr = _mm_set_epi64((__m64)(li+i),(__m64)0l); // msg = li mr = _mm_shuffle_epi8 (mr, mask); mr = _mm_xor_si128(mr, ok); // round 0 mr = _mm_aesenc_si128(mr, r1); mr = _mm_aesenc_si128(mr, r2); mr = _mm_aesenc_si128(mr, r3); mr = _mm_aesenc_si128(mr, r4); mr = _mm_aesenc_si128(mr, r5); mr = _mm_aesenc_si128(mr, r6); mr = _mm_aesenc_si128(mr, r7); mr = _mm_aesenc_si128(mr, r8); mr = _mm_aesenc_si128(mr, r9); mr = _mm_aesenclast_si128(mr, r10); uint8_t* pp = dest+(li*16); _mm_storeu_si128((__m128i*) pp, mr); } } #else //__AES__ #include "aes_gladman/aes.h" #define htonll(x) ((1==htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32)) void offline_prg_init() { aes_init(); } void * offline_prg_keyschedule(uint8_t * src) { uint8_t * r = malloc(11*16); aes_encrypt_ctx cx = {0}; aes_encrypt_key128(src, &cx); memcpy(r, cx.ks, 11*16); return r; } void offline_prg(uint8_t * dest, uint8_t * src, void * ri) { aes_encrypt_ctx cx = {0}; memcpy(cx.ks, ri, 11*16); cx.inf.l = 0; cx.inf.b[0] = 10 * 16; aes_encrypt(src, dest, &cx); #pragma omp simd for (uint8_t ii = 0; ii < 2; ii++) { ((uint64_t *) dest)[ii] ^= ((uint64_t *) src)[ii]; } } void offline_prg_oct(uint8_t * dest1, uint8_t * dest2, uint8_t * dest3, uint8_t * dest4, uint8_t * dest5, uint8_t * dest6, uint8_t * dest7, uint8_t * dest8, uint8_t * src1, uint8_t * src2, uint8_t * src3, uint8_t * src4, uint8_t * src5, uint8_t * src6, uint8_t * src7, uint8_t * src8, void * ri1, void * ri2 , void * ri3 , void * ri4, void * ri5, void * ri6 , void * ri7 , void * ri8 ) { offline_prg(dest1, src1, ri1); offline_prg(dest2, src2, ri2); offline_prg(dest3, src3, ri3); offline_prg(dest4, src4, ri4); offline_prg(dest5, src5, ri5); offline_prg(dest6, src6, ri6); offline_prg(dest7, src7, ri7); offline_prg(dest8, src8, ri8); } void offline_expand_from(uint8_t * dest, uint8_t * src, size_t i, size_t n) { uint8_t * key = offline_prg_keyschedule(src); aes_encrypt_ctx cx = {0}; memcpy(cx.ks, key, 11*16); cx.inf.l = 0; cx.inf.b[0] = 10 * 16; free(key); floram_set_procs_for_data_size(n*BLOCKSIZE); #pragma omp parallel for schedule(guided) for(size_t li=0; li<n; li++) { uint64_t iv[2] = {0,htonll(li+i)}; aes_encrypt(iv,&dest[li*16],&cx); } } #endif //__AES__ void offline_expand(uint8_t * dest, uint8_t * src, size_t n) { offline_expand_from(dest, src, 0, n); }
fracstep_GLS_strategy.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Author Julio Marti. // #if !defined(KRATOS_GLS_STRATEGY) #define KRATOS_GLS_STRATEGY /* System includes */ /* External includes */ #include "boost/smart_ptr.hpp" /* Project includes */ #include "utilities/geometry_utilities.h" #include "pfem_2_application.h" #include "includes/define.h" #include "includes/model_part.h" #include "includes/deprecated_variables.h" #include "includes/cfd_variables.h" #include "utilities/openmp_utils.h" #include "processes/process.h" #include "solving_strategies/schemes/scheme.h" #include "solving_strategies/strategies/solving_strategy.h" #include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme.h" #include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme_slip.h" #include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver.h" #include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver_componentwise.h" #include "solving_strategies/strategies/residualbased_linear_strategy.h" //#include "custom_utilities/solver_settings.h" #ifdef _OPENMP #include "omp.h" #endif #define QCOMP namespace Kratos { /**@name Kratos Globals */ /*@{ */ /*@} */ /**@name Type Definitions */ /*@{ */ /*@} */ /**@name Enum's */ /*@{ */ /*@} */ /**@name Functions */ /*@{ */ /*@} */ /**@name Kratos Classes */ /*@{ */ /// Short class definition. /** Detail class definition. \URL[Example of use html]{ extended_documentation/no_ex_of_use.html} \URL[Example of use pdf]{ extended_documentation/no_ex_of_use.pdf} \URL[Example of use doc]{ extended_documentation/no_ex_of_use.doc} \URL[Example of use ps]{ extended_documentation/no_ex_of_use.ps} \URL[Extended documentation html]{ extended_documentation/no_ext_doc.html} \URL[Extended documentation pdf]{ extended_documentation/no_ext_doc.pdf} \URL[Extended documentation doc]{ extended_documentation/no_ext_doc.doc} \URL[Extended documentation ps]{ extended_documentation/no_ext_doc.ps} */ template<class TSparseSpace, class TDenseSpace, class TLinearSolver > class FracStepStrategy : public SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> { public: /**@name Type Definitions */ /*@{ */ /** Counted pointer of ClassName */ KRATOS_CLASS_POINTER_DEFINITION( FracStepStrategy ); typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TDataType TDataType; //typedef typename BaseType::DofSetType DofSetType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef OpenMPUtils::PartitionVector PartitionVector; /*@} */ /**@name Life Cycle */ /*@{ */ /** * Constructor of the FracStepStrategy. Implements the solutions strategy for a Navier Stokes solver * using the fractional step approach. Prepared for both openmp parallelism and mpi parallelism. The function * also calls internally the "Check" function to verify that the input is complete * @param model_part - contains Nodes, elements, etc. * @param solver_config - auxiliary file to ease the configuration. Prescribes the linear solvers and builiding * strategies to be used in defining the current composite solver. * @see FractionalStepConfiguration for OpenMP setting or * @see TrilinosFractionalStepConfiguration (in the Trilinos application) for the MPI version * @param ReformDofAtEachIteration - if set to true the graph of the matrix is recomputed at each iteration * @param velocity_toll - tolerance used in the velocity convergence check * @param pressure_toll - pressure tolerance in finalizing the predictor corrector strategy * @param MaxVelocityIterations - maximum number of iterations of the velocity solver * @param MaxPressureIterations - max number of iteration for the predictor corrector strategy * @param time_order - 1=BDF1 , 2=BDF2 * @param domain_size 2=2D, 3=3D * @param predictor_corrector - true->for predictor corrector, false->standard Fractional Step (default = false) */ FracStepStrategy( ModelPart& model_part, typename TLinearSolver::Pointer pNewVelocityLinearSolver,typename TLinearSolver::Pointer pNewPressureLinearSolver, bool ReformDofAtEachIteration = true, double velocity_toll = 0.01, double pressure_toll = 0.01, int MaxVelocityIterations = 3, int MaxPressureIterations = 1, unsigned int time_order = 2, unsigned int domain_size = 2, bool predictor_corrector = false ) : SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(model_part, false)//, msolver_config(solver_config) { KRATOS_TRY this->mvelocity_toll = velocity_toll; this->mpressure_toll = pressure_toll; this->mMaxVelIterations = MaxVelocityIterations; this->mMaxPressIterations = MaxPressureIterations; this->mtime_order = time_order; this->mprediction_order = time_order; this->mdomain_size = domain_size; this->mpredictor_corrector = predictor_corrector; this->mReformDofAtEachIteration = ReformDofAtEachIteration; this->proj_is_initialized = false; this->mecho_level = 1; bool CalculateReactions = false; bool CalculateNormDxFlag = true; bool ReformDofAtEachIteration = false; //computation of the fractional vel velocity (first step) //3 dimensional case //typedef typename Kratos::VariableComponent<Kratos::VectorComponentAdaptor<Kratos::array_1d<double, 3 > > > VarComponent; typedef typename BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>::Pointer BuilderSolverTypePointer; typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; //initializing fractional velocity solution step typedef Scheme< TSparseSpace, TDenseSpace > SchemeType; typename SchemeType::Pointer pscheme = typename SchemeType::Pointer(new ResidualBasedIncrementalUpdateStaticScheme< TSparseSpace, TDenseSpace > ()); BuilderSolverTypePointer vel_build = BuilderSolverTypePointer(new ResidualBasedEliminationBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver > (pNewVelocityLinearSolver)); this->mpfracvel_strategy = typename BaseType::Pointer(new ResidualBasedLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver > (model_part, pscheme, pNewVelocityLinearSolver, vel_build, CalculateReactions, ReformDofAtEachIteration, CalculateNormDxFlag)); this->mpfracvel_strategy->SetEchoLevel(1); BuilderSolverTypePointer pressure_build = BuilderSolverTypePointer(new ResidualBasedEliminationBuilderAndSolverComponentwise<TSparseSpace, TDenseSpace, TLinearSolver, Variable<double> >(pNewPressureLinearSolver, PRESSURE)); this->mppressurestep = typename BaseType::Pointer(new ResidualBasedLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver > (model_part, pscheme,pNewPressureLinearSolver, pressure_build, CalculateReactions, ReformDofAtEachIteration, CalculateNormDxFlag)); this->mppressurestep->SetEchoLevel(2); this->m_step = 1; mHasSlipProcess = false; KRATOS_CATCH("") } /** Destructor. */ virtual ~FracStepStrategy() { } /** Destructor. */ double Solve() override { KRATOS_TRY Timer time; Timer::Start("Solve_strategy"); #if defined(QCOMP) double Dp_norm; Dp_norm = IterativeSolve(); #else //multifluids AssignInitialStepValues(); double Dp_norm = 1.00; //int iteration = 0; //int MaxPressureIterations = this->mMaxPressIterations; Dp_norm = IterativeSolve(); #endif //this->Clear(); this->m_step += 1; return Dp_norm; KRATOS_CATCH("") } double SolvePressure() { KRATOS_TRY //ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); this->SolveStep7(); //pold=pn+1 double Dp_norm = this->SolveStep2(); return Dp_norm; KRATOS_CATCH("") } double IterativeSolve() { KRATOS_TRY Timer time; Timer::Start("Solve_ambos"); double Dp_norm = 1.00; ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); //KRATOS_THROW_ERROR(std::logic_error, "method not implemented" , ""); rCurrentProcessInfo[VISCOSITY] = 1.0; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin();i != BaseType::GetModelPart().NodesEnd(); ++i) { i->FastGetSolutionStepValue(VELOCITY_X,1) = i->FastGetSolutionStepValue(VELOCITY_X); i->FastGetSolutionStepValue(VELOCITY_Y,1) = i->FastGetSolutionStepValue(VELOCITY_Y); i->FastGetSolutionStepValue(VELOCITY_Z,1) = i->FastGetSolutionStepValue(VELOCITY_Z); } #if defined(QCOMP) this->SolveStep1(this->mvelocity_toll, this->mMaxVelIterations); #else this->SolveStep3(); #endif //double p_norm=0.0; #if defined(QCOMP) //polimero this->SolveStepaux(); //int MaxPressureIterations = this->mMaxPressIterations; //int rank = BaseType::GetModelPart().GetCommunicator().MyPID(); //double p_norm = SavePressureIteration(); Dp_norm = 1.0; //Timer::Stop("Solve_ambos"); //KRATOS_WATCH(time) #else int iteration = 0; while ( iteration++ < 3) { Dp_norm = SolvePressure(); double p_norm = SavePressureIteration(); if (fabs(p_norm) > 1e-10){ Dp_norm /= p_norm; } else Dp_norm = 1.0; this->SolveStep4(); } #endif this->Clear(); return Dp_norm; KRATOS_CATCH("") } /** * copies PRESSURE->PRESSURE_OLD_IT * @return the norm of the pressure vector */ double SavePressureIteration() { KRATOS_TRY double local_p_norm = 0.0; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin(); i != BaseType::GetModelPart().NodesEnd(); ++i) { //setting the old value of the pressure to the current one const double& p = (i)->FastGetSolutionStepValue(PRESSURE); local_p_norm += p*p; } double p_norm = local_p_norm; //TODO: prepare for parallelization p_norm = sqrt(p_norm); return p_norm; KRATOS_CATCH("") } void AssignInitialStepValues() { KRATOS_TRY ModelPart& model_part=BaseType::GetModelPart(); const double dt = model_part.GetProcessInfo()[DELTA_TIME]; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin();i != BaseType::GetModelPart().NodesEnd(); ++i) { (i)->FastGetSolutionStepValue(PRESSURE_OLD_IT) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE,1) = 0.0; } KRATOS_CATCH(""); } /** * this function performs the iterative solution of the non-linear velocity problem in the first step * of the fractional step procedure * @param velocity_toll - tolerance used in the velocity convergence check * @param MaxIterations - max number of iterations */ void SolveStep1(double velocity_toll, int MaxIterations) { KRATOS_TRY; Timer time; Timer::Start("SolveStep1"); int rank = BaseType::GetModelPart().GetCommunicator().MyPID(); double normDx = 0.0; bool is_converged = false; int iteration = 0; //double iteration = 1; //ModelPart& model_part=BaseType::GetModelPart(); while (is_converged == false && iteration++<3) { //perform one iteration over the fractional step velocity normDx = FractionalVelocityIteration(); is_converged = ConvergenceCheck(normDx, velocity_toll); } if (is_converged == false) if (rank == 0) std::cout << "ATTENTION: convergence NOT achieved" << std::endl; KRATOS_CATCH(""); } double FractionalVelocityIteration() { KRATOS_TRY ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 1; double normDx = mpfracvel_strategy->Solve(); return normDx; KRATOS_CATCH(""); } void SolveStep4() { KRATOS_TRY; Timer time; Timer::Start("paso_4"); array_1d<double, 3 > zero = ZeroVector(3); //#ifdef _OPENMP // int number_of_threads = omp_get_max_threads(); //#else // int number_of_threads = 1; //#endif //ModelPart& model_part=BaseType::GetModelPart(); //double dt = model_part.GetProcessInfo()[DELTA_TIME]; //dt=0.005; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin();i != BaseType::GetModelPart().NodesEnd(); ++i) { array_1d<double, 3 > zero = ZeroVector(3); i->FastGetSolutionStepValue(FORCE)=ZeroVector(3); double & nodal_mass = (i)->FastGetSolutionStepValue(NODAL_MASS); nodal_mass = 0.0; } ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 6; for (ModelPart::ElementIterator i = BaseType::GetModelPart().ElementsBegin(); i != BaseType::GetModelPart().ElementsEnd(); ++i) { (i)->InitializeSolutionStep(BaseType::GetModelPart().GetProcessInfo()); } for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin();i != BaseType::GetModelPart().NodesEnd(); ++i) { array_1d<double,3>& force_temp = i->FastGetSolutionStepValue(FORCE); double A = (i)->FastGetSolutionStepValue(NODAL_MASS); if(A<0.0000000000000001){ A=1.0; } double dt_Minv = 0.005 / A ; //dt_Minv=1.0; force_temp *= dt_Minv; //KRATOS_WATCH(force_temp); if(!i->IsFixed(VELOCITY_X)) //FRACT_VEL_X { i->FastGetSolutionStepValue(VELOCITY_X) += force_temp[0] ; } if(!i->IsFixed(VELOCITY_Y)) { i->FastGetSolutionStepValue(VELOCITY_Y) +=force_temp[1]; } if(!i->IsFixed(VELOCITY_Z)) { i->FastGetSolutionStepValue(VELOCITY_Z) +=force_temp[2] ; } if(i->IsFixed(VELOCITY_X)) { i->FastGetSolutionStepValue(VELOCITY_X)=0.0; //i->FastGetSolutionStepValue(VELOCITY_X,1); } if(i->IsFixed(VELOCITY_Y)) { i->FastGetSolutionStepValue(VELOCITY_Y)= 0.0; //i->FastGetSolutionStepValue(VELOCITY_Y,1) ; } if(i->IsFixed(VELOCITY_Z)) { i->FastGetSolutionStepValue(VELOCITY_Z)=0.0; //i->FastGetSolutionStepValue(VELOCITY_Z,1) ; } } KRATOS_CATCH(""); } void SolveStep7() { KRATOS_TRY; // ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); array_1d<double, 3 > zero = ZeroVector(3); //Vector& BDFcoeffs = rCurrentProcessInfo[BDF_COEFFICIENTS]; #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif //ModelPart& model_part=BaseType::GetModelPart(); //const double dt = model_part.GetProcessInfo()[DELTA_TIME]; vector<unsigned int> partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Nodes().size(), partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); for (typename ModelPart::NodesContainerType::iterator it=it_begin; it!=it_end; ++it) { it->FastGetSolutionStepValue(PRESSURE_OLD_IT)=it->FastGetSolutionStepValue(PRESSURE); } } KRATOS_CATCH(""); } double SolveStep2() { KRATOS_TRY; Timer::Start("Presion"); BaseType::GetModelPart().GetProcessInfo()[FRACTIONAL_STEP] = 4; return mppressurestep->Solve(); Timer::Stop("Presion"); //KRATOS_WATCH(*time) //mppressurestep->Clear(); KRATOS_CATCH(""); } void SolveStep3() { KRATOS_TRY ModelPart& model_part=BaseType::GetModelPart(); const double dt = model_part.GetProcessInfo()[DELTA_TIME]; Timer time; Timer::Start("paso_3"); #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif vector<unsigned int> partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Nodes().size(), partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { double & nodal_mass = (i)->FastGetSolutionStepValue(NODAL_MASS); nodal_mass = 0.0; noalias(i->FastGetSolutionStepValue(FORCE)) = zero; //double & nodal_area = (i)->FastGetSolutionStepValue(NODAL_AREA); //nodal_area = 0.0; } } array_1d<double,3> zero = ZeroVector(3); ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 5; vector<unsigned int> elem_partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Elements().size(), elem_partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::ElementIterator it_begin = BaseType::GetModelPart().ElementsBegin() + elem_partition[k]; ModelPart::ElementIterator it_end = BaseType::GetModelPart().ElementsBegin() + elem_partition[k + 1]; for (ModelPart::ElementIterator i = it_begin; i != it_end; ++i) { (i)->InitializeSolutionStep(BaseType::GetModelPart().GetProcessInfo()); } } #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { array_1d<double,3>& force_temp = i->FastGetSolutionStepValue(FORCE); force_temp *=(1.0/ i->FastGetSolutionStepValue(NODAL_MASS)); //array_1d<double,3>& vel = i->FastGetSolutionStepValue(VELOCITY); i->FastGetSolutionStepValue(VELOCITY) = i->FastGetSolutionStepValue(VELOCITY,1) + dt * force_temp; } } KRATOS_CATCH(""); } void SolveStepaux() { KRATOS_TRY Timer time; Timer::Start("SolveStepaux"); //ModelPart& model_part=BaseType::GetModelPart(); //const double dt = model_part.GetProcessInfo()[DELTA_TIME]; #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif //number_of_threads = 1; vector<unsigned int> partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Nodes().size(), partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { double & nodal_mass = (i)->FastGetSolutionStepValue(NODAL_MASS); nodal_mass = 0.0; i->FastGetSolutionStepValue(PRESSUREAUX)=0.0; i->FastGetSolutionStepValue(PRESSURE)=0.0; } } ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 7; vector<unsigned int> elem_partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Elements().size(), elem_partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::ElementIterator it_begin = BaseType::GetModelPart().ElementsBegin() + elem_partition[k]; ModelPart::ElementIterator it_end = BaseType::GetModelPart().ElementsBegin() + elem_partition[k + 1]; for (ModelPart::ElementIterator i = it_begin; i != it_end; ++i) { (i)->InitializeSolutionStep(BaseType::GetModelPart().GetProcessInfo()); } } #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { if(i->FastGetSolutionStepValue(NODAL_MASS)==0.0) { i->FastGetSolutionStepValue(PRESSURE)=0.0; } else { //if() i->FastGetSolutionStepValue(PRESSURE)=i->FastGetSolutionStepValue(PRESSUREAUX) * (1.0/ i->FastGetSolutionStepValue(NODAL_MASS)); } } } KRATOS_CATCH(""); } /** * implements the convergence check for the velocities * convergence is considered achieved when normDx/norm(v) is less than tol * @param normDx norm of the VELOCITY correction * @param toll tolerance accepted * @return true if converged */ bool ConvergenceCheck(const double& normDx, double tol) { KRATOS_TRY; double norm_v = 0.00; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin(); i != BaseType::GetModelPart().NodesEnd(); ++i) { const array_1d<double, 3 > & v = (i)->FastGetSolutionStepValue(VELOCITY); norm_v += v[0] * v[0]; norm_v += v[1] * v[1]; norm_v += v[2] * v[2]; } //BaseType::GetModelPart().GetCommunicator().SumAll(norm_v); double norm_v1 = sqrt(norm_v); if (norm_v1 == 0.0) norm_v1 = 1.00; double ratio = normDx / norm_v1; int rank = BaseType::GetModelPart().GetCommunicator().MyPID(); if (rank == 0) std::cout << "velocity ratio = " << ratio << std::endl; if (ratio < tol) { if (rank == 0) std::cout << "convergence achieved" << std::endl; return true; } return false; KRATOS_CATCH(""); } void Compute() { KRATOS_TRY #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif array_1d<double,3> aux; array_1d<double,3> aux1; ModelPart& model_part=BaseType::GetModelPart(); const double dt = model_part.GetProcessInfo()[DELTA_TIME]; vector<unsigned int> partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Nodes().size(), partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); //first of all set to zero the nodal variables to be updated nodally for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { noalias(i->FastGetSolutionStepValue(FORCE)) = zero; (i)->FastGetSolutionStepValue(NODAL_MASS)=0.0; } } ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 6; vector<unsigned int> elem_partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Elements().size(), elem_partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::ElementIterator it_begin = BaseType::GetModelPart().ElementsBegin() + elem_partition[k]; ModelPart::ElementIterator it_end = BaseType::GetModelPart().ElementsBegin() + elem_partition[k + 1]; for (ModelPart::ElementIterator i = it_begin; i != it_end; ++i) { (i)->InitializeSolutionStep(BaseType::GetModelPart().GetProcessInfo()); } } #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); //first of all set to zero the nodal variables to be updated nodally for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { array_1d<double,3>& force_temp = i->FastGetSolutionStepValue(FORCE); force_temp -=i->FastGetSolutionStepValue(NODAL_MASS) * ((i)->FastGetSolutionStepValue(VELOCITY)-(i)->FastGetSolutionStepValue(VELOCITY,1))/dt; } } KRATOS_CATCH(""); } /** * * @param Level */ virtual void SetEchoLevel(int Level) override { mecho_level = Level; mpfracvel_strategy->SetEchoLevel(Level); mppressurestep->SetEchoLevel(Level); } virtual void Clear() override { int rank = BaseType::GetModelPart().GetCommunicator().MyPID(); if (rank == 0) KRATOS_WATCH("FracStepStrategy Clear Function called"); mpfracvel_strategy->Clear(); mppressurestep->Clear(); } virtual double GetStageResidualNorm(unsigned int step) { if (step <= 3) return mpfracvel_strategy->GetResidualNorm(); if (step == 4) return mppressurestep->GetResidualNorm(); else return 0.0; } /*@} */ /**@name Operators */ /*@{ */ /*@} */ /**@name Operations */ /*@{ */ /*@} */ /**@name Access */ /*@{ */ /*@} */ /**@name Inquiry */ /*@{ */ /*@} */ /**@name Friends */ /*@{ */ /*@} */ protected: /**@name Protected static Member Variables */ /*@{ */ /*@} */ /**@name Protected member Variables */ /*@{ */ typename BaseType::Pointer mpfracvel_strategy; typename BaseType::Pointer mppressurestep; double mvelocity_toll; double mpressure_toll; int mMaxVelIterations; int mMaxPressIterations; unsigned int mtime_order; unsigned int mprediction_order; bool mpredictor_corrector; bool mReformDofAtEachIteration; int mecho_level; bool muse_dt_in_stabilization; /*@} */ /**@name Protected Operators*/ /*@{ */ /*@} */ /**@name Protected Operations*/ /*@{ */ /*@} */ /**@name Protected Access */ /*@{ */ /*@} */ /**@name Protected Inquiry */ /*@{ */ /*@} */ /**@name Protected LifeCycle */ /*@{ */ /*@} */ private: /**@name Static Member Variables */ /*@{ */ /*@} */ /**@name Member Variables */ /*@{ */ unsigned int m_step; unsigned int mdomain_size; bool proj_is_initialized; //GenerateSlipConditionProcess::Pointer mpSlipProcess; bool mHasSlipProcess; std::vector< Process::Pointer > mInitializeIterationProcesses; inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, vector<unsigned int>& partitions) { partitions.resize(number_of_threads + 1); int partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for (unsigned int i = 1; i < number_of_threads; i++) partitions[i] = partitions[i - 1] + partition_size; } /*@} */ /**@name Private Operators*/ /*@{ */ //this funcion is needed to ensure that all the memory is allocated correctly /*@} */ /**@name Private Operations*/ /*@{ */ /*@} */ /**@name Private Access */ /*@{ */ /*@} */ /**@name Private Inquiry */ /*@{ */ /*@} */ /**@name Un accessible methods */ /*@{ */ /** Copy constructor. */ FracStepStrategy(const FracStepStrategy& Other); /*@} */ }; /* Class FracStepStrategy */ /*@} */ /**@name Type Definitions */ /*@{ */ /*@} */ } /* namespace Kratos.*/ #endif /* KRATOS_RESIDUALBASED_FRACTIONALSTEP_STRATEGY defined */
GB_unaryop__minv_uint64_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_uint64_int16 // op(A') function: GB_tran__minv_uint64_int16 // C type: uint64_t // A type: int16_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 64) #define GB_ATYPE \ int16_t #define GB_CTYPE \ uint64_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 = GB_IMINV_UNSIGNED (x, 64) ; // casting #define GB_CASTING(z, x) \ uint64_t z = (uint64_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT64 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint64_int16 ( uint64_t *restrict Cx, const int16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_uint64_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bml_export_ellpack_typed.c
#include "../../macros.h" #include "../../typed.h" #include "../bml_allocate.h" #include "../bml_logger.h" #include "../bml_types.h" #include "bml_allocate_ellpack.h" #include "bml_export_ellpack.h" #include "bml_types_ellpack.h" #include <complex.h> #include <math.h> #include <stdlib.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /** Convert a bml matrix into a dense matrix. * * \ingroup convert_group * * \param A The bml matrix * \return The dense matrix */ void *TYPED_FUNC( bml_export_to_dense_ellpack) ( bml_matrix_ellpack_t * A, bml_dense_order_t order) { int N = A->N; int M = A->M; int *A_nnz = A->nnz; int *A_index = A->index; REAL_T *A_dense = bml_allocate_memory(sizeof(REAL_T) * A->N * A->N); REAL_T *A_value = A->value; switch (order) { case dense_row_major: #pragma omp parallel for shared(N, M, A_nnz, A_index, A_value, A_dense) for (int i = 0; i < N; i++) { for (int j = 0; j < A_nnz[i]; j++) { A_dense[ROWMAJOR (i, A_index[ROWMAJOR(i, j, N, M)], N, N)] = A_value[ROWMAJOR(i, j, N, M)]; } } break; case dense_column_major: #pragma omp parallel for shared(N, M, A_nnz, A_index, A_value, A_dense) for (int i = 0; i < N; i++) { for (int j = 0; j < A_nnz[i]; j++) { A_dense[COLMAJOR (i, A_index[ROWMAJOR(i, j, N, M)], N, N)] = A_value[ROWMAJOR(i, j, N, M)]; } } break; default: LOG_ERROR("unknown order\n"); break; } return A_dense; }
GB_unaryop__abs_uint16_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_uint16_uint32 // op(A') function: GB_tran__abs_uint16_uint32 // C type: uint16_t // A type: uint32_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint16_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_CASTING(z, x) \ uint16_t z = (uint16_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT16 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint16_uint32 ( uint16_t *restrict Cx, const uint32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_uint16_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
opencl_office2010_fmt_plug.c
/* MS Office 2010 cracker patch for JtR. Hacked together during March of 2012 by * Dhiru Kholia <dhiru.kholia at gmail.com> * * OpenCL support by magnum. * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> * and Copyright (c) 2012, magnum and it is hereby released to the general public * under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_office2010; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_office2010); #else #include "sha.h" #include "aes.h" #include <stdio.h> #include <stdlib.h> #include <string.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 "unicode.h" #include "common-opencl.h" #include "office_common.h" #include "config.h" #define PLAINTEXT_LENGTH 51 #define UNICODE_LENGTH 104 /* In octets, including 0x80 */ #define FORMAT_LABEL "office2010-opencl" #define FORMAT_NAME "MS Office 2010" #define OCL_ALGORITHM_NAME "SHA1 OpenCL" #define CPU_ALGORITHM_NAME " AES" #define ALGORITHM_NAME OCL_ALGORITHM_NAME CPU_ALGORITHM_NAME #define BENCHMARK_COMMENT " (100,000 iterations)" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 0 #define BINARY_ALIGN 1 #define SALT_LENGTH 16 #define SALT_SIZE sizeof(*cur_salt) #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests tests[] = { /* 2010-Default_myhovercraftisfullofeels_.docx */ {"$office$*2010*100000*128*16*213aefcafd9f9188e78c1936cbb05a44*d5fc7691292ab6daf7903b9a8f8c8441*46bfac7fb87cd43bd0ab54ebc21c120df5fab7e6f11375e79ee044e663641d5e", "myhovercraftisfullofeels"}, /* 2010-Default_myhovercraftisfullofeels_.dotx */ {"$office$*2010*100000*128*16*0907ec6ecf82ede273b7ee87e44f4ce5*d156501661638cfa3abdb7fdae05555e*4e4b64e12b23f44d9a8e2e00196e582b2da70e5e1ab4784384ad631000a5097a", "myhovercraftisfullofeels"}, /* 2010-Default_myhovercraftisfullofeels_.xlsb */ {"$office$*2010*100000*128*16*71093d08cf950f8e8397b8708de27c1f*00780eeb9605c7e27227c5619e91dc21*90aaf0ea5ccc508e699de7d62c310f94b6798ae77632be0fc1a0dc71600dac38", "myhovercraftisfullofeels"}, /* 2010-Default_myhovercraftisfullofeels_.xlsx */ {"$office$*2010*100000*128*16*71093d08cf950f8e8397b8708de27c1f*ef51883a775075f30d2207e87987e6a3*a867f87ea955d15d8cb08dc8980c04bf564f8af060ab61bf7fa3543853e0d11a", "myhovercraftisfullofeels"}, {NULL} }; static ms_office_custom_salt *cur_salt; static int *cracked, any_cracked; static char *saved_key; /* Password encoded in UCS-2 */ static int *saved_len; /* UCS-2 password length, in octets */ static char *saved_salt; static unsigned char *key; /* Output key from kernel */ static int new_keys, spincount; static struct fmt_main *self; static cl_mem cl_saved_key, cl_saved_len, cl_salt, cl_pwhash, cl_key, cl_spincount; static cl_mem pinned_saved_key, pinned_saved_len, pinned_salt, pinned_key; static cl_kernel GenerateSHA1pwhash, Generate2010key; #define HASH_LOOPS 500 /* Lower figure gives less X hogging */ #define ITERATIONS 100000 #define STEP 0 #define SEED 128 static const char * warn[] = { "xfer: ", ", xfer: ", ", init: ", ", loop: ", ", final: ", ", xfer: " }; static int split_events[] = { 3, -1, -1 }; //This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { size_t s; s = autotune_get_task_max_work_group_size(FALSE, 0, GenerateSHA1pwhash); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel)); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, Generate2010key)); return s; } static void create_clobj(size_t gws, struct fmt_main *self) { int i; int bench_len = strlen(tests[0].plaintext) * 2; gws *= ocl_v_width; pinned_saved_key = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, UNICODE_LENGTH * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating page-locked memory"); cl_saved_key = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, UNICODE_LENGTH * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device memory"); saved_key = (char*)clEnqueueMapBuffer(queue[gpu_id], pinned_saved_key, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, UNICODE_LENGTH * gws, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory saved_key"); memset(saved_key, 0, UNICODE_LENGTH * gws); pinned_saved_len = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, sizeof(cl_int) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating page-locked memory"); cl_saved_len = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, sizeof(cl_int) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device memory"); saved_len = (int*)clEnqueueMapBuffer(queue[gpu_id], pinned_saved_len, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, sizeof(cl_int) * gws, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory saved_len"); for (i = 0; i < gws; i++) saved_len[i] = bench_len; pinned_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, SALT_LENGTH, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating page-locked memory"); cl_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, SALT_LENGTH, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device memory"); saved_salt = (char*) clEnqueueMapBuffer(queue[gpu_id], pinned_salt, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, SALT_LENGTH, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory saved_salt"); memset(saved_salt, 0, SALT_LENGTH); cl_pwhash = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, sizeof(cl_uint) * 6 * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device state buffer"); pinned_key = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, 32 * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating page-locked memory"); cl_key = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, 32 * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating device memory"); key = (unsigned char*) clEnqueueMapBuffer(queue[gpu_id], pinned_key, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, 32 * gws, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory verifier keys"); memset(key, 0, 32 * gws); cl_spincount = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, sizeof(cl_int), &spincount, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping spincount"); HANDLE_CLERROR(clSetKernelArg(GenerateSHA1pwhash, 0, sizeof(cl_mem), (void*)&cl_saved_key), "Error setting argument 0"); HANDLE_CLERROR(clSetKernelArg(GenerateSHA1pwhash, 1, sizeof(cl_mem), (void*)&cl_saved_len), "Error setting argument 1"); HANDLE_CLERROR(clSetKernelArg(GenerateSHA1pwhash, 2, sizeof(cl_mem), (void*)&cl_salt), "Error setting argument 2"); HANDLE_CLERROR(clSetKernelArg(GenerateSHA1pwhash, 3, sizeof(cl_mem), (void*)&cl_pwhash), "Error setting argument 3"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(cl_mem), (void*)&cl_pwhash), "Error setting argument 0"); HANDLE_CLERROR(clSetKernelArg(Generate2010key, 0, sizeof(cl_mem), (void*)&cl_pwhash), "Error setting argument 0"); HANDLE_CLERROR(clSetKernelArg(Generate2010key, 1, sizeof(cl_mem), (void*)&cl_key), "Error setting argument 1"); HANDLE_CLERROR(clSetKernelArg(Generate2010key, 2, sizeof(cl_mem), (void*)&cl_spincount), "Error setting argument 2"); cracked = mem_alloc(sizeof(*cracked) * gws); } static void release_clobj(void) { if (cracked) { HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_key, key, 0, NULL, NULL), "Error Unmapping key"); HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_saved_key, saved_key, 0, NULL, NULL), "Error Unmapping saved_key"); HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_saved_len, saved_len, 0, NULL, NULL), "Error Unmapping saved_len"); HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_salt, saved_salt, 0, NULL, NULL), "Error Unmapping saved_salt"); HANDLE_CLERROR(clFinish(queue[gpu_id]), "Error releasing memory mappings"); HANDLE_CLERROR(clReleaseMemObject(cl_spincount), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(pinned_key), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(pinned_saved_key), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(pinned_saved_len), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(pinned_salt), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_key), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_saved_key), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_saved_len), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_salt), "Release GPU buffer"); HANDLE_CLERROR(clReleaseMemObject(cl_pwhash), "Release GPU buffer"); MEM_FREE(cracked); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(GenerateSHA1pwhash), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(Generate2010key), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void clear_keys(void) { memset(saved_key, 0, UNICODE_LENGTH * global_work_size * ocl_v_width); memset(saved_len, 0, sizeof(*saved_len) * global_work_size * ocl_v_width); } static void set_key(char *key, int index) { UTF16 *utfkey = (UTF16*)&saved_key[index * UNICODE_LENGTH]; /* convert key to UTF-16LE */ saved_len[index] = enc_to_utf16(utfkey, PLAINTEXT_LENGTH, (UTF8*)key, strlen(key)); if (saved_len[index] < 0) saved_len[index] = strlen16(utfkey); /* Prepare for GPU */ utfkey[saved_len[index]] = 0x80; saved_len[index] <<= 1; new_keys = 1; } static void set_salt(void *salt) { cur_salt = (ms_office_custom_salt *)salt; memcpy(saved_salt, cur_salt->osalt, SALT_LENGTH); spincount = cur_salt->spinCount; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], cl_salt, CL_FALSE, 0, SALT_LENGTH, saved_salt, 0, NULL, NULL), "failed in clEnqueueWriteBuffer saved_salt"); HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], cl_spincount, CL_FALSE, 0, 4, &spincount, 0, NULL, NULL), "failed in clEnqueueWriteBuffer spincount"); } static void init(struct fmt_main *_self) { static char valgo[32] = ""; self = _self; opencl_prepare_dev(gpu_id); if ((ocl_v_width = opencl_get_vector_width(gpu_id, sizeof(cl_int))) > 1) { /* Run vectorized kernel */ snprintf(valgo, sizeof(valgo), OCL_ALGORITHM_NAME " %ux" CPU_ALGORITHM_NAME, ocl_v_width); self->params.algorithm_name = valgo; } if (options.target_enc == UTF_8) self->params.plaintext_length = MIN(125, 3 * PLAINTEXT_LENGTH); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DHASH_LOOPS=%u -DUNICODE_LENGTH=%u -DV_WIDTH=%u", HASH_LOOPS, UNICODE_LENGTH, ocl_v_width); opencl_init("$JOHN/kernels/office2010_kernel.cl", gpu_id, build_opts); // create kernel to execute GenerateSHA1pwhash = clCreateKernel(program[gpu_id], "GenerateSHA1pwhash", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel. Double-check kernel name?"); crypt_kernel = clCreateKernel(program[gpu_id], "HashLoop", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel. Double-check kernel name?"); Generate2010key = clCreateKernel(program[gpu_id], "Generate2010key", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel. Double-check kernel name?"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, HASH_LOOPS, split_events, warn, 3, self, create_clobj, release_clobj, 2 * ocl_v_width * UNICODE_LENGTH, 0, db); // Auto tune execution from shared/included code. autotune_run(self, ITERATIONS + 4, 0, (cpu(device_info[gpu_id]) ? 1000000000 : 10000000000ULL)); } } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t gws, scalar_gws; size_t *lws = local_work_size ? &local_work_size : NULL; gws = GET_MULTIPLE_OR_BIGGER_VW(count, local_work_size); scalar_gws = gws * ocl_v_width; if (any_cracked) { memset(cracked, 0, count * sizeof(*cracked)); any_cracked = 0; } if (ocl_autotune_running || new_keys) { BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], cl_saved_key, CL_FALSE, 0, UNICODE_LENGTH * scalar_gws, saved_key, 0, NULL, multi_profilingEvent[0]), "failed in clEnqueueWriteBuffer saved_key"); BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], cl_saved_len, CL_FALSE, 0, sizeof(int) * scalar_gws, saved_len, 0, NULL, multi_profilingEvent[1]), "failed in clEnqueueWriteBuffer saved_len"); new_keys = 0; } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], GenerateSHA1pwhash, 1, NULL, &scalar_gws, lws, 0, NULL, multi_profilingEvent[2]), "failed in clEnqueueNDRangeKernel"); for (index = 0; index < (ocl_autotune_running ? 1 : spincount / HASH_LOOPS); index++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &gws, lws, 0, NULL, multi_profilingEvent[3]), "failed in clEnqueueNDRangeKernel"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], Generate2010key, 1, NULL, &gws, lws, 0, NULL, multi_profilingEvent[4]), "failed in clEnqueueNDRangeKernel"); // read back verifier keys BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], cl_key, CL_TRUE, 0, 32 * scalar_gws, key, 0, NULL, multi_profilingEvent[5]), "failed in reading key back"); if (!ocl_autotune_running) { #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { SHA_CTX ctx; unsigned char hash[20]; unsigned char decryptedVerifierHashInputBytes[16]; unsigned char decryptedVerifierHashBytes[32]; ms_office_common_DecryptUsingSymmetricKeyAlgorithm(cur_salt, &key[32*index], cur_salt->encryptedVerifier, decryptedVerifierHashInputBytes, 16); ms_office_common_DecryptUsingSymmetricKeyAlgorithm(cur_salt, &key[32*index+16], cur_salt->encryptedVerifierHash, decryptedVerifierHashBytes, 32); SHA1_Init(&ctx); SHA1_Update(&ctx, decryptedVerifierHashInputBytes, 16); SHA1_Final(hash, &ctx); if (!memcmp(hash, decryptedVerifierHashBytes, 20)) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } } return count; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } static char *get_key(int index) { UTF16 buf[PLAINTEXT_LENGTH + 1]; memcpy(buf, &saved_key[index * UNICODE_LENGTH], saved_len[index]); buf[saved_len[index] >> 1] = 0; return (char*)utf16_to_enc(buf); } struct fmt_main fmt_opencl_office2010 = { { 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_UNICODE | FMT_UTF8 | FMT_OMP, { "iteration count", }, { FORMAT_TAG_OFFICE_2010 }, tests }, { init, done, reset, fmt_default_prepare, ms_office_common_valid_2010, fmt_default_split, fmt_default_binary, ms_office_common_get_salt, { ms_office_common_iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
fasta.c
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // Contributed by Jeremy Zerfas // This controls the width of lines that are output by this program. #define MAXIMUM_LINE_WIDTH 60 // This program will generate the random nucleotide sequences in parallel which // are worked on in blocks of lines. The number of lines in those blocks is // controlled by this setting. #define LINES_PER_BLOCK 1024 #define CHARACTERS_PER_BLOCK (MAXIMUM_LINE_WIDTH*LINES_PER_BLOCK) // The numbers of blocks to use is controlled by this setting. This program // limits itself to using at most three threads (see explanation further below) // so similarly only three blocks are used. #define BLOCKS_TO_USE 3 #include <stdint.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #endif // intptr_t should be the native integer type on most sane systems. typedef intptr_t intnative_t; typedef struct{ char letter; float probability; } nucleotide_info; // Repeatedly print string_To_Repeat until it has printed // number_Of_Characters_To_Create. The output is also wrapped to // MAXIMUM_LINE_WIDTH columns. static void repeat_And_Wrap_String(const char string_To_Repeat[], const intnative_t number_Of_Characters_To_Create){ const intnative_t string_To_Repeat_Length=strlen(string_To_Repeat); // Create an extended_String_To_Repeat which is a copy of string_To_Repeat // but extended with another copy of the first MAXIMUM_LINE_WIDTH characters // of string_To_Repeat appended to the end. Later on this allows us to // generate a line of output just by doing simple memory copies using an // appropriate offset into extended_String_To_Repeat. char extended_String_To_Repeat[string_To_Repeat_Length+MAXIMUM_LINE_WIDTH]; for(intnative_t column=0; column<string_To_Repeat_Length+MAXIMUM_LINE_WIDTH; column++) extended_String_To_Repeat[column]= string_To_Repeat[column%string_To_Repeat_Length]; intnative_t offset=0; char line[MAXIMUM_LINE_WIDTH+1]; line[MAXIMUM_LINE_WIDTH]='\n'; for(intnative_t current_Number_Of_Characters_To_Create= number_Of_Characters_To_Create; current_Number_Of_Characters_To_Create>0;){ // Figure out the length of the line we need to write. If it's less than // MAXIMUM_LINE_WIDTH then we also need to add a line feed in the right // spot too. intnative_t line_Length=MAXIMUM_LINE_WIDTH; if(current_Number_Of_Characters_To_Create<MAXIMUM_LINE_WIDTH){ line_Length=current_Number_Of_Characters_To_Create; line[line_Length]='\n'; } memcpy(line, extended_String_To_Repeat+offset, line_Length); // Update the offset, reducing it by string_To_Repeat_Length if // necessary. offset+=line_Length; if(offset>string_To_Repeat_Length) offset-=string_To_Repeat_Length; // Output the line to stdout and update the // current_Number_Of_Characters_To_Create. fwrite(line, line_Length+1, 1, stdout); current_Number_Of_Characters_To_Create-=line_Length; } } // Generate a floating point pseudorandom number from 0.0 to max using a linear // congruential generator. #define IM 139968 #define IA 3877 #define IC 29573 uint32_t seed=42; inline float get_LCG_Pseudorandom_Number(const float max){ seed=(seed*IA + IC)%IM; return max/IM*seed; } // Output any blocks that are ready to be output. Checks the block_Statuses of // up to number_Of_Blocks starting at next_Block_To_Output. void output_Blocks(char (* const blocks)[CHARACTERS_PER_BLOCK+LINES_PER_BLOCK], intnative_t * const block_Statuses, intnative_t * const next_Block_To_Output, const intnative_t number_Of_Blocks){ // Iterate over all the blocks at the start of the circular queue which are // ready to be output. for(; block_Statuses[*next_Block_To_Output]>0; *next_Block_To_Output=(*next_Block_To_Output+1)%number_Of_Blocks){ // Iterate over each line in the next_Block_To_Output. char * line=blocks[*next_Block_To_Output]; for(intnative_t block_Characters_Left_To_Output= block_Statuses[*next_Block_To_Output]; block_Characters_Left_To_Output>0;){ // Add a line feed to the end of the line. line[MAXIMUM_LINE_WIDTH]='\n'; // Determine what the line_Length should be and if necessary add a // line feed at the end. intnative_t line_Length=MAXIMUM_LINE_WIDTH; if(block_Characters_Left_To_Output<MAXIMUM_LINE_WIDTH){ line_Length=block_Characters_Left_To_Output; line[line_Length]='\n'; } // Write one line of the block. fwrite(line, line_Length+1, 1, stdout); // Decrement block_Characters_Left_To_Output and advance to the next // line. block_Characters_Left_To_Output-=line_Length; line+=line_Length+1; } // Mark the block as unused now. block_Statuses[*next_Block_To_Output]=-1; } } // Print a pseudorandom DNA sequence that is number_Of_Characters_To_Create // characters long and made up of the nucleotides specified in // nucleotides_Information and occurring at the frequencies specified in // nucleotides_Information. The output is also wrapped to MAXIMUM_LINE_WIDTH // columns. static void generate_And_Wrap_Pseudorandom_DNA_Sequence( const nucleotide_info nucleotides_Information[], const intnative_t number_Of_Nucleotides, const intnative_t number_Of_Characters_To_Create){ // Cumulate the probabilities. Note that the probability is being multiplied // by IM because later on we'll also be calling the random number generator // with a value that is multiplied by IM. Since the random number generator // does a division by IM this allows the compiler to cancel out the // multiplication and division by IM with each other without requiring any // changes to the random number generator code whose code was explicitly // defined in the rules. float cumulative_Probabilities[number_Of_Nucleotides], cumulative_Probability=0.0; for(intnative_t i=0; i<number_Of_Nucleotides; i++){ cumulative_Probability+=nucleotides_Information[i].probability; cumulative_Probabilities[i]=cumulative_Probability*IM; } // blocks is a circular queue that stores the blocks while they are being // processed. next_Block_To_Output contains the index of the first block in // the queue which is also the next block that should be output once it is // ready. char blocks[BLOCKS_TO_USE][CHARACTERS_PER_BLOCK+LINES_PER_BLOCK]; intnative_t next_Block_To_Output=0; // block_Statuses contains a status value for each block in the circular // queue. // -A value of -1 means that block is not in use. // -A value of 0 means that block is in use and being processed. // -A positive value means that block is ready to be output and the value // is its length. intnative_t block_Statuses[BLOCKS_TO_USE]; for(intnative_t i=0; i<BLOCKS_TO_USE; block_Statuses[i++]=-1); intnative_t current_Number_Of_Characters_To_Create= number_Of_Characters_To_Create; // Limit the number_Of_Threads_To_Use to three threads since the bottleneck // for this program is the speed at which the pseudorandom generator can be // ran at which is only fast enough to keep about two other threads busy. // Using more threads will start slowing down the program due to the // overhead from additional thread management and resource usage. Using more // threads will also use more CPU time too since normally waiting OpenMP // threads will use spinlocks. #ifdef _OPENMP intnative_t number_Of_Threads_To_Use=omp_get_num_procs(); if(number_Of_Threads_To_Use>3) number_Of_Threads_To_Use=3; omp_set_num_threads(number_Of_Threads_To_Use); #endif #pragma omp parallel for schedule(guided) for(intnative_t current_Block_Number=0; current_Block_Number< (number_Of_Characters_To_Create+CHARACTERS_PER_BLOCK-1)/ CHARACTERS_PER_BLOCK; current_Block_Number++){ intnative_t block_To_Use, block_Length; float pseudorandom_Numbers[CHARACTERS_PER_BLOCK]; // Only one thread can be outputting blocks or generating pseudorandom // numbers at a time in order to ensure they are done in the correct // order. #pragma omp critical { // Find the first unused block (if any) and set that as the // block_To_Use for outputting the nucleotide sequence to. block_To_Use=next_Block_To_Output; for(intnative_t i=0; i<BLOCKS_TO_USE; i++, block_To_Use=(block_To_Use+1)%BLOCKS_TO_USE){ if(block_Statuses[block_To_Use]==-1) break; } // If no unused block was found then block_To_Use will be restored // to next_Block_To_Output and we will have to wait for it to finish // processing, output that block, and then use that block. while(block_Statuses[block_To_Use]==0){ #pragma omp flush(block_Statuses) } // Output any blocks that are ready to be output. output_Blocks(blocks, block_Statuses, &next_Block_To_Output, BLOCKS_TO_USE); // Update the status for block_To_Use to reflect that it is now // being processed. block_Statuses[block_To_Use]++; // Figure out what the block_Length should be and decrement // current_Number_Of_Characters_To_Create by that amount. block_Length=CHARACTERS_PER_BLOCK; if(current_Number_Of_Characters_To_Create<CHARACTERS_PER_BLOCK) block_Length=current_Number_Of_Characters_To_Create; current_Number_Of_Characters_To_Create-=block_Length; // Get the pseudorandom_Numbers to use for this block. for(intnative_t pseudorandom_Number_Index=0; pseudorandom_Number_Index<block_Length; pseudorandom_Numbers[pseudorandom_Number_Index++]= get_LCG_Pseudorandom_Number(IM)); } // Start processing the pseudorandom_Numbers and generate the // corresponding block of nucleotides that will be output later by // filling block_To_Use with characters from nucleotides_Information[] // that are selected by looking up the pseudorandom number. char * line=blocks[block_To_Use]; for(intnative_t column=0, pseudorandom_Number_Index=0; pseudorandom_Number_Index<block_Length; pseudorandom_Number_Index++){ const float r=pseudorandom_Numbers[pseudorandom_Number_Index]; // Count the number of nucleotides with a probability less than what // was selected by the random number generator and then use that // count as an index for the nucleotide to select. It's arguable // whether this qualifies as a linear search but I guess you can say // that you're doing a linear search for all the nucleotides with a // probability less than what was selected by the random number // generator and then just counting how many matches were found. // With a small number of nucleotides this can be faster than doing // a more normal linear search (although in some cases it may // generate different results) and a couple of the other programs // already do this as well so we will too. intnative_t count=0; for(intnative_t i=0; i<number_Of_Nucleotides; i++) if(cumulative_Probabilities[i]<=r) count++; line[column]=nucleotides_Information[count].letter; // If we reach the end of the line, reset the column counter and // advance to the next line. if(++column==MAXIMUM_LINE_WIDTH){ column=0; line+=MAXIMUM_LINE_WIDTH+1; } } // Update the block_Statuses so that this block_To_Use gets output // later. block_Statuses[block_To_Use]=block_Length; } // Output the remaining blocks. output_Blocks(blocks, block_Statuses, &next_Block_To_Output, BLOCKS_TO_USE); } int main(int argc, char ** argv){ const intnative_t n=atoi(argv[1]); fputs(">ONE Homo sapiens alu\n", stdout); const char homo_Sapiens_Alu[]= "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTC" "AGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCG" "TGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGG" "AGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"; repeat_And_Wrap_String(homo_Sapiens_Alu, 2*n); fputs(">TWO IUB ambiguity codes\n", stdout); nucleotide_info iub_Nucleotides_Information[]={ {'a', 0.27}, {'c', 0.12}, {'g', 0.12}, {'t', 0.27}, {'B', 0.02}, {'D', 0.02}, {'H', 0.02}, {'K', 0.02}, {'M', 0.02}, {'N', 0.02}, {'R', 0.02}, {'S', 0.02}, {'V', 0.02}, {'W', 0.02}, {'Y', 0.02}}; generate_And_Wrap_Pseudorandom_DNA_Sequence(iub_Nucleotides_Information, sizeof(iub_Nucleotides_Information)/sizeof(nucleotide_info), 3*n); fputs(">THREE Homo sapiens frequency\n", stdout); nucleotide_info homo_Sapien_Nucleotides_Information[]={ {'a', 0.3029549426680}, {'c', 0.1979883004921}, {'g', 0.1975473066391}, {'t', 0.3015094502008}}; generate_And_Wrap_Pseudorandom_DNA_Sequence( homo_Sapien_Nucleotides_Information, sizeof(homo_Sapien_Nucleotides_Information)/sizeof(nucleotide_info), 5*n); return 0; }
DRB100-task-reference-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Cover the implicitly determined rule: In an orphaned task generating construct, * formal arguments passed by reference are firstprivate. * This requires OpenMP 4.5 to work. * Earlier OpenMP does not allow a reference type for a variable within firstprivate(). * */ #include <stdio.h> #define MYLEN 100 int a[MYLEN]; void gen_task(int i) { a[i]= i+1; } int main() { int i=0; #pragma omp parallel { #pragma omp for private(i) for (i=0; i<MYLEN; i++) { gen_task(i); } } /* correctness checking */ for (i=0; i<MYLEN; i++) { //assert (a[i]==i+1); if (a[i]!= i+1) { printf("warning: a[%d] = %d, not expected %d\n", i, a[i], i+1); } } return 0; }
fields_modifiers.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #define XSTR(x) #x #define STR(x) XSTR(x) #define streqls(s1, s2) (!strcmp(s1, s2)) #define check(condition) \ if (!(condition)) { \ fprintf(stderr, "error: %s: %d: " STR(condition) "\n", __FILE__, \ __LINE__); \ exit(1); \ } #define BUFFER_SIZE 1024 char buf[BUFFER_SIZE]; #pragma omp threadprivate(buf) char* get_string(size_t check_needed) { size_t needed = omp_capture_affinity(buf, BUFFER_SIZE, NULL); //printf("buf = %s\n", buf); check(needed < BUFFER_SIZE); if (check_needed != 0) { check(needed == check_needed); } return buf; } void check_thread_num_padded_rjustified() { int i; const char* formats[2] = {"%0.8{thread_num}", "%0.8n"}; for (i = 0; i < sizeof(formats)/sizeof(formats[0]); ++i) { omp_set_affinity_format(formats[i]); #pragma omp parallel num_threads(8) { int j; int tid = omp_get_thread_num(); char ctid = '0' + (char)tid; char* s = get_string(8); for (j = 0; j < 7; ++j) { check(s[j] == '0'); } check(s[j] == ctid); } } } void check_thread_num_rjustified() { int i; const char* formats[2] = {"%.12{thread_num}", "%.12n"}; for (i = 0; i < sizeof(formats)/sizeof(formats[0]); ++i) { omp_set_affinity_format(formats[i]); #pragma omp parallel num_threads(8) { int j; int tid = omp_get_thread_num(); char ctid = '0' + (char)tid; char* s = get_string(12); for (j = 0; j < 11; ++j) { check(s[j] == ' '); } check(s[j] == ctid); } } } void check_thread_num_ljustified() { int i; const char* formats[2] = {"%5{thread_num}", "%5n"}; for (i = 0; i < sizeof(formats)/sizeof(formats[0]); ++i) { omp_set_affinity_format(formats[i]); #pragma omp parallel num_threads(8) { int j; int tid = omp_get_thread_num(); char ctid = '0' + (char)tid; char* s = get_string(5); check(s[0] == ctid); for (j = 1; j < 5; ++j) { check(s[j] == ' '); } } } } void check_thread_num_padded_ljustified() { int i; const char* formats[2] = {"%018{thread_num}", "%018n"}; for (i = 0; i < sizeof(formats)/sizeof(formats[0]); ++i) { omp_set_affinity_format(formats[i]); #pragma omp parallel num_threads(8) { int j; int tid = omp_get_thread_num(); char ctid = '0' + (char)tid; char* s = get_string(18); check(s[0] == ctid); for (j = 1; j < 18; ++j) { check(s[j] == ' '); } } } } int main(int argc, char** argv) { check_thread_num_ljustified(); check_thread_num_rjustified(); check_thread_num_padded_ljustified(); check_thread_num_padded_rjustified(); return 0; }
ParallelOpenMP.h
#pragma once #include <cstddef> #include <exception> #ifdef _OPENMP #define INTRA_OP_PARALLEL #include <omp.h> #endif namespace at { template <class F> inline void parallel_for( const int64_t begin, const int64_t end, const int64_t grain_size, const F& f) { TORCH_CHECK(grain_size >= 0); at::internal::lazy_init_num_threads(); if (begin >= end) { return; } if (end - begin == 1) { f(begin, end); return; } #ifdef _OPENMP std::atomic_flag err_flag = ATOMIC_FLAG_INIT; std::exception_ptr eptr; // Work around memory leak when using 1 thread in nested "omp parallel" // caused by some buggy OpenMP versions and the fact that omp_in_parallel() // returns false when omp_get_max_threads() == 1 inside nested "omp parallel" // See issue gh-32284 #pragma omp parallel if (omp_get_max_threads() > 1 && !omp_in_parallel() && ((end - begin) > grain_size)) { // choose number of tasks based on grain size and number of threads // can't use num_threads clause due to bugs in GOMP's thread pool (See #32008) int64_t num_threads = omp_get_num_threads(); if (grain_size > 0) { num_threads = std::min(num_threads, divup((end - begin), grain_size)); } int64_t tid = omp_get_thread_num(); int64_t chunk_size = divup((end - begin), num_threads); int64_t begin_tid = begin + tid * chunk_size; if (begin_tid < end) { try { f(begin_tid, std::min(end, chunk_size + begin_tid)); } catch (...) { if (!err_flag.test_and_set()) { eptr = std::current_exception(); } } } } if (eptr) { std::rethrow_exception(eptr); } #else f(begin, end); #endif } template <class scalar_t, class F, class SF> inline scalar_t parallel_reduce( const int64_t begin, const int64_t end, const int64_t grain_size, const scalar_t ident, const F& f, const SF& sf) { TORCH_CHECK(grain_size >= 0); at::internal::lazy_init_num_threads(); if (begin >= end) { return ident; } else if (in_parallel_region() || get_num_threads() == 1) { return f(begin, end, ident); } else { const int64_t num_results = divup((end - begin), grain_size); std::vector<scalar_t> results(num_results); scalar_t* results_data = results.data(); std::atomic_flag err_flag = ATOMIC_FLAG_INIT; std::exception_ptr eptr; #pragma omp parallel for if ((end - begin) >= grain_size) for (int64_t id = 0; id < num_results; id++) { int64_t i = begin + id * grain_size; try { results_data[id] = f(i, i + std::min(end - i, grain_size), ident); } catch (...) { if (!err_flag.test_and_set()) { eptr = std::current_exception(); } } } if (eptr) { std::rethrow_exception(eptr); } scalar_t result = ident; for (auto partial_result : results) { result = sf(result, partial_result); } return result; } } } // namespace at
pclansy.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/pzlansy.c, normal z -> c, Fri Sep 28 17:38:13 2018 * **/ #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" #include "plasma_workspace.h" #include <plasma_core_blas.h> #define A(m, n) (plasma_complex32_t*)plasma_tile_addr(A, m, n) /***************************************************************************//** * Parallel tile calculation of max, one, infinity or Frobenius matrix norm * for a symmetric matrix. ******************************************************************************/ void plasma_pclansy(plasma_enum_t norm, plasma_enum_t uplo, plasma_desc_t A, float *work, float *value, plasma_sequence_t *sequence, plasma_request_t *request) { // Return if failed sequence. if (sequence->status != PlasmaSuccess) return; switch (norm) { float stub; float *workspace; float *scale; float *sumsq; //================ // PlasmaMaxNorm //================ case PlasmaMaxNorm: for (int m = 0; m < A.mt; m++) { int mvam = plasma_tile_mview(A, m); int ldam = plasma_tile_mmain(A, m); if (uplo == PlasmaLower) { for (int n = 0; n < m; n++) { int nvan = plasma_tile_nview(A, n); plasma_core_omp_clange(PlasmaMaxNorm, mvam, nvan, A(m, n), ldam, &stub, &work[A.mt*n+m], sequence, request); } } else { // PlasmaUpper for (int n = m+1; n < A.nt; n++) { int nvan = plasma_tile_nview(A, n); plasma_core_omp_clange(PlasmaMaxNorm, mvam, nvan, A(m, n), ldam, &stub, &work[A.mt*n+m], sequence, request); } } plasma_core_omp_clansy(PlasmaMaxNorm, uplo, mvam, A(m, m), ldam, &stub, &work[A.mt*m+m], sequence, request); } #pragma omp taskwait plasma_core_omp_slansy(PlasmaMaxNorm, uplo, A.nt, work, A.mt, &stub, value, sequence, request); break; //================ // PlasmaOneNorm //================ case PlasmaOneNorm: case PlasmaInfNorm: for (int m = 0; m < A.mt; m++) { int mvam = plasma_tile_mview(A, m); int ldam = plasma_tile_mmain(A, m); if (uplo == PlasmaLower) { for (int n = 0; n < m; n++) { int nvan = plasma_tile_nview(A, n); plasma_core_omp_clange_aux(PlasmaOneNorm, mvam, nvan, A(m, n), ldam, &work[A.n*m+n*A.nb], sequence, request); plasma_core_omp_clange_aux(PlasmaInfNorm, mvam, nvan, A(m, n), ldam, &work[A.n*n+m*A.nb], sequence, request); } } else { // PlasmaUpper for (int n = m+1; n < A.nt; n++) { int nvan = plasma_tile_nview(A, n); plasma_core_omp_clange_aux(PlasmaOneNorm, mvam, nvan, A(m, n), ldam, &work[A.n*m+n*A.nb], sequence, request); plasma_core_omp_clange_aux(PlasmaInfNorm, mvam, nvan, A(m, n), ldam, &work[A.n*n+m*A.nb], sequence, request); } } plasma_core_omp_clansy_aux(PlasmaOneNorm, uplo, mvam, A(m, m), ldam, &work[A.n*m+m*A.nb], sequence, request); } #pragma omp taskwait workspace = work + A.mt*A.n; plasma_core_omp_slange(PlasmaInfNorm, A.n, A.mt, work, A.n, workspace, value, sequence, request); break; //====================== // PlasmaFrobeniusNorm //====================== case PlasmaFrobeniusNorm: scale = work; sumsq = work + A.mt*A.nt; for (int m = 0; m < A.mt; m++) { int mvam = plasma_tile_mview(A, m); int ldam = plasma_tile_mmain(A, m); if (uplo == PlasmaLower) { for (int n = 0; n < m; n++) { int nvan = plasma_tile_nview(A, n); plasma_core_omp_cgessq(mvam, nvan, A(m, n), ldam, &scale[A.mt*n+m], &sumsq[A.mt*n+m], sequence, request); } } else { // PlasmaUpper for (int n = m+1; n < A.nt; n++) { int nvan = plasma_tile_nview(A, n); plasma_core_omp_cgessq(mvam, nvan, A(m, n), ldam, &scale[A.mt*m+n], &sumsq[A.mt*m+n], sequence, request); } } plasma_core_omp_csyssq(uplo, mvam, A(m, m), ldam, &scale[A.mt*m+m], &sumsq[A.mt*m+m], sequence, request); } #pragma omp taskwait plasma_core_omp_ssyssq_aux(A.mt, A.nt, scale, sumsq, value, sequence, request); break; } }
GB_unop__ceil_fc64_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 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__ceil_fc64_fc64) // op(A') function: GB (_unop_tran__ceil_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = GB_cceil (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_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 = GB_cceil (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = 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_FC64_t z = aij ; \ Cx [pC] = GB_cceil (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_CEIL || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__ceil_fc64_fc64) ( GxB_FC64_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_FC64_t z = aij ; Cx [p] = GB_cceil (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_FC64_t z = aij ; Cx [p] = GB_cceil (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__ceil_fc64_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
kernel_mergeSortPass.h
#pragma omp target teams distribute parallel for num_teams(grid[0]) thread_limit(local[0]) for (int gid = 0; gid < global[0]; gid++) { // The division to work on int division = gid / threadsPerDiv; if(division < DIVISIONS) { // The block within the division int int_gid = gid - division * threadsPerDiv; int Astart = startaddr[division] + int_gid * nrElems; int Bstart = Astart + nrElems/2; //global float4 *resStart; float4* resStart= &(d_resultList[Astart]); if(Astart < startaddr[division + 1]) { if(Bstart >= startaddr[division + 1]){ for(int i=0; i<(startaddr[division + 1] - Astart); i++) { resStart[i] = d_origList[Astart + i]; } } else { int aidx = 0; int bidx = 0; int outidx = 0; float4 a, b; float4 zero = {0.f, 0.f, 0.f, 0.f}; a = d_origList[Astart + aidx]; b = d_origList[Bstart + bidx]; while(true) { /** * For some reason, it's faster to do the texture fetches here than * after the merge */ float4 nextA = d_origList[Astart + aidx + 1]; float4 nextB = (Bstart + bidx + 1 >= listsize/4) ? zero : d_origList[Bstart + bidx + 1]; float4 na = getLowest(a,b); float4 nb = getHighest(a,b); a = sortElem(na); b = sortElem(nb); // Now, a contains the lowest four elements, sorted resStart[outidx++] = a; bool elemsLeftInA; bool elemsLeftInB; elemsLeftInA = (aidx + 1 < nrElems/2); // Astart + aidx + 1 is allways less than division border elemsLeftInB = (bidx + 1 < nrElems/2) && (Bstart + bidx + 1 < startaddr[division + 1]); if(elemsLeftInA){ if(elemsLeftInB){ float nextA_t = nextA.x; float nextB_t = nextB.x; if(nextA_t < nextB_t) { aidx += 1; a = nextA; } else { bidx += 1; a = nextB; } } else { aidx += 1; a = nextA; } } else { if(elemsLeftInB){ bidx += 1; a = nextB; } else { break; } } } resStart[outidx++] = b; } } } }
pure_convection_edgebased.h
/* ============================================================================== KratosPFEMApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi pooyan@cimne.upc.edu rrossi@cimne.upc.edu - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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. ============================================================================== */ // // Project Name: Kratos // Last Modified by: $Author: rrossi $ // Date: $Date: 2009-01-13 15:39:56 $ // Revision: $Revision: 1.3 $ // // #if !defined(KRATOS_PURE_CONVECTION_EDGEBASED_SOLVER_H_INCLUDED) #define KRATOS_PURE_CONVECTION_EDGEBASED_SOLVER_H_INCLUDED #define SPLIT_OSS // #define SYMM_PRESS // System includes #include <string> #include <iostream> #include <algorithm> // #include <omp.h> // External includes // Project includes #include "includes/define.h" #include "includes/model_part.h" #include "includes/node.h" //#include "geometries/geometry.h" #include "utilities/geometry_utilities.h" #include "incompressible_fluid_application.h" namespace Kratos { template<unsigned int TDim, class MatrixContainer, class TSparseSpace, class TLinearSolver> class PureConvectionEdgeBased { public: //name for the self defined structure typedef EdgesStructureType<TDim> CSR_Tuple; typedef std::vector<CSR_Tuple> EdgesVectorType; //name for row start and column index vectors typedef vector<unsigned int> IndicesVectorType; //defining matrix type for test calculations typedef vector< array_1d<double, TDim> > CalcVectorType; //defining type for local storage of nodal values typedef vector<double> ValuesVectorType; //defining types for matrix operations typedef typename TSparseSpace::MatrixType TSystemMatrixType; typedef typename TSparseSpace::VectorType TSystemVectorType; //constructor and destructor PureConvectionEdgeBased(MatrixContainer& mr_matrix_container, ModelPart& mr_model_part ) : mr_matrix_container(mr_matrix_container),mr_model_part(mr_model_part) {}; ~PureConvectionEdgeBased() {}; //*********************************** //function to initialize fluid solver void Initialize( ) { KRATOS_TRY //get number of nodes unsigned int n_nodes = mr_model_part.Nodes().size(); //unsigned int n_edges = mr_matrix_container.GetNumberEdges(); //size data vectors mWork.resize(n_nodes); mPi.resize(n_nodes); mUn.resize(n_nodes); mUn1.resize(n_nodes); mphi_n.resize(n_nodes); mphi_n1.resize(n_nodes); mA.resize(n_nodes); mHmin.resize(n_nodes); mTau.resize(n_nodes); mBeta.resize(n_nodes); mx.resize(n_nodes); //read variables from Kratos mr_matrix_container.FillVectorFromDatabase(VELOCITY, mUn1, mr_model_part.Nodes()); mr_matrix_container.FillOldVectorFromDatabase(VELOCITY, mUn, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(DISTANCE, mphi_n1, mr_model_part.Nodes()); mr_matrix_container.FillOldScalarFromDatabase(DISTANCE, mphi_n, mr_model_part.Nodes()); mr_matrix_container.FillCoordinatesFromDatabase(mx, mr_model_part.Nodes()); //set flag for first time step mFirstStep = true; ValuesVectorType& aaa = mr_matrix_container.GetHmin(); for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { mHmin[i_node] = aaa[i_node]; } KRATOS_CATCH("") } //*************************************** //function to set adequate time step size void ComputeTimeStep(double CFLNumber) { KRATOS_TRY //local variable for time step size double delta_t = 1e10; //getting value of current velocity mr_matrix_container.FillVectorFromDatabase(VELOCITY, mUn1, mr_model_part.Nodes()); //loop over all nodes double n_nodes = mUn1.size(); for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { //use CFL condition to compute time step size double delta_t_i = CFLNumber * mHmin[i_node] / norm_2(mUn1[i_node] ) ; //choose the overall minimum of delta_t_i if (delta_t_i < delta_t) delta_t = delta_t_i; } //perform MPI syncronization of the dt (minimum should be kept) //write time step size to Kratos ProcessInfo& CurrentProcessInfo = mr_model_part.GetProcessInfo(); CurrentProcessInfo[DELTA_TIME] = delta_t; KRATOS_CATCH("") } //********************************************************************************** //function to solve fluid equations - fractional step 1: compute fractional momentum void Solve() { KRATOS_TRY //PREREQUISITES //variables for node based data handling ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); int n_nodes = rNodes.size(); //storage of nodal values in local variables ValuesVectorType rhs; rhs.resize(n_nodes); //read variables from Kratos mr_matrix_container.FillVectorFromDatabase(VELOCITY, mUn1, mr_model_part.Nodes()); mr_matrix_container.FillOldVectorFromDatabase(VELOCITY, mUn, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(DISTANCE, mphi_n1, mr_model_part.Nodes()); mr_matrix_container.FillOldScalarFromDatabase(DISTANCE, mphi_n, mr_model_part.Nodes()); //read time step size from Kratos ProcessInfo& CurrentProcessInfo = mr_model_part.GetProcessInfo(); double delta_t = CurrentProcessInfo[DELTA_TIME]; //compute advective velocity - area average of the current velocity double coefficient = 1; CalculateAdvectiveVelocity(mUn,mUn1,mA, coefficient); //compute intrinsic time double time_inv = 1.0/delta_t; #pragma omp parallel for firstprivate(time_inv) for (int i_node = 0; i_node < n_nodes; i_node++) { double& h_i = mHmin[i_node]; array_1d<double, TDim>& a_i = mA[i_node]; double vel_norm = norm_2(a_i); mTau[i_node] = 1.0 / (2.0 * vel_norm/h_i + 0.01*time_inv ); } mr_matrix_container.AssignVectorToVector(mphi_n, mWork); //mWork = mphi_n //first step of Runge Kutta // mr_matrix_container.AssignVectorToVector(mphi_n,mphi_n1); //mphi_n1 = mphi_n mr_matrix_container.SetToZero(rhs); CalculateRHS( mphi_n1,mA,rhs); mr_matrix_container.Add_Minv_value(mWork,mWork, delta_t/6.0 , mr_matrix_container.GetInvertedMass(), rhs); mr_matrix_container.Add_Minv_value(mphi_n1, mphi_n, 0.5*delta_t , mr_matrix_container.GetInvertedMass(), rhs); //second step mr_matrix_container.SetToZero(rhs); CalculateRHS(mphi_n1,mA,rhs); mr_matrix_container.Add_Minv_value(mWork,mWork, delta_t/3.0 , mr_matrix_container.GetInvertedMass(), rhs); mr_matrix_container.Add_Minv_value(mphi_n1, mphi_n, 0.5*delta_t , mr_matrix_container.GetInvertedMass(),rhs); //third step CalculateAdvectiveVelocity(mUn, mUn1,mA, coefficient); mr_matrix_container.SetToZero(rhs); CalculateRHS( mphi_n1,mA,rhs); mr_matrix_container.Add_Minv_value(mWork,mWork, delta_t/3.0 , mr_matrix_container.GetInvertedMass(), rhs); mr_matrix_container.Add_Minv_value(mphi_n1, mphi_n, delta_t , mr_matrix_container.GetInvertedMass(), rhs); //fourth step CalculateAdvectiveVelocity(mUn, mUn1,mA, coefficient); mr_matrix_container.SetToZero(rhs); CalculateRHS( mphi_n1,mA,rhs ); mr_matrix_container.Add_Minv_value(mWork,mWork, delta_t/6.0 , mr_matrix_container.GetInvertedMass(), rhs); //compute right-hand side mr_matrix_container.AssignVectorToVector(mWork,mphi_n1); mr_matrix_container.WriteScalarToDatabase(DISTANCE, mphi_n1, mr_model_part.Nodes()); KRATOS_CATCH("") } //********************************************************************* //function to calculate right-hand side of fractional momentum equation void CalculateRHS( const ValuesVectorType& mphi, const CalcVectorType& convective_velocity, ValuesVectorType& rhs) { KRATOS_TRY int n_nodes = mphi.size(); //calculating the convective projection #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) { array_1d<double, TDim>& pi_i = mPi[i_node]; //setting to zero the projection for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) pi_i[l_comp] = 0.0; // double& pi_i = mPi[i_node]; const double& phi_i = mphi[i_node]; const array_1d<double, TDim> a_i = convective_velocity[i_node]; //loop to all the edges surrounding node I for (unsigned int csr_index=mr_matrix_container.GetRowStartIndex()[i_node]; csr_index!=mr_matrix_container.GetRowStartIndex()[i_node+1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // const array_1d<double, TDim>& a_j = convective_velocity[j_neighbour]; const double& phi_j = mphi[j_neighbour]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; // edge_ij.Add_ConvectiveContribution(pi_i,a_i,phi_i,a_j,phi_j); edge_ij.Add_grad_p(pi_i,phi_i,phi_j); } //apply inverted mass matrix const double m_inv = mr_matrix_container.GetInvertedMass()[i_node]; // pi_i *= m_inv; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) pi_i[l_comp] *= m_inv; // KRATOS_WATCH(pi_i); } //calculating limitor array_1d<double, TDim> dir; #pragma omp parallel for private(dir) for (int i_node = 0; i_node < n_nodes; i_node++) { const array_1d<double, TDim>& x_i = mx[i_node]; const array_1d<double, TDim>& proj_i = mPi[i_node]; const double& p_i = mphi[i_node]; double& beta_i = mBeta[i_node]; beta_i = 0.0; double n = 0.0; double h=0.0; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; const double& p_j = mphi[j_neighbour]; const array_1d<double, TDim>& x_j = mx[j_neighbour]; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) dir[l_comp] = x_j[l_comp] - x_i[l_comp]; double lenght = dir[0]*dir[0]; for (unsigned int l_comp = 1; l_comp < TDim; l_comp++) lenght += dir[l_comp]*dir[l_comp]; lenght = sqrt(lenght); const array_1d<double, TDim>& proj_j = mPi[j_neighbour]; double proj = 0.0; for (unsigned int comp = 0; comp < TDim; comp++) proj += 0.5*dir[comp]*(proj_i[comp]+proj_j[comp]); // proj += dir[comp]*pi_i[comp]; double numerator = fabs( fabs(p_j - p_i) - fabs(proj) ); double denom = fabs( fabs(p_j - p_i) + 1e-6); double beta = numerator/denom; beta_i += beta; n += 1.0; h += lenght; /* if(beta_i < beta) beta_i = beta;*/ } beta_i /= n; h /=n; if(beta_i > 1.0) beta_i = 1.0; beta_i*=h; // KRATOS_WATCH(beta_i); } //perform MPI syncronization //calculating the RHS double stab_low; double stab_high; array_1d<double, TDim> aux; #pragma omp parallel for private(stab_low,stab_high,aux) for ( int i_node = 0; i_node < n_nodes; i_node++) { double& rhs_i = rhs[i_node]; const double& phi_i = mphi[i_node]; const double& beta_i = mBeta[i_node]; const array_1d<double, TDim>& a_i = convective_velocity[i_node]; const array_1d<double, TDim>& proj_i = mPi[i_node]; // const array_1d<double, TDim>& x_i = mx[i_node]; double pi_i = proj_i[0]*a_i[0]; for (unsigned int l_comp = 1; l_comp < TDim; l_comp++) pi_i += proj_i[l_comp]*a_i[l_comp]; //double& h_i = mHmin[i_node]; double norm_a = a_i[0]*a_i[0]; for (unsigned int l_comp = 1; l_comp < TDim; l_comp++) norm_a += a_i[l_comp]*a_i[l_comp]; norm_a = sqrt(norm_a); //initializing with the external forces (e.g. gravity) rhs_i = 0.0; //loop to all the edges surrounding node I for (unsigned int csr_index=mr_matrix_container.GetRowStartIndex()[i_node]; csr_index!=mr_matrix_container.GetRowStartIndex()[i_node+1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // const array_1d<double, TDim>& x_j = mx[j_neighbour]; //double& rhs_j = rhs[j_neighbour]; const double& phi_j = mphi[j_neighbour]; const array_1d<double, TDim>& a_j = convective_velocity[j_neighbour]; const array_1d<double, TDim>& proj_j = mPi[j_neighbour]; double pi_j = proj_j[0]*a_i[0]; for (unsigned int l_comp = 1; l_comp < TDim; l_comp++) pi_j += proj_j[l_comp]*a_i[l_comp]; //double& h_j = mHmin[j_neighbour]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; //convection operator edge_ij.Sub_ConvectiveContribution(rhs_i,a_i,phi_i,a_j,phi_j); //calculate stabilization part edge_ij.CalculateConvectionStabilization_LOW( stab_low,a_i,phi_i,a_j,phi_j); double edge_tau = mTau[i_node]; edge_ij.CalculateConvectionStabilization_HIGH( stab_high,a_i,pi_i,a_j,pi_j); edge_ij.Sub_StabContribution( rhs_i, edge_tau, 1.0, stab_low, stab_high); /* double laplacian_ij=0.0; edge_ij.CalculateScalarLaplacian( laplacian_ij ); double capturing= laplacian_ij * (phi_j - phi_i); rhs_i-= 0.1*0.5*capturing*beta_i*norm_a*mHmin[i_node];*/ // for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) // dir[l_comp] = x_j[l_comp] - x_i[l_comp]; // // double proj = 0.0; // for (unsigned int comp = 0; comp < TDim; comp++) // proj += 0.5*dir[comp]*(proj_i[comp]+proj_j[comp]); // // proj += dir[comp]*proj_i[comp]; // // double numerator = fabs( fabs(pi_j - pi_i) - fabs(proj) ); // double denom = fabs( fabs(pi_j - pi_i) + fabs(proj) + 1e-6); // // double beta = numerator/denom; // // if(beta > 1.0) // beta = 1.0; double beta = beta_i; double coeff = 0.35; //=0.5*0.5; double laplacian_ij=0.0; edge_ij.CalculateScalarLaplacian( laplacian_ij ); double capturing= laplacian_ij * (phi_j - phi_i); // rhs_i-= coeff*capturing*beta*norm_a; double aaa = 0.0; for (unsigned int k_comp = 0; k_comp < TDim; k_comp++) for (unsigned int m_comp = 0; m_comp < TDim; m_comp++) aaa += a_i[k_comp] * a_i[m_comp] * edge_ij.LaplacianIJ(k_comp,m_comp); if(norm_a > 1e-20) aaa/=(norm_a*norm_a); double capturing2 = aaa * (phi_j - phi_i); // rhs_i-= coeff*(capturing - capturing2)*beta*norm_a; // } // KRATOS_WATCH(rhs_i); } KRATOS_CATCH("") } void CalculateAdvectiveVelocity( const CalcVectorType& mUn, const CalcVectorType& mUn1, CalcVectorType& mA, double coefficient) { int n_nodes = mUn1.size(); #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) { //reference for advective velocity of node i array_1d<double, TDim>& a_i = mA[i_node]; const array_1d<double, TDim>& Un_i = mUn[i_node]; const array_1d<double, TDim>& Un1_i = mUn1[i_node]; for (unsigned int k_comp = 0; k_comp < TDim; k_comp++) a_i[k_comp] = coefficient * Un1_i[k_comp] + (1.0 - coefficient)* Un_i[k_comp]; } } //******************************* //function to free dynamic memory void Clear() { KRATOS_TRY mWork.clear(); mPi.clear(); mUn.clear(); mUn1.clear(); mA.clear(); mphi_n.clear(); mphi_n1.clear(); mHmin.clear(); mTau.clear(); mBeta.clear(); mx.clear(); KRATOS_CATCH("") } private: MatrixContainer& mr_matrix_container; ModelPart& mr_model_part; bool msmooth_convective_velocity; bool minclude_shock_capturing; //nodal values //velocity vector U at time steps n and n+1 CalcVectorType mUn1,mUn; CalcVectorType mPi; //pressure vector p at time steps n and n+1 CalcVectorType mx; ValuesVectorType mBeta; ValuesVectorType mWork; ValuesVectorType mphi_n, mphi_n1; //variable to be convected //advective velocity vector CalcVectorType mA; //minimum length of the edges surrounding edges surrounding each nodal point ValuesVectorType mHmin; //flag for first time step bool mFirstStep; //intrinsic time step size ValuesVectorType mTau; }; } //namespace Kratos #endif //KRATOS_PURE_CONVECTION_EDGEBASED_SOLVER_H_INCLUDED defined
task_target_device_codegen.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex "__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" "pl_cond[ .].+[.|,]" --prefix-filecheck-ir-name _ // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -fopenmp-version=50 -x c -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp-simd -fopenmp-version=50 -x c -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s // RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s // SIMD-ONLY0-NOT: {{__kmpc|__tgt}} // expected-no-diagnostics #ifndef HEADER #define HEADER void test_task_affinity() { int t; #pragma omp task { #pragma omp target device(t) ; } } #endif // CHECK-LABEL: define {{[^@]+}}@test_task_affinity // CHECK-SAME: () #[[ATTR0:[0-9]+]] { // CHECK-NEXT: entry: // CHECK-NEXT: [[T:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[AGG_CAPTURED:%.*]] = alloca [[STRUCT_ANON:%.*]], align 1 // CHECK-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]]) // CHECK-NEXT: [[TMP1:%.*]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* @[[GLOB1]], i32 [[TMP0]], i32 1, i64 48, i64 0, i32 (i32, i8*)* bitcast (i32 (i32, %struct.kmp_task_t_with_privates*)* @.omp_task_entry. to i32 (i32, i8*)*)) // CHECK-NEXT: [[TMP2:%.*]] = bitcast i8* [[TMP1]] to %struct.kmp_task_t_with_privates* // CHECK-NEXT: [[TMP3:%.*]] = getelementptr inbounds [[STRUCT_KMP_TASK_T_WITH_PRIVATES:%.*]], %struct.kmp_task_t_with_privates* [[TMP2]], i32 0, i32 0 // CHECK-NEXT: [[TMP4:%.*]] = getelementptr inbounds [[STRUCT_KMP_TASK_T_WITH_PRIVATES]], %struct.kmp_task_t_with_privates* [[TMP2]], i32 0, i32 1 // CHECK-NEXT: [[TMP5:%.*]] = getelementptr inbounds [[STRUCT__KMP_PRIVATES_T:%.*]], %struct..kmp_privates.t* [[TMP4]], i32 0, i32 0 // CHECK-NEXT: [[TMP6:%.*]] = load i32, i32* [[T]], align 4 // CHECK-NEXT: store i32 [[TMP6]], i32* [[TMP5]], align 8 // CHECK-NEXT: [[TMP7:%.*]] = call i32 @__kmpc_omp_task(%struct.ident_t* @[[GLOB1]], i32 [[TMP0]], i8* [[TMP1]]) // CHECK-NEXT: ret void // // // CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_test_task_affinity_l18 // CHECK-SAME: () #[[ATTR1:[0-9]+]] { // CHECK-NEXT: entry: // CHECK-NEXT: ret void // // // CHECK-LABEL: define {{[^@]+}}@.omp_task_privates_map. // CHECK-SAME: (%struct..kmp_privates.t* noalias [[TMP0:%.*]], i32** noalias [[TMP1:%.*]]) #[[ATTR2:[0-9]+]] { // CHECK-NEXT: entry: // CHECK-NEXT: [[DOTADDR:%.*]] = alloca %struct..kmp_privates.t*, align 8 // CHECK-NEXT: [[DOTADDR1:%.*]] = alloca i32**, align 8 // CHECK-NEXT: store %struct..kmp_privates.t* [[TMP0]], %struct..kmp_privates.t** [[DOTADDR]], align 8 // CHECK-NEXT: store i32** [[TMP1]], i32*** [[DOTADDR1]], align 8 // CHECK-NEXT: [[TMP2:%.*]] = load %struct..kmp_privates.t*, %struct..kmp_privates.t** [[DOTADDR]], align 8 // CHECK-NEXT: [[TMP3:%.*]] = getelementptr inbounds [[STRUCT__KMP_PRIVATES_T:%.*]], %struct..kmp_privates.t* [[TMP2]], i32 0, i32 0 // CHECK-NEXT: [[TMP4:%.*]] = load i32**, i32*** [[DOTADDR1]], align 8 // CHECK-NEXT: store i32* [[TMP3]], i32** [[TMP4]], align 8 // CHECK-NEXT: ret void // // // CHECK-LABEL: define {{[^@]+}}@.omp_task_entry. // CHECK-SAME: (i32 [[TMP0:%.*]], %struct.kmp_task_t_with_privates* noalias [[TMP1:%.*]]) #[[ATTR3:[0-9]+]] { // CHECK-NEXT: entry: // CHECK-NEXT: [[DOTGLOBAL_TID__ADDR_I:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[DOTPART_ID__ADDR_I:%.*]] = alloca i32*, align 8 // CHECK-NEXT: [[DOTPRIVATES__ADDR_I:%.*]] = alloca i8*, align 8 // CHECK-NEXT: [[DOTCOPY_FN__ADDR_I:%.*]] = alloca void (i8*, ...)*, align 8 // CHECK-NEXT: [[DOTTASK_T__ADDR_I:%.*]] = alloca i8*, align 8 // CHECK-NEXT: [[__CONTEXT_ADDR_I:%.*]] = alloca %struct.anon*, align 8 // CHECK-NEXT: [[DOTFIRSTPRIV_PTR_ADDR_I:%.*]] = alloca i32*, align 8 // CHECK-NEXT: [[DOTCAPTURE_EXPR__I:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[DOTADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[DOTADDR1:%.*]] = alloca %struct.kmp_task_t_with_privates*, align 8 // CHECK-NEXT: store i32 [[TMP0]], i32* [[DOTADDR]], align 4 // CHECK-NEXT: store %struct.kmp_task_t_with_privates* [[TMP1]], %struct.kmp_task_t_with_privates** [[DOTADDR1]], align 8 // CHECK-NEXT: [[TMP2:%.*]] = load i32, i32* [[DOTADDR]], align 4 // CHECK-NEXT: [[TMP3:%.*]] = load %struct.kmp_task_t_with_privates*, %struct.kmp_task_t_with_privates** [[DOTADDR1]], align 8 // CHECK-NEXT: [[TMP4:%.*]] = getelementptr inbounds [[STRUCT_KMP_TASK_T_WITH_PRIVATES:%.*]], %struct.kmp_task_t_with_privates* [[TMP3]], i32 0, i32 0 // CHECK-NEXT: [[TMP5:%.*]] = getelementptr inbounds [[STRUCT_KMP_TASK_T:%.*]], %struct.kmp_task_t* [[TMP4]], i32 0, i32 2 // CHECK-NEXT: [[TMP6:%.*]] = getelementptr inbounds [[STRUCT_KMP_TASK_T]], %struct.kmp_task_t* [[TMP4]], i32 0, i32 0 // CHECK-NEXT: [[TMP7:%.*]] = load i8*, i8** [[TMP6]], align 8 // CHECK-NEXT: [[TMP8:%.*]] = bitcast i8* [[TMP7]] to %struct.anon* // CHECK-NEXT: [[TMP9:%.*]] = getelementptr inbounds [[STRUCT_KMP_TASK_T_WITH_PRIVATES]], %struct.kmp_task_t_with_privates* [[TMP3]], i32 0, i32 1 // CHECK-NEXT: [[TMP10:%.*]] = bitcast %struct..kmp_privates.t* [[TMP9]] to i8* // CHECK-NEXT: [[TMP11:%.*]] = bitcast %struct.kmp_task_t_with_privates* [[TMP3]] to i8* // CHECK-NEXT: call void @llvm.experimental.noalias.scope.decl(metadata [[META3:![0-9]+]]) // CHECK-NEXT: call void @llvm.experimental.noalias.scope.decl(metadata [[META6:![0-9]+]]) // CHECK-NEXT: call void @llvm.experimental.noalias.scope.decl(metadata [[META8:![0-9]+]]) // CHECK-NEXT: call void @llvm.experimental.noalias.scope.decl(metadata [[META10:![0-9]+]]) // CHECK-NEXT: store i32 [[TMP2]], i32* [[DOTGLOBAL_TID__ADDR_I]], align 4, !noalias !12 // CHECK-NEXT: store i32* [[TMP5]], i32** [[DOTPART_ID__ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: store i8* [[TMP10]], i8** [[DOTPRIVATES__ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: store void (i8*, ...)* bitcast (void (%struct..kmp_privates.t*, i32**)* @.omp_task_privates_map. to void (i8*, ...)*), void (i8*, ...)** [[DOTCOPY_FN__ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: store i8* [[TMP11]], i8** [[DOTTASK_T__ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: store %struct.anon* [[TMP8]], %struct.anon** [[__CONTEXT_ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: [[TMP12:%.*]] = load %struct.anon*, %struct.anon** [[__CONTEXT_ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: [[TMP13:%.*]] = load void (i8*, ...)*, void (i8*, ...)** [[DOTCOPY_FN__ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: [[TMP14:%.*]] = load i8*, i8** [[DOTPRIVATES__ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: [[TMP15:%.*]] = bitcast void (i8*, ...)* [[TMP13]] to void (i8*, i32**)* // CHECK-NEXT: call void [[TMP15]](i8* [[TMP14]], i32** [[DOTFIRSTPRIV_PTR_ADDR_I]]) #[[ATTR4:[0-9]+]] // CHECK-NEXT: [[TMP16:%.*]] = load i32*, i32** [[DOTFIRSTPRIV_PTR_ADDR_I]], align 8, !noalias !12 // CHECK-NEXT: [[TMP17:%.*]] = load i32, i32* [[TMP16]], align 4 // CHECK-NEXT: store i32 [[TMP17]], i32* [[DOTCAPTURE_EXPR__I]], align 4, !noalias !12 // CHECK-NEXT: call void @{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_test_task_affinity_l18() #[[ATTR4]] // CHECK-NEXT: ret i32 0 //
sum_v1.c
/* * Assignment 2 (CSE436) * Kazumi Malhan * 06/08/2016 * * Sum of A[N] */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <sys/timeb.h> /* read timer in second */ double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } /* read timer in ms */ double read_timer_ms() { struct timeb tm; ftime(&tm); return (double) tm.time * 1000.0 + (double) tm.millitm; } #define REAL float #define VECTOR_LENGTH 102400 /* initialize a vector with random floating point numbers */ void init(REAL *A, int N) { int i; for (i = 0; i < N; i++) { A[i] = (double) drand48(); } } /* Function Prototypes */ REAL sum (int N, REAL *A); REAL sum_omp_parallel (int N, REAL *A, int num_tasks); REAL sum_omp_parallel_for (int N, REAL *A, int num_tasks); /* * To compile: gcc sum.c -fopenmp -o sum * To run: ./sum N num_tasks */ int main(int argc, char *argv[]) { int N = VECTOR_LENGTH; int num_tasks = 4; double elapsed_serial, elapsed_para, elapsed_para_for; /* for timing */ if (argc < 3) { fprintf(stderr, "Usage: sum [<N(%d)>] [<#tasks(%d)>]\n", N,num_tasks); fprintf(stderr, "\t Example: ./sum %d %d\n", N,num_tasks); } else { N = atoi(argv[1]); num_tasks = atoi(argv[2]); } REAL *A = (REAL*)malloc(sizeof(REAL)*N); srand48((1 << 12)); init(A, N); /* Serial Run */ elapsed_serial = read_timer(); REAL result = sum(N, A); elapsed_serial = (read_timer() - elapsed_serial); printf("Serial Result:\t\t %f\n", result); // debug /* Parallel Run */ elapsed_para = read_timer(); result = sum_omp_parallel(N, A, num_tasks); elapsed_para = (read_timer() - elapsed_para); printf("Parallel Result:\t %f\n", result); // debug /* Parallel For Run */ elapsed_para_for = read_timer(); result = sum_omp_parallel_for(N, A, num_tasks); elapsed_para_for = (read_timer() - elapsed_para_for); printf("Parallel For Result:\t %f\n", result); // debug /* you should add the call to each function and time the execution */ printf("======================================================================================================\n"); printf("\tSum %d numbers with %d tasks\n", N, num_tasks); printf("------------------------------------------------------------------------------------------------------\n"); printf("Performance:\t\tRuntime (ms)\t MFLOPS \n"); printf("------------------------------------------------------------------------------------------------------\n"); printf("Sum Serial:\t\t\t%4f\t%4f\n", elapsed_serial * 1.0e3, 2*N / (1.0e6 * elapsed_serial)); printf("Sum Parallel:\t\t\t%4f\t%4f\n", elapsed_para * 1.0e3, 2*N / (1.0e6 * elapsed_para)); printf("Sum Parallel For:\t\t%4f\t%4f\n", elapsed_para_for * 1.0e3, 2*N / (1.0e6 * elapsed_para_for)); free(A); return 0; } /* Serial Implemenration */ REAL sum(int N, REAL *A) { int i; REAL result = 0.0; for (i = 0; i < N; ++i) result += A[i]; return result; } /* Parallel Implemenration */ REAL sum_omp_parallel (int N, REAL *A, int num_tasks) { REAL result = 0.0; omp_set_num_threads(num_tasks); /* Determine if task can be evenly distrubutable */ int each_task = N / num_tasks; int leftover = N - (each_task * num_tasks); #pragma omp parallel shared (N, A, num_tasks, result, leftover) { int i, tid, istart, iend; tid = omp_get_thread_num(); istart = tid * (N / num_tasks); iend = (tid + 1) * (N / num_tasks); for (i = istart; i < iend; ++i) { #pragma omp atomic result += A[i]; /* Must be atomic */ } /* Take care left over */ if (tid < leftover) { #pragma omp atomic result += A[N - tid - 1]; } } // end of parallel return result; } /* Parallel For Implemenration */ REAL sum_omp_parallel_for (int N, REAL *A, int num_tasks) { int i; REAL result = 0.0; omp_set_num_threads(num_tasks); # pragma omp parallel shared (N, A, result) private (i) { # pragma omp for schedule(static) nowait for (i = 0; i < N; ++i) { #pragma omp atomic result += A[i]; } } // end of parallel return result; }
DataUtils.h
#ifndef _SPTAG_COMMON_DATAUTILS_H_ #define _SPTAG_COMMON_DATAUTILS_H_ #include <sys/stat.h> #include <atomic> #include "CommonUtils.h" #include "../../Helper/CommonHelper.h" namespace SPTAG { namespace COMMON { const int bufsize = 1024 * 1024 * 1024; class DataUtils { public: template <typename T> static void ProcessTSVData(int id, int threadbase, std::uint64_t blocksize, std::string filename, std::string outfile, std::string outmetafile, std::string outmetaindexfile, std::atomic_int& numSamples, int& D, DistCalcMethod distCalcMethod) { std::ifstream inputStream(filename); if (!inputStream.is_open()) { std::cerr << "unable to open file " + filename << std::endl; throw MyException("unable to open file " + filename); exit(1); } std::ofstream outputStream, metaStream_out, metaStream_index; outputStream.open(outfile + std::to_string(id + threadbase), std::ofstream::binary); metaStream_out.open(outmetafile + std::to_string(id + threadbase), std::ofstream::binary); metaStream_index.open(outmetaindexfile + std::to_string(id + threadbase), std::ofstream::binary); if (!outputStream.is_open() || !metaStream_out.is_open() || !metaStream_index.is_open()) { std::cerr << "unable to open output file " << outfile << " " << outmetafile << " " << outmetaindexfile << std::endl; throw MyException("unable to open output files"); exit(1); } std::vector<float> arr; std::vector<T> sample; int base = 1; if (distCalcMethod == DistCalcMethod::Cosine) { base = Utils::GetBase<T>(); } std::uint64_t writepos = 0; int sampleSize = 0; std::uint64_t totalread = 0; std::streamoff startpos = id * blocksize; #ifndef _MSC_VER int enter_size = 1; #else int enter_size = 1; #endif std::string currentLine; size_t index; inputStream.seekg(startpos, std::ifstream::beg); if (id != 0) { std::getline(inputStream, currentLine); totalread += currentLine.length() + enter_size; } std::cout << "Begin thread " << id << " begin at:" << (startpos + totalread) << std::endl; while (!inputStream.eof() && totalread <= blocksize) { std::getline(inputStream, currentLine); if (currentLine.length() <= enter_size || (index = Utils::ProcessLine(currentLine, arr, D, base, distCalcMethod)) < 0) { totalread += currentLine.length() + enter_size; continue; } sample.resize(D); for (int j = 0; j < D; j++) sample[j] = (T)arr[j]; outputStream.write((char *)(sample.data()), sizeof(T)*D); metaStream_index.write((char *)&writepos, sizeof(std::uint64_t)); metaStream_out.write(currentLine.c_str(), index); writepos += index; sampleSize += 1; totalread += currentLine.length() + enter_size; } metaStream_index.write((char *)&writepos, sizeof(std::uint64_t)); metaStream_index.write((char *)&sampleSize, sizeof(int)); inputStream.close(); outputStream.close(); metaStream_out.close(); metaStream_index.close(); numSamples.fetch_add(sampleSize); std::cout << "Finish Thread[" << id << ", " << sampleSize << "] at:" << (startpos + totalread) << std::endl; } static void MergeData(int threadbase, std::string outfile, std::string outmetafile, std::string outmetaindexfile, std::atomic_int& numSamples, int D) { std::ifstream inputStream; std::ofstream outputStream; char * buf = new char[bufsize]; std::uint64_t * offsets; int partSamples; int metaSamples = 0; std::uint64_t lastoff = 0; outputStream.open(outfile, std::ofstream::binary); outputStream.write((char *)&numSamples, sizeof(int)); outputStream.write((char *)&D, sizeof(int)); for (int i = 0; i < threadbase; i++) { std::string file = outfile + std::to_string(i); inputStream.open(file, std::ifstream::binary); while (!inputStream.eof()) { inputStream.read(buf, bufsize); outputStream.write(buf, inputStream.gcount()); } inputStream.close(); remove(file.c_str()); } outputStream.close(); outputStream.open(outmetafile, std::ofstream::binary); for (int i = 0; i < threadbase; i++) { std::string file = outmetafile + std::to_string(i); inputStream.open(file, std::ifstream::binary); while (!inputStream.eof()) { inputStream.read(buf, bufsize); outputStream.write(buf, inputStream.gcount()); } inputStream.close(); remove(file.c_str()); } outputStream.close(); delete[] buf; outputStream.open(outmetaindexfile, std::ofstream::binary); outputStream.write((char *)&numSamples, sizeof(int)); for (int i = 0; i < threadbase; i++) { std::string file = outmetaindexfile + std::to_string(i); inputStream.open(file, std::ifstream::binary); inputStream.seekg(-((long long)sizeof(int)), inputStream.end); inputStream.read((char *)&partSamples, sizeof(int)); offsets = new std::uint64_t[partSamples + 1]; inputStream.seekg(0, inputStream.beg); inputStream.read((char *)offsets, sizeof(std::uint64_t)*(partSamples + 1)); inputStream.close(); remove(file.c_str()); for (int j = 0; j < partSamples + 1; j++) offsets[j] += lastoff; outputStream.write((char *)offsets, sizeof(std::uint64_t)*partSamples); lastoff = offsets[partSamples]; metaSamples += partSamples; delete[] offsets; } outputStream.write((char *)&lastoff, sizeof(std::uint64_t)); outputStream.close(); std::cout << "numSamples:" << numSamples << " metaSamples:" << metaSamples << " D:" << D << std::endl; } static bool MergeIndex(const std::string& p_vectorfile1, const std::string& p_metafile1, const std::string& p_metaindexfile1, const std::string& p_vectorfile2, const std::string& p_metafile2, const std::string& p_metaindexfile2) { std::ifstream inputStream1, inputStream2; std::ofstream outputStream; char * buf = new char[bufsize]; int R1, R2, C1, C2; #define MergeVector(inputStream, vectorFile, R, C) \ inputStream.open(vectorFile, std::ifstream::binary); \ if (!inputStream.is_open()) { \ std::cout << "Cannot open vector file: " << vectorFile <<"!" << std::endl; \ return false; \ } \ inputStream.read((char *)&(R), sizeof(int)); \ inputStream.read((char *)&(C), sizeof(int)); \ MergeVector(inputStream1, p_vectorfile1, R1, C1) MergeVector(inputStream2, p_vectorfile2, R2, C2) #undef MergeVector if (C1 != C2) { inputStream1.close(); inputStream2.close(); std::cout << "Vector dimensions are not the same!" << std::endl; return false; } R1 += R2; outputStream.open(p_vectorfile1 + "_tmp", std::ofstream::binary); outputStream.write((char *)&R1, sizeof(int)); outputStream.write((char *)&C1, sizeof(int)); while (!inputStream1.eof()) { inputStream1.read(buf, bufsize); outputStream.write(buf, inputStream1.gcount()); } while (!inputStream2.eof()) { inputStream2.read(buf, bufsize); outputStream.write(buf, inputStream2.gcount()); } inputStream1.close(); inputStream2.close(); outputStream.close(); if (p_metafile1 != "" && p_metafile2 != "") { outputStream.open(p_metafile1 + "_tmp", std::ofstream::binary); #define MergeMeta(inputStream, metaFile) \ inputStream.open(metaFile, std::ifstream::binary); \ if (!inputStream.is_open()) { \ std::cout << "Cannot open meta file: " << metaFile << "!" << std::endl; \ return false; \ } \ while (!inputStream.eof()) { \ inputStream.read(buf, bufsize); \ outputStream.write(buf, inputStream.gcount()); \ } \ inputStream.close(); \ MergeMeta(inputStream1, p_metafile1) MergeMeta(inputStream2, p_metafile2) #undef MergeMeta outputStream.close(); delete[] buf; std::uint64_t * offsets; int partSamples; std::uint64_t lastoff = 0; outputStream.open(p_metaindexfile1 + "_tmp", std::ofstream::binary); outputStream.write((char *)&R1, sizeof(int)); #define MergeMetaIndex(inputStream, metaIndexFile) \ inputStream.open(metaIndexFile, std::ifstream::binary); \ if (!inputStream.is_open()) { \ std::cout << "Cannot open meta index file: " << metaIndexFile << "!" << std::endl; \ return false; \ } \ inputStream.read((char *)&partSamples, sizeof(int)); \ offsets = new std::uint64_t[partSamples + 1]; \ inputStream.read((char *)offsets, sizeof(std::uint64_t)*(partSamples + 1)); \ inputStream.close(); \ for (int j = 0; j < partSamples + 1; j++) offsets[j] += lastoff; \ outputStream.write((char *)offsets, sizeof(std::uint64_t)*partSamples); \ lastoff = offsets[partSamples]; \ delete[] offsets; \ MergeMetaIndex(inputStream1, p_metaindexfile1) MergeMetaIndex(inputStream2, p_metaindexfile2) #undef MergeMetaIndex outputStream.write((char *)&lastoff, sizeof(std::uint64_t)); outputStream.close(); rename((p_metafile1 + "_tmp").c_str(), p_metafile1.c_str()); rename((p_metaindexfile1 + "_tmp").c_str(), p_metaindexfile1.c_str()); } rename((p_vectorfile1 + "_tmp").c_str(), p_vectorfile1.c_str()); std::cout << "Merged -> numSamples:" << R1 << " D:" << C1 << std::endl; return true; } template <typename T> static void ParseData(std::string filenames, std::string outfile, std::string outmetafile, std::string outmetaindexfile, int threadnum, DistCalcMethod distCalcMethod) { omp_set_num_threads(threadnum); std::atomic_int numSamples = { 0 }; int D = -1; int threadbase = 0; std::vector<std::string> inputFileNames = Helper::StrUtils::SplitString(filenames, ","); for (std::string inputFileName : inputFileNames) { #ifndef _MSC_VER struct stat stat_buf; stat(inputFileName.c_str(), &stat_buf); #else struct _stat64 stat_buf; int res = _stat64(inputFileName.c_str(), &stat_buf); #endif std::uint64_t blocksize = (stat_buf.st_size + threadnum - 1) / threadnum; #pragma omp parallel for for (int i = 0; i < threadnum; i++) { ProcessTSVData<T>(i, threadbase, blocksize, inputFileName, outfile, outmetafile, outmetaindexfile, numSamples, D, distCalcMethod); } threadbase += threadnum; } MergeData(threadbase, outfile, outmetafile, outmetaindexfile, numSamples, D); } }; } } #endif // _SPTAG_COMMON_DATAUTILS_H_
simpf.c
/* Start reading here */ #include <fftw3.h> #define NUM_POINTS 64 /* Never mind this bit */ #include <stdio.h> #include <math.h> #define REAL 0 #define IMAG 1 float theta; void acquire_from_somewhere(fftwf_complex* signal) { /* Generate two sine waves of different frequencies and * * amplitudes. * */ int i; #pragma omp for private(theta) for (i = 0; i < NUM_POINTS; ++i) { theta = (float)i / (float)NUM_POINTS * M_PI; signal[i][REAL] = 1.0 * cos(4.0 * theta) + 0.5 * cos( 8.0 * theta); signal[i][IMAG] = 1.0 * sin(2.0 * theta) + 0.5 * sin(16.0 * theta); signal[i][IMAG] = 1.0 * cos(2.0 * theta) + 0.5 * cos(16.0 * theta); // signal[i][REAL]=i; // signal[i][IMAG]=0; } } void do_something_with(fftwf_complex* result) { int i; for (i = 0; i < NUM_POINTS; ++i) { float mag = sqrt(result[i][REAL] * result[i][REAL] + result[i][IMAG] * result[i][IMAG]); printf("%23.12f %10.5f %10.5f\n", mag,result[i][REAL] ,result[i][IMAG]); } } /* Resume reading here */ int main() { fftwf_complex signal[NUM_POINTS]; fftwf_complex result[NUM_POINTS]; fftwf_plan plan = fftwf_plan_dft_1d(NUM_POINTS, signal, result, FFTW_FORWARD, FFTW_ESTIMATE); acquire_from_somewhere(signal); fftwf_execute(plan); do_something_with(result); fftwf_destroy_plan(plan); return 0; }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- 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 Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; struct OMPTraitProperty; struct OMPTraitSelector; struct OMPTraitSet; class OMPTraitInfo; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> FloatControlHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFenvAccessHandler; std::unique_ptr<PragmaHandler> STDCFenvRoundHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// Current kind of OpenMP clause OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; void MaybeDestroyTemplateIds() { if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); } void DestroyTemplateIds(); /// RAII object to destroy TemplateIdAnnotations where possible, from a /// likely-good position during parsing. struct DestroyTemplateIdAnnotationsRAIIObj { Parser &Self; DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {} ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// Handle the annotation token produced for /// #pragma STDC FENV_ROUND... void HandlePragmaFEnvRound(); /// Handle the annotation token produced for /// #pragma float_control void HandlePragmaFloatControl(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static TypeResult getTypeAnnotation(const Token &Tok) { if (!Tok.getAnnotationValue()) return TypeError(); return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, TypeResult T) { assert((T.isInvalid() || T.get()) && "produced a valid-but-null type annotation?"); Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser &p) : P(p), PrevPreferredType(P.PreferredType) { PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens. enum class CompoundToken { /// A '(' '{' beginning a statement-expression. StmtExprBegin, /// A '}' ')' ending a statement-expression. StmtExprEnd, /// A '[' '[' beginning a C++11 or C2x attribute. AttrBegin, /// A ']' ']' ending a C++11 or C2x attribute. AttrEnd, /// A '::' '*' forming a C++ pointer-to-member declaration. MemberPtr, }; /// Check that a compound operator was written in a "sensible" way, and warn /// if not. void checkCompoundToken(SourceLocation FirstTokLoc, tok::TokenKind FirstTokKind, CompoundToken Op); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// Introduces zero or more scopes for parsing. The scopes will all be exited /// when the object is destroyed. class MultiParseScope { Parser &Self; unsigned NumScopes = 0; MultiParseScope(const MultiParseScope&) = delete; public: MultiParseScope(Parser &Self) : Self(Self) {} void Enter(unsigned ScopeFlags) { Self.EnterScope(ScopeFlags); ++NumScopes; } void Exit() { while (NumScopes) { Self.ExitScope(); --NumScopes; } } ~MultiParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); /// Re-enter the template scopes for a declaration that might be a template. unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. Balances (), [], and {} delimiter tokens while /// skipping. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser *Self; /// Method - The method declaration. Decl *Method; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) {} /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; // In ParseCXXInlineMethods.cpp. struct ReenterTemplateScopeRAII; struct ReenterClassScopeRAII; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr, bool EnterForConditionScope = false); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); struct DesignatorCompletionInfo { SmallVectorImpl<Expr *> &InitExprs; QualType PreferredBaseType; }; ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK, SourceLocation *LParenLoc = nullptr, SourceLocation *RParenLoc = nullptr); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Whether a defining-type-specifier is permitted in a given context. enum class AllowDefiningTypeSpec { /// The grammar doesn't allow a defining-type-specifier here, and we must /// not parse one (eg, because a '{' could mean something else). No, /// The grammar doesn't allow a defining-type-specifier here, but we permit /// one for error recovery purposes. Sema will reject. NoButErrorRecovery, /// The grammar allows a defining-type-specifier here, even though it's /// always invalid. Sema will reject. YesButInvalid, /// The grammar allows a defining-type-specifier here, and one can be valid. Yes }; /// Is this a context in which we are parsing defining-type-specifiers (and /// so permit class and enum definitions in addition to non-defining class and /// enum elaborated-type-specifiers)? static AllowDefiningTypeSpec isDefiningTypeSpecifierContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: return AllowDefiningTypeSpec::Yes; case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: return AllowDefiningTypeSpec::YesButInvalid; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: return AllowDefiningTypeSpec::NoButErrorRecovery; case DeclSpecContext::DSC_trailing: return AllowDefiningTypeSpec::No; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which an opaque-enum-declaration can appear? static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: return true; case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, RecordDecl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Determine whether we could have an enum-base. /// /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise /// only consider this to be an enum-base if the next token is a '{'. /// /// \return \c false if this cannot possibly be an enum base; \c true /// otherwise. bool isEnumBase(bool AllowSemi); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); /// Try to skip a possibly empty sequence of 'attribute-specifier's without /// full validation of the syntactic structure of attributes. bool TrySkipAttributes(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeName, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); enum ParseAttrKindMask { PAKM_GNU = 1 << 0, PAKM_Declspec = 1 << 1, PAKM_CXX11 = 1 << 2, }; /// \brief Parse attributes based on what syntaxes are desired, allowing for /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec: /// __attribute__((...)) __declspec(...) __attribute__((...))) /// Note that Microsoft attributes (spelled with single square brackets) are /// not supported by this because of parsing ambiguities with other /// constructs. /// /// There are some attribute parse orderings that should not be allowed in /// arbitrary order. e.g., /// /// [[]] __attribute__(()) int i; // OK /// __attribute__(()) [[]] int i; // Not OK /// /// Such situations should use the specific attribute parsing functionality. void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributesWithRange &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr); void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { ParsedAttributesWithRange AttrsWithRange(AttrFactory); ParseAttributes(WhichAttrKinds, AttrsWithRange, End, LateAttrs); Attrs.takeAllFrom(AttrsWithRange); } /// \brief Possibly parse attributes based on what syntaxes are desired, /// allowing for the order to vary. bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributesWithRange &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) || (standardAttributesAllowed() && isCXX11AttributeSpecifier())) { ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs); return true; } return false; } bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) || (standardAttributesAllowed() && isCXX11AttributeSpecifier())) { ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs); return true; } return false; } void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } bool MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParseGNUAttributes(attrs, endLoc, LateAttrs); return true; } return false; } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } bool MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); return true; } return false; } bool MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) { ParseCXX11Attributes(attrs, endLoc); return true; } return false; } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) { ParseMicrosoftDeclSpecs(Attrs, End); return true; } return false; } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); ExprResult ParseExtIntegerArgument(); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse a property kind into \p TIProperty for the selector set \p Set and /// selector \p Selector. void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, llvm::omp::TraitSet Set, llvm::omp::TraitSelector Selector, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector kind into \p TISelector for the selector set \p Set. void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector set kind into \p TISet. void parseOMPTraitSetKind(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context property. void parseOMPContextProperty(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context selector. void parseOMPContextSelector(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &SeenSelectors); /// Parses an OpenMP context selector set. void parseOMPContextSelectorSet(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets); /// Parses OpenMP context selectors. bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI); /// Parse a `match` clause for an '#pragma omp declare variant'. Return true /// if there was an error. bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI, OMPTraitInfo *ParentTI); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse 'omp [begin] assume[s]' directive. void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Parse 'omp end assumes' directive. void ParseOpenMPEndAssumesDirective(SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if /// it is not the current token. void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind); /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error /// that the "end" matching the "begin" directive of kind \p BeginKind was not /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`. void parseOMPEndDirective(OpenMPDirectiveKind BeginKind, OpenMPDirectiveKind ExpectedKind, OpenMPDirectiveKind FoundKind, SourceLocation MatchingLoc, SourceLocation FoundLoc, bool SkipUntilOpenMPEnd); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Tries to parse cast part of OpenMP array shaping operation: /// '[' expression ']' { '[' expression ']' } ')'. bool tryParseOpenMPArrayShapingCastPart(); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param DKind Directive kind. /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses the 'sizes' clause of a '#pragma omp tile' directive. OMPClause *ParseOpenMPSizesClause(); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses and creates OpenMP 5.0 iterators expression: /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier = /// <range-specification> }+ ')' ExprResult ParseOpenMPIteratorsExpr(); /// Parses allocators and traits in the context of the uses_allocator clause. /// Expected format: /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')' OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind); /// Parses clause with an interop variable of kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. // OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *DepModOrTailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> MapTypeModifiers; SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> MapTypeModifiersLoc; SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers> MotionModifiers; SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation ExtraModifierLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; class GNUAsmQualifiers { unsigned Qualifiers = AQ_unspecified; public: enum AQ { AQ_unspecified = 0, AQ_volatile = 1, AQ_inline = 2, AQ_goto = 4, }; static const char *getQualifierName(AQ Qualifier); bool setAsmQualifier(AQ Qualifier); inline bool isVolatile() const { return Qualifiers & AQ_volatile; }; inline bool isInline() const { return Qualifiers & AQ_inline; }; inline bool isGoto() const { return Qualifiers & AQ_goto; } }; bool isGCCAsmStatement(const Token &TokAfterAsm) const; bool isGNUAsmQualifier(const Token &TokAfterAsm) const; GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const; bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ); }; } // end namespace clang #endif
rhs.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB SP code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// #include <math.h> #include "header.h" void compute_rhs() { int i, j, k, m; double aux, rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1; #pragma omp parallel default(shared) private(i,j,k,m,rho_inv,aux,uijk, \ up1,um1,vijk,vp1,vm1,wijk,wp1,wm1) { //--------------------------------------------------------------------- // compute the reciprocal of density, and the kinetic energy, // and the speed of sound. //--------------------------------------------------------------------- #pragma omp for schedule(static) nowait for (k = 0; k <= grid_points[2]-1; k++) { for (j = 0; j <= grid_points[1]-1; j++) { for (i = 0; i <= grid_points[0]-1; i++) { rho_inv = 1.0/u[k][j][i][0]; rho_i[k][j][i] = rho_inv; us[k][j][i] = u[k][j][i][1] * rho_inv; vs[k][j][i] = u[k][j][i][2] * rho_inv; ws[k][j][i] = u[k][j][i][3] * rho_inv; square[k][j][i] = 0.5* ( u[k][j][i][1]*u[k][j][i][1] + u[k][j][i][2]*u[k][j][i][2] + u[k][j][i][3]*u[k][j][i][3] ) * rho_inv; qs[k][j][i] = square[k][j][i] * rho_inv; //------------------------------------------------------------------- // (don't need speed and ainx until the lhs computation) //------------------------------------------------------------------- aux = c1c2*rho_inv* (u[k][j][i][4] - square[k][j][i]); speed[k][j][i] = sqrt(aux); } } } //--------------------------------------------------------------------- // copy the exact forcing term to the right hand side; because // this forcing term is known, we can store it on the whole grid // including the boundary //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = 0; k <= nz2+1; k++) { for (j = 0; j <= ny2+1; j++) { for (i = 0; i <= nx2+1; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = forcing[k][j][i][m]; } } } } //--------------------------------------------------------------------- // compute xi-direction fluxes //--------------------------------------------------------------------- #pragma omp for schedule(static) nowait for (k = 1; k <= nz2; k++) { for (j = 1; j <= ny2; j++) { for (i = 1; i <= nx2; i++) { uijk = us[k][j][i]; up1 = us[k][j][i+1]; um1 = us[k][j][i-1]; rhs[k][j][i][0] = rhs[k][j][i][0] + dx1tx1 * (u[k][j][i+1][0] - 2.0*u[k][j][i][0] + u[k][j][i-1][0]) - tx2 * (u[k][j][i+1][1] - u[k][j][i-1][1]); rhs[k][j][i][1] = rhs[k][j][i][1] + dx2tx1 * (u[k][j][i+1][1] - 2.0*u[k][j][i][1] + u[k][j][i-1][1]) + xxcon2*con43 * (up1 - 2.0*uijk + um1) - tx2 * (u[k][j][i+1][1]*up1 - u[k][j][i-1][1]*um1 + (u[k][j][i+1][4] - square[k][j][i+1] - u[k][j][i-1][4] + square[k][j][i-1]) * c2); rhs[k][j][i][2] = rhs[k][j][i][2] + dx3tx1 * (u[k][j][i+1][2] - 2.0*u[k][j][i][2] + u[k][j][i-1][2]) + xxcon2 * (vs[k][j][i+1] - 2.0*vs[k][j][i] + vs[k][j][i-1]) - tx2 * (u[k][j][i+1][2]*up1 - u[k][j][i-1][2]*um1); rhs[k][j][i][3] = rhs[k][j][i][3] + dx4tx1 * (u[k][j][i+1][3] - 2.0*u[k][j][i][3] + u[k][j][i-1][3]) + xxcon2 * (ws[k][j][i+1] - 2.0*ws[k][j][i] + ws[k][j][i-1]) - tx2 * (u[k][j][i+1][3]*up1 - u[k][j][i-1][3]*um1); rhs[k][j][i][4] = rhs[k][j][i][4] + dx5tx1 * (u[k][j][i+1][4] - 2.0*u[k][j][i][4] + u[k][j][i-1][4]) + xxcon3 * (qs[k][j][i+1] - 2.0*qs[k][j][i] + qs[k][j][i-1]) + xxcon4 * (up1*up1 - 2.0*uijk*uijk + um1*um1) + xxcon5 * (u[k][j][i+1][4]*rho_i[k][j][i+1] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k][j][i-1][4]*rho_i[k][j][i-1]) - tx2 * ( (c1*u[k][j][i+1][4] - c2*square[k][j][i+1])*up1 - (c1*u[k][j][i-1][4] - c2*square[k][j][i-1])*um1 ); } } //--------------------------------------------------------------------- // add fourth order xi-direction dissipation //--------------------------------------------------------------------- for (j = 1; j <= ny2; j++) { i = 1; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * (5.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m]); } i = 2; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m]); } } for (j = 1; j <= ny2; j++) { for (i = 3; i <= nx2-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m] ); } } } for (j = 1; j <= ny2; j++) { i = nx2-1; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] ); } i = nx2; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.0*u[k][j][i-1][m] + 5.0*u[k][j][i][m] ); } } } #pragma omp for schedule(static) for (k = 1; k <= nz2; k++) { for (j = 1; j <= ny2; j++) { for (i = 1; i <= nx2; i++) { vijk = vs[k][j][i]; vp1 = vs[k][j+1][i]; vm1 = vs[k][j-1][i]; rhs[k][j][i][0] = rhs[k][j][i][0] + dy1ty1 * (u[k][j+1][i][0] - 2.0*u[k][j][i][0] + u[k][j-1][i][0]) - ty2 * (u[k][j+1][i][2] - u[k][j-1][i][2]); rhs[k][j][i][1] = rhs[k][j][i][1] + dy2ty1 * (u[k][j+1][i][1] - 2.0*u[k][j][i][1] + u[k][j-1][i][1]) + yycon2 * (us[k][j+1][i] - 2.0*us[k][j][i] + us[k][j-1][i]) - ty2 * (u[k][j+1][i][1]*vp1 - u[k][j-1][i][1]*vm1); rhs[k][j][i][2] = rhs[k][j][i][2] + dy3ty1 * (u[k][j+1][i][2] - 2.0*u[k][j][i][2] + u[k][j-1][i][2]) + yycon2*con43 * (vp1 - 2.0*vijk + vm1) - ty2 * (u[k][j+1][i][2]*vp1 - u[k][j-1][i][2]*vm1 + (u[k][j+1][i][4] - square[k][j+1][i] - u[k][j-1][i][4] + square[k][j-1][i]) * c2); rhs[k][j][i][3] = rhs[k][j][i][3] + dy4ty1 * (u[k][j+1][i][3] - 2.0*u[k][j][i][3] + u[k][j-1][i][3]) + yycon2 * (ws[k][j+1][i] - 2.0*ws[k][j][i] + ws[k][j-1][i]) - ty2 * (u[k][j+1][i][3]*vp1 - u[k][j-1][i][3]*vm1); rhs[k][j][i][4] = rhs[k][j][i][4] + dy5ty1 * (u[k][j+1][i][4] - 2.0*u[k][j][i][4] + u[k][j-1][i][4]) + yycon3 * (qs[k][j+1][i] - 2.0*qs[k][j][i] + qs[k][j-1][i]) + yycon4 * (vp1*vp1 - 2.0*vijk*vijk + vm1*vm1) + yycon5 * (u[k][j+1][i][4]*rho_i[k][j+1][i] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k][j-1][i][4]*rho_i[k][j-1][i]) - ty2 * ((c1*u[k][j+1][i][4] - c2*square[k][j+1][i]) * vp1 - (c1*u[k][j-1][i][4] - c2*square[k][j-1][i]) * vm1); } } //--------------------------------------------------------------------- // add fourth order eta-direction dissipation //--------------------------------------------------------------------- j = 1; for (i = 1; i <= nx2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * ( 5.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m]); } } j = 2; for (i = 1; i <= nx2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m]); } } for (j = 3; j <= ny2-2; j++) { for (i = 1; i <= nx2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m] ); } } } j = ny2-1; for (i = 1; i <= nx2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] ); } } j = ny2; for (i = 1; i <= nx2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.0*u[k][j-1][i][m] + 5.0*u[k][j][i][m] ); } } } #pragma omp for schedule(static) for (k = 1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { wijk = ws[k][j][i]; wp1 = ws[k+1][j][i]; wm1 = ws[k-1][j][i]; rhs[k][j][i][0] = rhs[k][j][i][0] + dz1tz1 * (u[k+1][j][i][0] - 2.0*u[k][j][i][0] + u[k-1][j][i][0]) - tz2 * (u[k+1][j][i][3] - u[k-1][j][i][3]); rhs[k][j][i][1] = rhs[k][j][i][1] + dz2tz1 * (u[k+1][j][i][1] - 2.0*u[k][j][i][1] + u[k-1][j][i][1]) + zzcon2 * (us[k+1][j][i] - 2.0*us[k][j][i] + us[k-1][j][i]) - tz2 * (u[k+1][j][i][1]*wp1 - u[k-1][j][i][1]*wm1); rhs[k][j][i][2] = rhs[k][j][i][2] + dz3tz1 * (u[k+1][j][i][2] - 2.0*u[k][j][i][2] + u[k-1][j][i][2]) + zzcon2 * (vs[k+1][j][i] - 2.0*vs[k][j][i] + vs[k-1][j][i]) - tz2 * (u[k+1][j][i][2]*wp1 - u[k-1][j][i][2]*wm1); rhs[k][j][i][3] = rhs[k][j][i][3] + dz4tz1 * (u[k+1][j][i][3] - 2.0*u[k][j][i][3] + u[k-1][j][i][3]) + zzcon2*con43 * (wp1 - 2.0*wijk + wm1) - tz2 * (u[k+1][j][i][3]*wp1 - u[k-1][j][i][3]*wm1 + (u[k+1][j][i][4] - square[k+1][j][i] - u[k-1][j][i][4] + square[k-1][j][i]) * c2); rhs[k][j][i][4] = rhs[k][j][i][4] + dz5tz1 * (u[k+1][j][i][4] - 2.0*u[k][j][i][4] + u[k-1][j][i][4]) + zzcon3 * (qs[k+1][j][i] - 2.0*qs[k][j][i] + qs[k-1][j][i]) + zzcon4 * (wp1*wp1 - 2.0*wijk*wijk + wm1*wm1) + zzcon5 * (u[k+1][j][i][4]*rho_i[k+1][j][i] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k-1][j][i][4]*rho_i[k-1][j][i]) - tz2 * ((c1*u[k+1][j][i][4] - c2*square[k+1][j][i])*wp1 - (c1*u[k-1][j][i][4] - c2*square[k-1][j][i])*wm1); } } } //--------------------------------------------------------------------- // add fourth order zeta-direction dissipation //--------------------------------------------------------------------- k = 1; #pragma omp for schedule(static) nowait for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * (5.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m]); } } } k = 2; #pragma omp for schedule(static) nowait for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m]); } } } #pragma omp for schedule(static) nowait for (k = 3; k <= grid_points[2]-4; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m] ); } } } } k = grid_points[2]-3; #pragma omp for schedule(static) nowait for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] ); } } } k = grid_points[2]-2; #pragma omp for schedule(static) for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.0*u[k-1][j][i][m] + 5.0*u[k][j][i][m] ); } } } #pragma omp for schedule(static) nowait for (k = 1; k <= nz2; k++) { for (j = 1; j <= ny2; j++) { for (i = 1; i <= nx2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] * dt; } } } } } //end parallel }
variational_distance_calculation_process.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // Ruben Zorrilla // // #if !defined(KRATOS_VARIATIONAL_DISTANCE_CALCULATION_PROCESS_INCLUDED ) #define KRATOS_VARIATIONAL_DISTANCE_CALCULATION_PROCESS_INCLUDED // System includes #include <string> #include <iostream> #include <algorithm> // External includes // Project includes #include "includes/define.h" #include "containers/model.h" #include "includes/kratos_flags.h" #include "elements/distance_calculation_element_simplex.h" #include "linear_solvers/linear_solver.h" #include "processes/process.h" #include "modeler/connectivity_preserve_modeler.h" #include "solving_strategies/builder_and_solvers/residualbased_block_builder_and_solver.h" #include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme.h" #include "solving_strategies/strategies/residualbased_linear_strategy.h" #include "utilities/variable_utils.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /**takes a model part full of SIMPLICIAL ELEMENTS (triangles and tetras) and recomputes a signed distance function mantaining as much as possible the position of the zero of the function prior to the call. This is achieved by minimizing the function ( 1 - norm( gradient( distance ) )**2 with the restriction that "distance" is a finite elment function */ template< unsigned int TDim, class TSparseSpace, class TDenseSpace, class TLinearSolver > class VariationalDistanceCalculationProcess : public Process { public: KRATOS_DEFINE_LOCAL_FLAG(PERFORM_STEP1); KRATOS_DEFINE_LOCAL_FLAG(DO_EXPENSIVE_CHECKS); KRATOS_DEFINE_LOCAL_FLAG(CALCULATE_EXACT_DISTANCES_TO_PLANE); ///@name Type Definitions ///@{ typedef Scheme< TSparseSpace, TDenseSpace > SchemeType; typedef typename SchemeType::Pointer SchemePointerType; typedef typename BuilderAndSolver<TSparseSpace,TDenseSpace,TLinearSolver>::Pointer BuilderSolverPointerType; typedef ImplicitSolvingStrategy< TSparseSpace, TDenseSpace, TLinearSolver > SolvingStrategyType; ///@} ///@name Pointer Definitions /// Pointer definition of VariationalDistanceCalculationProcess KRATOS_CLASS_POINTER_DEFINITION(VariationalDistanceCalculationProcess); ///@} ///@name Life Cycle ///@{ /**This process recomputed the distance function mantaining the zero of the existing distance distribution * for this reason the DISTANCE should be initialized to values distinct from zero in at least some portions of the domain * alternatively, the DISTANCE shall be fixed to zero at least on some nodes, and the process will compute a positive distance * respecting that zero * @param base_model_parr - is the model part on the top of which the calculation will be performed * @param plinear_solver - linear solver to be used internally * @max_iterations - maximum number of iteration to be employed in the nonlinear optimization process. * - can also be set to 0 if a (very) rough approximation is enough * * EXAMPLE OF USAGE FROM PYTHON: * class distance_linear_solver_settings: solver_type = "AMGCL" tolerance = 1E-3 max_iteration = 200 scaling = False krylov_type = "CG" smoother_type = "SPAI0" verbosity = 0 import linear_solver_factory distance_linear_solver = linear_solver_factory.ConstructSolver(distance_linear_solver_settings) max_iterations=1 distance_calculator = VariationalDistanceCalculationProcess2D(fluid_model_part, distance_linear_solver, max_iterations) distance_calculator.Execute() */ VariationalDistanceCalculationProcess( ModelPart& rBaseModelPart, typename TLinearSolver::Pointer pLinearSolver, unsigned int MaxIterations = 10, Flags Options = CALCULATE_EXACT_DISTANCES_TO_PLANE.AsFalse(), std::string AuxPartName = "RedistanceCalculationPart", double Coefficient1 = 0.01, double Coefficient2 = 0.1) : mDistancePartIsInitialized(false), mMaxIterations(MaxIterations), mrModel( rBaseModelPart.GetModel() ), mrBaseModelPart (rBaseModelPart), mOptions( Options ), mAuxModelPartName( AuxPartName ), mCoefficient1(Coefficient1), mCoefficient2(Coefficient2) { KRATOS_TRY ValidateInput(); // Generate an auxilary model part and populate it by elements of type DistanceCalculationElementSimplex ReGenerateDistanceModelPart(rBaseModelPart); auto p_builder_solver = Kratos::make_shared<ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> >(pLinearSolver); InitializeSolutionStrategy(p_builder_solver); KRATOS_CATCH("") } /// Constructor with custom Builder And Solver /** To be used in the trilinos version, since the trilinos builder and * solver needs additional data (the EpetraComm). * @param rBaseModelPart Reference ModelPart for distance calculation. * @param pLinearSolver Linear solver for the distance system. * @param MaxIterations Maximum number of non-linear optimization iterations. * @param Options Configuration flags for the procedure. * @param AuxPartName Name to be used for the internal distance calculation ModelPart. */ VariationalDistanceCalculationProcess( ModelPart& rBaseModelPart, typename TLinearSolver::Pointer pLinearSolver, BuilderSolverPointerType pBuilderAndSolver, unsigned int MaxIterations = 10, Flags Options = CALCULATE_EXACT_DISTANCES_TO_PLANE.AsFalse(), std::string AuxPartName = "RedistanceCalculationPart", double Coefficient1 = 0.01, double Coefficient2 = 0.1) : mDistancePartIsInitialized(false), mMaxIterations(MaxIterations), mrModel( rBaseModelPart.GetModel() ), mrBaseModelPart (rBaseModelPart), mOptions( Options ), mAuxModelPartName( AuxPartName ), mCoefficient1(Coefficient1), mCoefficient2(Coefficient2) { KRATOS_TRY ValidateInput(); // Generate an auxilary model part and populate it by elements of type DistanceCalculationElementSimplex ReGenerateDistanceModelPart(rBaseModelPart); InitializeSolutionStrategy(pBuilderAndSolver); KRATOS_CATCH("") } /// Destructor. ~VariationalDistanceCalculationProcess() override { Clear(); }; ///@} ///@name Operators ///@{ void operator()() { Execute(); } ///@} ///@name Operations ///@{ void Execute() override { KRATOS_TRY; if(mDistancePartIsInitialized == false){ ReGenerateDistanceModelPart(mrBaseModelPart); } ModelPart& r_distance_model_part = mrModel.GetModelPart( mAuxModelPartName ); // TODO: check flag PERFORM_STEP1 // Step1 - solve a poisson problem with a source term which depends on the sign of the existing distance function r_distance_model_part.pGetProcessInfo()->SetValue(FRACTIONAL_STEP,1); // Unfix the distances const int nnodes = static_cast<int>(r_distance_model_part.NumberOfNodes()); block_for_each(r_distance_model_part.Nodes(), [](Node<3>& rNode){ double& d = rNode.FastGetSolutionStepValue(DISTANCE); double& fix_flag = rNode.FastGetSolutionStepValue(FLAG_VARIABLE); // Free the DISTANCE values fix_flag = 1.0; rNode.Free(DISTANCE); // Save the distances rNode.SetValue(DISTANCE, d); if(d == 0){ d = 1.0e-15; fix_flag = -1.0; rNode.Fix(DISTANCE); } else { if(d > 0.0){ d = 1.0e15; // Set to a large number, to make sure that that the minimal distance is computed according to CaculateTetrahedraDistances } else { d = -1.0e15; } } }); block_for_each(r_distance_model_part.Elements(), [this](Element& rElem){ array_1d<double,TDim+1> distances; auto& geom = rElem.GetGeometry(); for(unsigned int i=0; i<TDim+1; i++){ distances[i] = geom[i].GetValue(DISTANCE); } const array_1d<double,TDim+1> original_distances = distances; // The element is cut by the interface if(this->IsSplit(distances)){ // Compute the unsigned distance using GeometryUtils if (mOptions.Is(CALCULATE_EXACT_DISTANCES_TO_PLANE)) { GeometryUtils::CalculateExactDistancesToPlane(geom, distances); } else { if(TDim==3){ GeometryUtils::CalculateTetrahedraDistances(geom, distances); } else { GeometryUtils::CalculateTriangleDistances(geom, distances); } } // Assign the sign using the original distance values for(unsigned int i = 0; i < TDim+1; ++i){ if(original_distances[i] < 0){ distances[i] = -distances[i]; } } for(unsigned int i = 0; i < TDim+1; ++i){ double &d = geom[i].FastGetSolutionStepValue(DISTANCE); double &fix_flag = geom[i].FastGetSolutionStepValue(FLAG_VARIABLE); geom[i].SetLock(); if(std::abs(d) > std::abs(distances[i])){ d = distances[i]; } fix_flag = -1.0; geom[i].Fix(DISTANCE); geom[i].UnSetLock(); } } }); // SHALL WE SYNCHRONIZE SOMETHING IN HERE?¿?¿??¿ WE'VE CHANGED THE NODAL DISTANCE VALUES FROM THE ELEMENTS... this->SynchronizeFixity(); this->SynchronizeDistance(); // Compute the maximum and minimum distance for the fixed nodes double max_dist = 0.0; double min_dist = 0.0; for(int i_node = 0; i_node < nnodes; ++i_node){ auto it_node = r_distance_model_part.NodesBegin() + i_node; if(it_node->IsFixed(DISTANCE)){ const double& d = it_node->FastGetSolutionStepValue(DISTANCE); if(d > max_dist){ max_dist = d; } if(d < min_dist){ min_dist = d; } } } // Synchronize the maximum and minimum distance values const auto &r_communicator = r_distance_model_part.GetCommunicator().GetDataCommunicator(); max_dist = r_communicator.MaxAll(max_dist); min_dist = r_communicator.MinAll(min_dist); // Assign the max dist to all of the non-fixed positive nodes // and the minimum one to the non-fixed negatives block_for_each(r_distance_model_part.Nodes(), [&min_dist, &max_dist](Node<3>& rNode){ if(!rNode.IsFixed(DISTANCE)){ double& d = rNode.FastGetSolutionStepValue(DISTANCE); if(d>0){ d = max_dist; } else { d = min_dist; } } }); mpSolvingStrategy->Solve(); // Step2 - minimize the target residual r_distance_model_part.pGetProcessInfo()->SetValue(FRACTIONAL_STEP,2); for(unsigned int it = 0; it<mMaxIterations; it++){ mpSolvingStrategy->Solve(); } // Unfix the distances VariableUtils().ApplyFixity(DISTANCE, false, r_distance_model_part.Nodes()); KRATOS_CATCH("") } void Clear() override { if(mrModel.HasModelPart( mAuxModelPartName )) mrModel.DeleteModelPart( mAuxModelPartName ); mDistancePartIsInitialized = false; mpSolvingStrategy->Clear(); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "VariationalDistanceCalculationProcess"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "VariationalDistanceCalculationProcess"; } /// Print object's data. void PrintData(std::ostream& rOStream) const override { } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ bool mDistancePartIsInitialized; unsigned int mMaxIterations; Model& mrModel; ModelPart& mrBaseModelPart; Flags mOptions; std::string mAuxModelPartName; double mCoefficient1; double mCoefficient2; typename SolvingStrategyType::UniquePointer mpSolvingStrategy; ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ void ValidateInput() { const DataCommunicator& r_comm = mrBaseModelPart.GetCommunicator().GetDataCommunicator(); int num_elements = mrBaseModelPart.NumberOfElements(); int num_nodes = mrBaseModelPart.NumberOfNodes(); if (num_elements > 0) { const auto geometry_family = mrBaseModelPart.ElementsBegin()->GetGeometry().GetGeometryFamily(); KRATOS_ERROR_IF( (TDim == 2) && (geometry_family != GeometryData::KratosGeometryFamily::Kratos_Triangle) ) << "In 2D the element type is expected to be a triangle." << std::endl; KRATOS_ERROR_IF( (TDim == 3) && (geometry_family != GeometryData::KratosGeometryFamily::Kratos_Tetrahedra) ) << "In 3D the element type is expected to be a tetrahedron" << std::endl; } KRATOS_ERROR_IF(r_comm.SumAll(num_nodes) == 0) << "The model part has no nodes." << std::endl; KRATOS_ERROR_IF(r_comm.SumAll(num_elements) == 0) << "The model Part has no elements." << std::endl; // Check that required nodal variables are present VariableUtils().CheckVariableExists<Variable<double > >(DISTANCE, mrBaseModelPart.Nodes()); VariableUtils().CheckVariableExists<Variable<double > >(FLAG_VARIABLE, mrBaseModelPart.Nodes()); } void InitializeSolutionStrategy(BuilderSolverPointerType pBuilderAndSolver) { // Generate a linear strategy auto p_scheme = Kratos::make_shared< ResidualBasedIncrementalUpdateStaticScheme< TSparseSpace,TDenseSpace > >(); ModelPart& r_distance_model_part = mrModel.GetModelPart( mAuxModelPartName ); bool CalculateReactions = false; bool ReformDofAtEachIteration = false; bool CalculateNormDxFlag = false; mpSolvingStrategy = Kratos::make_unique<ResidualBasedLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver> >( r_distance_model_part, p_scheme, pBuilderAndSolver, CalculateReactions, ReformDofAtEachIteration, CalculateNormDxFlag); // TODO: check flag DO_EXPENSIVE_CHECKS mpSolvingStrategy->Check(); } virtual void ReGenerateDistanceModelPart(ModelPart& rBaseModelPart) { KRATOS_TRY if(mrModel.HasModelPart( mAuxModelPartName )) mrModel.DeleteModelPart( mAuxModelPartName ); // Ensure that the nodes have distance as a DOF VariableUtils().AddDof<Variable<double> >(DISTANCE, rBaseModelPart); // Generate ModelPart& r_distance_model_part = mrModel.CreateModelPart( mAuxModelPartName ); Element::Pointer p_distance_element = Kratos::make_intrusive<DistanceCalculationElementSimplex<TDim> >(); r_distance_model_part.GetNodalSolutionStepVariablesList() = rBaseModelPart.GetNodalSolutionStepVariablesList(); ConnectivityPreserveModeler modeler; modeler.GenerateModelPart(rBaseModelPart, r_distance_model_part, *p_distance_element); // Using the conditions to mark the boundary with the flag boundary // Note that we DO NOT add the conditions to the model part VariableUtils().SetFlag<ModelPart::NodesContainerType>(BOUNDARY, false, r_distance_model_part.Nodes()); // Note that above we have assigned the same geometry. Thus the flag is // set in the distance model part despite we are iterating the base one for (auto it_cond = rBaseModelPart.ConditionsBegin(); it_cond != rBaseModelPart.ConditionsEnd(); ++it_cond){ Geometry< Node<3> >& geom = it_cond->GetGeometry(); for(unsigned int i=0; i<geom.size(); i++){ geom[i].Set(BOUNDARY,true); } } rBaseModelPart.GetCommunicator().SynchronizeOrNodalFlags(BOUNDARY); r_distance_model_part.GetProcessInfo().SetValue(VARIATIONAL_REDISTANCE_COEFFICIENT_FIRST, mCoefficient1); r_distance_model_part.GetProcessInfo().SetValue(VARIATIONAL_REDISTANCE_COEFFICIENT_SECOND, mCoefficient2); mDistancePartIsInitialized = true; KRATOS_CATCH("") } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ bool IsSplit(const array_1d<double,TDim+1> &rDistances){ unsigned int positives = 0, negatives = 0; for(unsigned int i = 0; i < TDim+1; ++i){ if(rDistances[i] >= 0){ ++positives; } else { ++negatives; } } if (positives > 0 && negatives > 0){ return true; } return false; } void SynchronizeDistance(){ ModelPart& r_distance_model_part = mrModel.GetModelPart( mAuxModelPartName ); auto &r_communicator = r_distance_model_part.GetCommunicator(); // Only required in the MPI case if(r_communicator.TotalProcesses() != 1){ int nnodes = static_cast<int>(r_distance_model_part.NumberOfNodes()); // Set the distance absolute value #pragma omp parallel for for(int i_node = 0; i_node < nnodes; ++i_node){ auto it_node = r_distance_model_part.NodesBegin() + i_node; it_node->FastGetSolutionStepValue(DISTANCE) = std::abs(it_node->FastGetSolutionStepValue(DISTANCE)); } // Synchronize the unsigned value to minimum r_communicator.SynchronizeCurrentDataToMin(DISTANCE); // Set the distance sign again by retrieving it from the non-historical database #pragma omp parallel for for(int i_node = 0; i_node < nnodes; ++i_node){ auto it_node = r_distance_model_part.NodesBegin() + i_node; if(it_node->GetValue(DISTANCE) < 0.0){ it_node->FastGetSolutionStepValue(DISTANCE) = -it_node->FastGetSolutionStepValue(DISTANCE); } } } } void SynchronizeFixity(){ ModelPart& r_distance_model_part = mrModel.GetModelPart( mAuxModelPartName ); auto &r_communicator = r_distance_model_part.GetCommunicator(); // Only required in the MPI case if(r_communicator.TotalProcesses() != 1){ int nnodes = static_cast<int>(r_distance_model_part.NumberOfNodes()); // Synchronize the fixity flag variable to minium // (-1.0 means fixed and 1.0 means free) r_communicator.SynchronizeCurrentDataToMin(FLAG_VARIABLE); // Set the fixity according to the synchronized flag #pragma omp parallel for for(int i_node = 0; i_node < nnodes; ++i_node){ auto it_node = r_distance_model_part.NodesBegin() + i_node; const double &r_fix_flag = it_node->FastGetSolutionStepValue(FLAG_VARIABLE); if (r_fix_flag == -1.0){ it_node->Fix(DISTANCE); } } } } ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. VariationalDistanceCalculationProcess& operator=(VariationalDistanceCalculationProcess const& rOther); /// Copy constructor. //VariationalDistanceCalculationProcess(VariationalDistanceCalculationProcess const& rOther); ///@} }; // Class VariationalDistanceCalculationProcess //avoiding using the macro since this has a template parameter. If there was no template plase use the KRATOS_CREATE_LOCAL_FLAG macro template< unsigned int TDim,class TSparseSpace, class TDenseSpace, class TLinearSolver > const Kratos::Flags VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>::PERFORM_STEP1(Kratos::Flags::Create(0)); template< unsigned int TDim,class TSparseSpace, class TDenseSpace, class TLinearSolver > const Kratos::Flags VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>::DO_EXPENSIVE_CHECKS(Kratos::Flags::Create(1)); template< unsigned int TDim,class TSparseSpace, class TDenseSpace, class TLinearSolver > const Kratos::Flags VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>::CALCULATE_EXACT_DISTANCES_TO_PLANE(Kratos::Flags::Create(2)); ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function template< unsigned int TDim, class TSparseSpace, class TDenseSpace, class TLinearSolver> inline std::istream& operator >> (std::istream& rIStream, VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>& rThis); /// output stream function template< unsigned int TDim, class TSparseSpace, class TDenseSpace, class TLinearSolver> inline std::ostream& operator << (std::ostream& rOStream, const VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_VARIATIONAL_DISTANCE_CALCULATION_PROCESS_INCLUDED defined
cpu_kernels.h
#pragma once #include <torchaudio/csrc/rnnt/cpu/math.h> #include <torchaudio/csrc/rnnt/options.h> #include <torchaudio/csrc/rnnt/types.h> #include <cstring> #include <limits> #include <vector> namespace torchaudio { namespace rnnt { namespace cpu { template <typename DTYPE> struct LogProbs { DTYPE skip_; // blank. DTYPE emit_; // target. LogProbs(DTYPE skip, DTYPE emit) : skip_(skip), emit_(emit) {} DTYPE& skip() { return skip_; } DTYPE& emit() { return emit_; } const DTYPE& skip() const { return skip_; } const DTYPE& emit() const { return emit_; } }; // TensorView: view a block of allocated memory as a tensor. template <typename DTYPE> class TensorView { public: TensorView(const std::vector<int>& dims, DTYPE* data) : dims_(dims), data_(data) { strides_.resize(dims.size()); strides_.back() = 1; for (int i = dims.size() - 2; i >= 0; --i) { strides_[i] = strides_[i + 1] * dims[i + 1]; } } DTYPE& operator()(const std::vector<int>& indices) { CHECK_EQ(indices.size(), dims_.size()); int index = indices.back(); for (int i = indices.size() - 2; i >= 0; --i) { index += indices[i] * strides_[i]; } return data_[index]; } void SetZero() { int size = dims_[0] * strides_[0]; std::memset(data_, 0, sizeof(DTYPE) * size); } private: std::vector<int> dims_; std::vector<int> strides_; DTYPE* data_; }; template <typename DTYPE, typename CAST_DTYPE> status_t LogSumExp2D(int N, int D, const DTYPE* logits, CAST_DTYPE* outputs) { for (int i = 0; i < N * D; i += D) { CAST_DTYPE max = logits[i]; for (int j = 1; j < D; ++j) { max = std::max(max, CAST_DTYPE(logits[i + j])); } CAST_DTYPE sum = 0; for (int j = 0; j < D; ++j) { sum = sum + std::exp(CAST_DTYPE(logits[i + j]) - max); } outputs[i / D] = max + std::log(sum); } return SUCCESS; } template <typename DTYPE, typename CAST_DTYPE> void ComputeLogProbsOneSequence( const Options& options, TensorView<const DTYPE>& logits, const int* targets, int srcLen, int tgtLen, TensorView<const CAST_DTYPE>& denom, TensorView<LogProbs<CAST_DTYPE>>& logProbs) { const int& T = srcLen; const int& U = tgtLen; const int& blank = options.blank_; for (int t = 0; t < T; ++t) { for (int u = 0; u < U; ++u) { if (u < U - 1) { logProbs({t, u}).emit() = CAST_DTYPE(logits({t, u, targets[u]})) - denom({t, u}); } logProbs({t, u}).skip() = CAST_DTYPE(logits({t, u, blank})) - denom({t, u}); } } } template <typename DTYPE, typename CAST_DTYPE> status_t ComputeLogProbs( const Options& options, const DTYPE* logits, const int* targets, const int* srcLengths, const int* tgtLengths, const CAST_DTYPE* denominators, CAST_DTYPE* logProbs) { std::vector<TensorView<const DTYPE>> seqLogits; std::vector<const int*> seqTargets; std::vector<TensorView<const CAST_DTYPE>> seqDenoms; std::vector<TensorView<LogProbs<CAST_DTYPE>>> seqlogProbs; const int& B = options.batchSize_; const int& maxT = options.maxSrcLen_; const int& maxU = options.maxTgtLen_; const int& D = options.numTargets_; for (int b = 0; b < B; ++b) { seqLogits.push_back( TensorView<const DTYPE>({maxT, maxU, D}, logits + b * maxT * maxU * D)); seqTargets.push_back(targets + b * (maxU - 1)); seqDenoms.push_back(TensorView<const CAST_DTYPE>( {maxT, maxU}, denominators + b * maxT * maxU)); seqlogProbs.push_back(TensorView<LogProbs<CAST_DTYPE>>( {maxT, maxU}, reinterpret_cast<LogProbs<CAST_DTYPE>*>(logProbs) + b * maxT * maxU)); } //#pragma omp parallel for for (int b = 0; b < B; ++b) { // use max 2 * B threads. ComputeLogProbsOneSequence<DTYPE, CAST_DTYPE>( /*options=*/options, /*logits=*/seqLogits[b], /*targets=*/seqTargets[b], /*srcLen=*/srcLengths[b], /*tgtLen=*/tgtLengths[b] + 1, // with prepended blank. /*denom=*/seqDenoms[b], /*logProbs=*/seqlogProbs[b]); } return SUCCESS; } template <typename DTYPE> DTYPE ComputeAlphaOneSequence( const Options& options, TensorView<const LogProbs<DTYPE>>& logProbs, int srcLen, int tgtLen, TensorView<DTYPE>& alpha) { const int& T = srcLen; const int& U = tgtLen; alpha({0, 0}) = DTYPE(0); for (int t = 1; t < T; ++t) { // u == 0. alpha({t, 0}) = alpha({t - 1, 0}) + logProbs({t - 1, 0}).skip(); } for (int u = 1; u < U; ++u) { // t == 0. alpha({0, u}) = alpha({0, u - 1}) + logProbs({0, u - 1}).emit(); } for (int t = 1; t < T; ++t) { for (int u = 1; u < U; ++u) { alpha({t, u}) = math::lse( alpha({t - 1, u}) + logProbs({t - 1, u}).skip(), alpha({t, u - 1}) + logProbs({t, u - 1}).emit()); } } DTYPE forward_score = alpha({T - 1, U - 1}) + logProbs({T - 1, U - 1}).skip(); return forward_score; } template <typename DTYPE> DTYPE ComputeBetaOneSequence( const Options& options, TensorView<const LogProbs<DTYPE>>& logProbs, int srcLen, int tgtLen, TensorView<DTYPE>& beta) { const int& T = srcLen; const int& U = tgtLen; beta({T - 1, U - 1}) = logProbs({T - 1, U - 1}).skip(); for (int t = T - 2; t >= 0; --t) { // u == U - 1. beta({t, U - 1}) = beta({t + 1, U - 1}) + logProbs({t, U - 1}).skip(); } for (int u = U - 2; u >= 0; --u) { // t == T - 1. beta({T - 1, u}) = beta({T - 1, u + 1}) + logProbs({T - 1, u}).emit(); } for (int t = T - 2; t >= 0; --t) { for (int u = U - 2; u >= 0; --u) { beta({t, u}) = math::lse( beta({t + 1, u}) + logProbs({t, u}).skip(), beta({t, u + 1}) + logProbs({t, u}).emit()); } } DTYPE backward_score = beta({0, 0}); return backward_score; } template <typename DTYPE> DTYPE ComputeAlphaOrBetaOneSequence( int thread, const Options& options, TensorView<const LogProbs<DTYPE>>& logProbs, int srcLen, int tgtLen, TensorView<DTYPE>& alpha, TensorView<DTYPE>& beta) { if (thread & 1) { return ComputeAlphaOneSequence<DTYPE>( /*options=*/options, /*logProbs=*/logProbs, /*srcLen=*/srcLen, /*tgtLen=*/tgtLen, /*alpha=*/alpha); } else { return ComputeBetaOneSequence<DTYPE>( /*options=*/options, /*logProbs=*/logProbs, /*srcLen=*/srcLen, /*tgtLen=*/tgtLen, /*beta=*/beta); } } template <typename DTYPE, typename CAST_DTYPE> void ComputeAlphasBetas( const Options& options, const CAST_DTYPE* logProbs, const int* srcLengths, const int* tgtLengths, CAST_DTYPE* alphas, CAST_DTYPE* betas, DTYPE* costs) { std::vector<TensorView<const LogProbs<CAST_DTYPE>>> seqlogProbs; std::vector<TensorView<CAST_DTYPE>> seq_alphas; std::vector<TensorView<CAST_DTYPE>> seq_betas; const int& B = options.batchSize_; const int& maxT = options.maxSrcLen_; const int& maxU = options.maxTgtLen_; for (int b = 0; b < B; ++b) { seqlogProbs.push_back(TensorView<const LogProbs<CAST_DTYPE>>( {maxT, maxU}, reinterpret_cast<LogProbs<CAST_DTYPE>*>( const_cast<CAST_DTYPE*>(logProbs)) + b * maxT * maxU)); seq_alphas.push_back( TensorView<CAST_DTYPE>({maxT, maxU}, alphas + b * maxT * maxU)); seq_betas.push_back( TensorView<CAST_DTYPE>({maxT, maxU}, betas + b * maxT * maxU)); } std::vector<CAST_DTYPE> scores(B << 1); //#pragma omp parallel for for (int t = 0; t < (B << 1); ++t) { // use max 2 * B threads. int i = (t >> 1); scores[t] = ComputeAlphaOrBetaOneSequence<CAST_DTYPE>( /*thread=*/t, /*options=*/options, /*logProbs=*/seqlogProbs[i], /*srcLen=*/srcLengths[i], /*tgtLen=*/tgtLengths[i] + 1, // with prepended blank. /*alpha=*/seq_alphas[i], /*beta=*/seq_betas[i]); } for (int b = 0; b < B; ++b) { costs[b] = -scores[b << 1]; } } template <typename DTYPE, typename CAST_DTYPE> void ComputeGradientsOneSequence( const Options& options, TensorView<const DTYPE>& logits, const int* targets, int srcLen, int tgtLen, TensorView<const CAST_DTYPE>& denom, TensorView<const CAST_DTYPE>& alpha, TensorView<const CAST_DTYPE>& beta, TensorView<DTYPE>& gradients) { // don't set gradients to zero to here as gradients might reuse memory from // logits const int& T = srcLen; const int& U = tgtLen; const int& D = options.numTargets_; const int& blank = options.blank_; const CAST_DTYPE clamp = options.clamp_; CAST_DTYPE cost = -beta({0, 0}); // Note - below gradient is different from numpy_transducer, since we // compute log_softmax more efficiently within the loss, to save memory The // details of the below implementation / equations can be found in Sec 3.2 // (function merging) in below paper: // https://www.microsoft.com/en-us/research/uploads/prod/2019/10/RNNT.pdf for (int t = 0; t < T; ++t) { for (int u = 0; u < U; ++u) { CAST_DTYPE c = alpha({t, u}) + cost - denom({t, u}); for (int d = 0; d < D; ++d) { CAST_DTYPE g = CAST_DTYPE(logits({t, u, d})) + c; if (d == blank && t == T - 1 && u == U - 1) { // last blank transition. gradients({t, u, d}) = std::exp(g + beta({t, u})) - std::exp(g); } else if (d == blank && t < T - 1) { gradients({t, u, d}) = std::exp(g + beta({t, u})) - std::exp(g + beta({t + 1, u})); } else if (u < U - 1 && d == targets[u]) { gradients({t, u, d}) = std::exp(g + beta({t, u})) - std::exp(g + beta({t, u + 1})); } else { gradients({t, u, d}) = std::exp(g + beta({t, u})); } if (clamp > 0) { gradients({t, u, d}) = math::min(CAST_DTYPE(gradients({t, u, d})), clamp); gradients({t, u, d}) = math::max(CAST_DTYPE(gradients({t, u, d})), -clamp); } } } } // zero out the rest of the gradients, necessary when reusing logits memory // check the memory location to see if it's necessary if (&gradients({0, 0, 0}) == &logits({0, 0, 0})) { const int& maxT = options.maxSrcLen_; const int& maxU = options.maxTgtLen_; for (int t = T; t < maxT; ++t) { for (int u = 0; u < maxU; ++u) { for (int d = 0; d < D; ++d) { gradients({t, u, d}) = 0.; } } } for (int t = 0; t < T; ++t) { for (int u = U; u < maxU; ++u) { for (int d = 0; d < D; ++d) { gradients({t, u, d}) = 0.; } } } } } template <typename DTYPE, typename CAST_DTYPE> void ComputeGradients( const Options& options, const DTYPE* logits, const int* targets, const int* srcLengths, const int* tgtLengths, const CAST_DTYPE* denominators, const CAST_DTYPE* alphas, const CAST_DTYPE* betas, DTYPE* gradients) { std::vector<TensorView<const DTYPE>> seqLogits; std::vector<const int*> seqTargets; std::vector<TensorView<const CAST_DTYPE>> seqDenoms; std::vector<TensorView<const CAST_DTYPE>> seq_alphas; std::vector<TensorView<const CAST_DTYPE>> seq_betas; std::vector<TensorView<DTYPE>> seq_gradients; const int& B = options.batchSize_; const int& maxT = options.maxSrcLen_; const int& maxU = options.maxTgtLen_; const int& D = options.numTargets_; for (int b = 0; b < B; ++b) { seqLogits.push_back( TensorView<const DTYPE>({maxT, maxU, D}, logits + b * maxT * maxU * D)); seqTargets.push_back(targets + b * (maxU - 1)); seqDenoms.push_back(TensorView<const CAST_DTYPE>( {maxT, maxU}, denominators + b * maxT * maxU)); seq_alphas.push_back( TensorView<const CAST_DTYPE>({maxT, maxU}, alphas + b * maxT * maxU)); seq_betas.push_back( TensorView<const CAST_DTYPE>({maxT, maxU}, betas + b * maxT * maxU)); seq_gradients.push_back( TensorView<DTYPE>({maxT, maxU, D}, gradients + b * maxT * maxU * D)); } //#pragma omp parallel for for (int b = 0; b < B; ++b) { // use max 2 * B threads. ComputeGradientsOneSequence<DTYPE, CAST_DTYPE>( /*options=*/options, /*logits=*/seqLogits[b], /*targets=*/seqTargets[b], /*srcLen=*/srcLengths[b], /*tgtLen=*/tgtLengths[b] + 1, // with prepended blank. /*denom=*/seqDenoms[b], /*alpha=*/seq_alphas[b], /*beta=*/seq_betas[b], /*gradients=*/seq_gradients[b]); } } template <typename DTYPE, typename CAST_DTYPE> void ComputeAlphas( const Options& options, const CAST_DTYPE* logProbs, const int* srcLengths, const int* tgtLengths, CAST_DTYPE* alphas) { std::vector<TensorView<const LogProbs<CAST_DTYPE>>> seqlogProbs; std::vector<TensorView<CAST_DTYPE>> seq_alphas; const int& B = options.batchSize_; const int& maxT = options.maxSrcLen_; const int& maxU = options.maxTgtLen_; for (int b = 0; b < B; ++b) { seqlogProbs.push_back(TensorView<const LogProbs<CAST_DTYPE>>( {maxT, maxU}, reinterpret_cast<LogProbs<CAST_DTYPE>*>( const_cast<CAST_DTYPE*>(logProbs)) + b * maxT * maxU)); seq_alphas.push_back( TensorView<CAST_DTYPE>({maxT, maxU}, alphas + b * maxT * maxU)); } std::vector<CAST_DTYPE> scores(B << 1); //#pragma omp parallel for for (int i = 0; i < B; ++i) { // use max 2 * B threads. ComputeAlphaOneSequence<DTYPE>( options, /*logProbs=*/seqlogProbs[i], /*srcLen=*/srcLengths[i], /*tgtLen=*/tgtLengths[i] + 1, // with prepended blank. /*alpha=*/seq_alphas[i]); } } template <typename DTYPE, typename CAST_DTYPE> void ComputeBetas( const Options& options, const CAST_DTYPE* logProbs, const int* srcLengths, const int* tgtLengths, CAST_DTYPE* costs, CAST_DTYPE* betas) { std::vector<TensorView<const LogProbs<CAST_DTYPE>>> seqlogProbs; std::vector<TensorView<CAST_DTYPE>> seq_betas; const int& B = options.batchSize_; const int& maxT = options.maxSrcLen_; const int& maxU = options.maxTgtLen_; for (int b = 0; b < B; ++b) { seqlogProbs.push_back(TensorView<const LogProbs<CAST_DTYPE>>( {maxT, maxU}, reinterpret_cast<LogProbs<CAST_DTYPE>*>( const_cast<CAST_DTYPE*>(logProbs)) + b * maxT * maxU)); seq_betas.push_back( TensorView<CAST_DTYPE>({maxT, maxU}, betas + b * maxT * maxU)); } std::vector<CAST_DTYPE> scores(B << 1); //#pragma omp parallel for for (int i = 0; i < B; ++i) { // use max 2 * B threads. ComputeBetaOneSequence<DTYPE>( options, /*logProbs=*/seqlogProbs[i], /*srcLen=*/srcLengths[i], /*tgtLen=*/tgtLengths[i] + 1, // with prepended blank. /*betas=*/seq_betas[i]); } } } // namespace cpu } // namespace rnnt } // namespace torchaudio
rose_v1_matrixVectormultiply.c
/* Naive matrix-vector multiplication By C. Liao */ #define N 1000 #include <omp.h> int i; int j; int k; double a[1000][1000]; double v[1000]; double v_out[1000]; int mmm() { #pragma omp parallel for private (i,j) for (i = 0; i <= 999; i += 1) { float sum = 0.0; #pragma omp parallel for private (j) reduction (+:sum) for (j = 0; j <= 999; j += 1) { sum += a[i][j] * v[j]; } v_out[i] = sum; } return 0; }
GB_binop__band_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__band_uint64 // A.*B function (eWiseMult): GB_AemultB__band_uint64 // A*D function (colscale): GB_AxD__band_uint64 // D*A function (rowscale): GB_DxB__band_uint64 // C+=B function (dense accum): GB_Cdense_accumB__band_uint64 // C+=b function (dense accum): GB_Cdense_accumb__band_uint64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__band_uint64 // C=scalar+B GB_bind1st__band_uint64 // C=scalar+B' GB_bind1st_tran__band_uint64 // C=A+scalar GB_bind2nd__band_uint64 // C=A'+scalar GB_bind2nd_tran__band_uint64 // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij) & (bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x) & (y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BAND || GxB_NO_UINT64 || GxB_NO_BAND_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__band_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__band_uint64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__band_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__band_uint64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__band_uint64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__band_uint64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__band_uint64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__band_uint64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t bij = Bx [p] ; Cx [p] = (x) & (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__band_uint64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; Cx [p] = (aij) & (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (x) & (aij) ; \ } GrB_Info GB_bind1st_tran__band_uint64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (aij) & (y) ; \ } GrB_Info GB_bind2nd_tran__band_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nodal_residualbased_elimination_builder_and_solver_continuity.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi, Alessandro Franci // // #if !defined(KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_CONTINUITY ) #define KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_CONTINUITY /* System includes */ #include <set> #ifdef _OPENMP #include <omp.h> #endif /* External includes */ // #define USE_GOOGLE_HASH #ifdef USE_GOOGLE_HASH #include "sparsehash/dense_hash_set" //included in external libraries #else #include <unordered_set> #endif /* Project includes */ #include "utilities/timer.h" #include "includes/define.h" #include "includes/key_hash.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" #include "includes/model_part.h" #include "pfem_fluid_dynamics_application_variables.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class NodalResidualBasedEliminationBuilderAndSolverContinuity * @ingroup KratosCore * @brief Current class provides an implementation for standard builder and solving operations. * @details The RHS is constituted by the unbalanced loads (residual) * Degrees of freedom are reordered putting the restrained degrees of freedom at * the end of the system ordered in reverse order with respect to the DofSet. * Imposition of the dirichlet conditions is naturally dealt with as the residual already contains * this information. * Calculation of the reactions involves a cost very similiar to the calculation of the total residual * @author Riccardo Rossi */ template<class TSparseSpace, class TDenseSpace, //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class NodalResidualBasedEliminationBuilderAndSolverContinuity : public BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver > { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(NodalResidualBasedEliminationBuilderAndSolverContinuity); typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef Node<3> NodeType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; typedef typename BaseType::ElementsContainerType ElementsContainerType; typedef Vector VectorType; ///@} ///@name Life Cycle ///@{ /** Constructor. */ NodalResidualBasedEliminationBuilderAndSolverContinuity( typename TLinearSolver::Pointer pNewLinearSystemSolver) : BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver >(pNewLinearSystemSolver) { // KRATOS_INFO("NodalResidualBasedEliminationBuilderAndSolverContinuity") << "Using the standard builder and solver " << std::endl; } /** Destructor. */ ~NodalResidualBasedEliminationBuilderAndSolverContinuity() override { } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ void BuildNodally( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double pressure=0; double deltaPressure=0; double meanMeshSize=0; double characteristicLength=0; double density=0; double nodalVelocityNorm=0; double tauStab=0; double dNdXi=0; double dNdYi=0; double dNdZi=0; double dNdXj=0; double dNdYj=0; double dNdZj=0; unsigned int firstRow=0; unsigned int firstCol=0; /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(),NodesBegin,NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType& neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() +1 ; if(neighSize>1) { const double nodalVolume=itNode->FastGetSolutionStepValue(NODAL_VOLUME); LHS_Contribution= ZeroMatrix(neighSize,neighSize); RHS_Contribution= ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff=itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear=itNode->FastGetSolutionStepValue(YIELD_SHEAR); if(yieldShear>0){ double adaptiveExponent=itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate=itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent=-adaptiveExponent*equivalentStrainRate; if(equivalentStrainRate!=0){ deviatoricCoeff+=(yieldShear/equivalentStrainRate)*(1-exp(exponent)); } if(equivalentStrainRate<0.00001 && yieldShear!=0 && adaptiveExponent!=0){ // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff=adaptiveExponent*yieldShear; } } if(deviatoricCoeff>0.1){ deviatoricCoeff=0.1; } double volumetricCoeff=timeInterval*itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure=itNode->FastGetSolutionStepValue(PRESSURE,0)-itNode->FastGetSolutionStepValue(PRESSURE,1); LHS_Contribution(0,0)+= nodalVolume/volumetricCoeff; RHS_Contribution[0] += -deltaPressure*nodalVolume/volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE)*nodalVolume; const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0]=itNode->GetDof(PRESSURE,xDofPos).EquationId(); for (unsigned int i = 0; i< neighb_nodes.size(); i++) { EquationId[i+1]=neighb_nodes[i].GetDof(PRESSURE,xDofPos).EquationId(); } firstRow=0; firstCol=0; meanMeshSize=itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); characteristicLength=1.0*meanMeshSize; density=itNode->FastGetSolutionStepValue(DENSITY); /* double tauStab=1.0/(8.0*deviatoricCoeff/(meanMeshSize*meanMeshSize)+2.0*density/timeInterval); */ if(dimension==2){ nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y)); }else if(dimension==3){ nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y) + itNode->FastGetSolutionStepValue(VELOCITY_Z)*itNode->FastGetSolutionStepValue(VELOCITY_Z)); } tauStab= 1.0 * (characteristicLength * characteristicLength * timeInterval) / ( density * nodalVelocityNorm * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval ); itNode->FastGetSolutionStepValue(NODAL_TAU)=tauStab; /* std::cout<<"tauStab= "<<tauStab<<std::endl; */ LHS_Contribution(0,0)+= +nodalVolume*tauStab*density/(volumetricCoeff*timeInterval); RHS_Contribution[0] += -nodalVolume*tauStab*density/(volumetricCoeff*timeInterval)*(deltaPressure-itNode->FastGetSolutionStepValue(PRESSURE_VELOCITY,0)*timeInterval); if(itNode->Is(FREE_SURFACE)){ // // double nodalFreesurfaceArea=itNode->FastGetSolutionStepValue(NODAL_FREESURFACE_AREA); // /* LHS_Contribution(0,0) += + 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize; */ // /* RHS_Contribution[0] += - 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize * itNode->FastGetSolutionStepValue(PRESSURE,0); */ LHS_Contribution(0,0) += + 4.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize); RHS_Contribution[0] += - 4.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE,0); const array_1d<double, 3> &Normal = itNode->FastGetSolutionStepValue(NORMAL); Vector& SpatialDefRate=itNode->FastGetSolutionStepValue(NODAL_SPATIAL_DEF_RATE); array_1d<double, 3> nodalAcceleration= 0.5*(itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION,1); /* nodalAcceleration= (itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval; */ double nodalNormalAcceleration=0; double nodalNormalProjDefRate=0; if(dimension==2){ nodalNormalProjDefRate=Normal[0]*SpatialDefRate[0]*Normal[0] + Normal[1]*SpatialDefRate[1]*Normal[1] + 2*Normal[0]*SpatialDefRate[2]*Normal[1]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X,1) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1); */ // nodalNormalAcceleration=(0.5*(itNode->FastGetSolutionStepValue(VELOCITY_X,0)-itNode->FastGetSolutionStepValue(VELOCITY_X,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_X,1))*Normal[0] + // (0.5*(itNode->FastGetSolutionStepValue(VELOCITY_Y,0)-itNode->FastGetSolutionStepValue(VELOCITY_Y,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1))*Normal[1]; nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1]; }else if(dimension==3){ nodalNormalProjDefRate=Normal[0]*SpatialDefRate[0]*Normal[0] + Normal[1]*SpatialDefRate[1]*Normal[1] + Normal[2]*SpatialDefRate[2]*Normal[2] + 2*Normal[0]*SpatialDefRate[3]*Normal[1] + 2*Normal[0]*SpatialDefRate[4]*Normal[2] + 2*Normal[1]*SpatialDefRate[5]*Normal[2]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y) + Normal[2]*itNode->FastGetSolutionStepValue(ACCELERATION_Z); */ /* nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1] + Normal[2]*nodalAcceleration[2]; */ } // RHS_Contribution[0] += tauStab * (density*nodalNormalAcceleration - 4.0*deviatoricCoeff*nodalNormalProjDefRate/meanMeshSize) * nodalFreesurfaceArea; double accelerationContribution=2.0*density*nodalNormalAcceleration/meanMeshSize; double deviatoricContribution=8.0*deviatoricCoeff*nodalNormalProjDefRate/(meanMeshSize*meanMeshSize); RHS_Contribution[0] += 1.0* tauStab * (accelerationContribution - deviatoricContribution) * nodalVolume; } array_1d<double, 3 >& VolumeAcceleration = itNode->FastGetSolutionStepValue(VOLUME_ACCELERATION); // double posX= itNode->X(); // double posY= itNode->Y(); // double coeffX =(12.0-24.0*posY)*pow(posX,4); // coeffX += (-24.0+48.0*posY)*pow(posX,3); // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // double coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); for (unsigned int i = 0; i< neighSize; i++) { dNdXi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol]; dNdYi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol+1]; if(i!=0){ // i==0 of EquationIs has been already filled with the master node (that is not included in neighb_nodes). The next is stored for i+1 EquationId[i]=neighb_nodes[i-1].GetDof(PRESSURE,xDofPos).EquationId(); // at i==0 density and volume acceleration are taken from the master node density= neighb_nodes[i-1].FastGetSolutionStepValue(DENSITY); // VolumeAcceleration = neighb_nodes[i-1].FastGetSolutionStepValue(VOLUME_ACCELERATION); // // posX= neighb_nodes[i-1].X(); // // posY= neighb_nodes[i-1].Y(); // // coeffX =(12.0-24.0*posY)*pow(posX,4); // // coeffX += (-24.0+48.0*posY)*pow(posX,3); // // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // // coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); } if(dimension==2){ // RHS_Contribution[i] += - tauStab * density * (dNdXi* VolumeAcceleration[0]*coeffX + dNdYi* VolumeAcceleration[1]*coeffY) * nodalVolume; RHS_Contribution[i] += - tauStab * density * (dNdXi* VolumeAcceleration[0] + dNdYi* VolumeAcceleration[1]) * nodalVolume; } else if(dimension==3){ dNdZi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol+2]; RHS_Contribution[i] += - tauStab * density * (dNdXi* VolumeAcceleration[0] + dNdYi* VolumeAcceleration[1] + dNdZi* VolumeAcceleration[2]) * nodalVolume; } firstRow=0; for (unsigned int j = 0; j< neighSize; j++) { dNdXj=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow]; dNdYj=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow+1]; // double Vx=itNode->FastGetSolutionStepValue(VELOCITY_X,0); // double Vy=itNode->FastGetSolutionStepValue(VELOCITY_Y,0); if(j!=0){ pressure=neighb_nodes[j-1].FastGetSolutionStepValue(PRESSURE,0); // Vx= neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X,0); // Vy= neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y,0); // meanMeshSize=neighb_nodes[j-1].FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); // characteristicLength=2.0*meanMeshSize; // density=neighb_nodes[j-1].FastGetSolutionStepValue(DENSITY); // if(dimension==2){ // nodalVelocityNorm= sqrt(neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X) + // neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y)); // }else if(dimension==3){ // nodalVelocityNorm=sqrt(neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_X) + // neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Y) + // neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Z)*neighb_nodes[j-1].FastGetSolutionStepValue(VELOCITY_Z)); // } }else{ pressure=itNode->FastGetSolutionStepValue(PRESSURE,0); // meanMeshSize=itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); // characteristicLength=2.0*meanMeshSize; // density=itNode->FastGetSolutionStepValue(DENSITY); // if(dimension==2){ // nodalVelocityNorm= sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + // itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y)); // }else if(dimension==3){ // nodalVelocityNorm=sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + // itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y) + // itNode->FastGetSolutionStepValue(VELOCITY_Z)*itNode->FastGetSolutionStepValue(VELOCITY_Z)); // } } // tauStab= 1.0 * (characteristicLength * characteristicLength * timeInterval) / ( density * nodalVelocityNorm * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval ); if(dimension==2){ // // ////////////////// Laplacian term for LHS LHS_Contribution(i,j)+= + tauStab * (dNdXi*dNdXj + dNdYi*dNdYj) * nodalVolume ; // // ////////////////// Laplacian term L_ij*P_j for RHS RHS_Contribution[i] += - tauStab * (dNdXi*dNdXj + dNdYi*dNdYj) * nodalVolume * pressure; // RHS_Contribution[i] += (dNdXj*Vx + dNdYj*Vy)*nodalVolume/3.0; // LHS_Contribution(i,j)+= nodalVolume/volumetricCoeff/(1.0+double(neighSize)); // if(i==j){ // RHS_Contribution[i] += (-deltaPressure/volumetricCoeff )*nodalVolume; // } } else if(dimension==3){ dNdZj=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow+2]; ////////////////// Laplacian term for LHS LHS_Contribution(i,j) += + tauStab * (dNdXi*dNdXj + dNdYi*dNdYj + dNdZi*dNdZj) * nodalVolume; ////////////////// Laplacian term L_ij*P_j for RHS RHS_Contribution[i] += - tauStab * (dNdXi*dNdXj + dNdYi*dNdYj + dNdZi*dNdZj) * nodalVolume * pressure; } firstRow+=dimension; } firstCol+=dimension; } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } KRATOS_CATCH("") } void BuildNodallyUnlessLaplacian( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double deltaPressure=0; double meanMeshSize=0; double characteristicLength=0; double density=0; double nodalVelocityNorm=0; double tauStab=0; double dNdXi=0; double dNdYi=0; double dNdZi=0; unsigned int firstCol=0; /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(),NodesBegin,NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType& neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() +1 ; if(neighSize>1) { const double nodalVolume=itNode->FastGetSolutionStepValue(NODAL_VOLUME); LHS_Contribution= ZeroMatrix(neighSize,neighSize); RHS_Contribution= ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff=itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear=itNode->FastGetSolutionStepValue(YIELD_SHEAR); if(yieldShear>0){ double adaptiveExponent=itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate=itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent=-adaptiveExponent*equivalentStrainRate; if(equivalentStrainRate!=0){ deviatoricCoeff+=(yieldShear/equivalentStrainRate)*(1-exp(exponent)); } if(equivalentStrainRate<0.00001 && yieldShear!=0 && adaptiveExponent!=0){ // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff=adaptiveExponent*yieldShear; } } if(deviatoricCoeff>0.1){ deviatoricCoeff=0.1; } double volumetricCoeff=timeInterval*itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure=itNode->FastGetSolutionStepValue(PRESSURE,0)-itNode->FastGetSolutionStepValue(PRESSURE,1); LHS_Contribution(0,0)+= nodalVolume/volumetricCoeff; RHS_Contribution[0] += -deltaPressure*nodalVolume/volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE)*nodalVolume; const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0]=itNode->GetDof(PRESSURE,xDofPos).EquationId(); for (unsigned int i = 0; i< neighb_nodes.size(); i++) { EquationId[i+1]=neighb_nodes[i].GetDof(PRESSURE,xDofPos).EquationId(); } firstCol=0; meanMeshSize=itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); characteristicLength=1.0*meanMeshSize; density=itNode->FastGetSolutionStepValue(DENSITY); /* double tauStab=1.0/(8.0*deviatoricCoeff/(meanMeshSize*meanMeshSize)+2.0*density/timeInterval); */ if(dimension==2){ nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y)); } else if(dimension==3){ nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y) + itNode->FastGetSolutionStepValue(VELOCITY_Z)*itNode->FastGetSolutionStepValue(VELOCITY_Z)); } tauStab= 1.0 * (characteristicLength * characteristicLength * timeInterval) / ( density * nodalVelocityNorm * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval ); itNode->FastGetSolutionStepValue(NODAL_TAU)=tauStab; LHS_Contribution(0,0)+= +nodalVolume*tauStab*density/(volumetricCoeff*timeInterval); RHS_Contribution[0] += -nodalVolume*tauStab*density/(volumetricCoeff*timeInterval)*(deltaPressure-itNode->FastGetSolutionStepValue(PRESSURE_VELOCITY,0)*timeInterval); if(itNode->Is(FREE_SURFACE)){ // // double nodalFreesurfaceArea=itNode->FastGetSolutionStepValue(NODAL_FREESURFACE_AREA); // /* LHS_Contribution(0,0) += + 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize; */ // /* RHS_Contribution[0] += - 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize * itNode->FastGetSolutionStepValue(PRESSURE,0); */ LHS_Contribution(0,0) += + 4.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize); RHS_Contribution[0] += - 4.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE,0); array_1d<double, 3> &Normal = itNode->FastGetSolutionStepValue(NORMAL); Vector& SpatialDefRate=itNode->FastGetSolutionStepValue(NODAL_SPATIAL_DEF_RATE); array_1d<double, 3> nodalAcceleration= 0.5*(itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION,1); /* nodalAcceleration= (itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval; */ double nodalNormalAcceleration=0; double nodalNormalProjDefRate=0; if(dimension==2){ nodalNormalProjDefRate=Normal[0]*SpatialDefRate[0]*Normal[0] + Normal[1]*SpatialDefRate[1]*Normal[1] + 2*Normal[0]*SpatialDefRate[2]*Normal[1]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X,1) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1); */ // nodalNormalAcceleration=(0.5*(itNode->FastGetSolutionStepValue(VELOCITY_X,0)-itNode->FastGetSolutionStepValue(VELOCITY_X,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_X,1))*Normal[0] + // (0.5*(itNode->FastGetSolutionStepValue(VELOCITY_Y,0)-itNode->FastGetSolutionStepValue(VELOCITY_Y,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1))*Normal[1]; nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1]; }else if(dimension==3){ nodalNormalProjDefRate=Normal[0]*SpatialDefRate[0]*Normal[0] + Normal[1]*SpatialDefRate[1]*Normal[1] + Normal[2]*SpatialDefRate[2]*Normal[2] + 2*Normal[0]*SpatialDefRate[3]*Normal[1] + 2*Normal[0]*SpatialDefRate[4]*Normal[2] + 2*Normal[1]*SpatialDefRate[5]*Normal[2]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y) + Normal[2]*itNode->FastGetSolutionStepValue(ACCELERATION_Z); */ /* nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1] + Normal[2]*nodalAcceleration[2]; */ } // RHS_Contribution[0] += tauStab * (density*nodalNormalAcceleration - 4.0*deviatoricCoeff*nodalNormalProjDefRate/meanMeshSize) * nodalFreesurfaceArea; double accelerationContribution=2.0*density*nodalNormalAcceleration/meanMeshSize; double deviatoricContribution=8.0*deviatoricCoeff*nodalNormalProjDefRate/(meanMeshSize*meanMeshSize); RHS_Contribution[0] += 1.0* tauStab * (accelerationContribution - deviatoricContribution) * nodalVolume; } array_1d<double, 3 >& VolumeAcceleration = itNode->FastGetSolutionStepValue(VOLUME_ACCELERATION); // double posX= itNode->X(); // double posY= itNode->Y(); // double coeffX =(12.0-24.0*posY)*pow(posX,4); // coeffX += (-24.0+48.0*posY)*pow(posX,3); // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // double coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); for (unsigned int i = 0; i< neighSize; i++) { dNdXi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol]; dNdYi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol+1]; if(i!=0){ // i==0 of EquationIs has been already filled with the master node (that is not included in neighb_nodes). The next is stored for i+1 EquationId[i]=neighb_nodes[i-1].GetDof(PRESSURE,xDofPos).EquationId(); // at i==0 density and volume acceleration are taken from the master node density= neighb_nodes[i-1].FastGetSolutionStepValue(DENSITY); // // VolumeAcceleration = neighb_nodes[i-1].FastGetSolutionStepValue(VOLUME_ACCELERATION); // // posX= neighb_nodes[i-1].X(); // // posY= neighb_nodes[i-1].Y(); // // coeffX =(12.0-24.0*posY)*pow(posX,4); // // coeffX += (-24.0+48.0*posY)*pow(posX,3); // // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // // coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); } if(dimension==2){ // RHS_Contribution[i] += - tauStab * density * (dNdXi* VolumeAcceleration[0]*coeffX + dNdYi* VolumeAcceleration[1]*coeffY) * nodalVolume; RHS_Contribution[i] += - tauStab * density * (dNdXi* VolumeAcceleration[0] + dNdYi* VolumeAcceleration[1]) * nodalVolume; } else if(dimension==3){ dNdZi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol+2]; RHS_Contribution[i] += - tauStab * density * (dNdXi* VolumeAcceleration[0] + dNdYi* VolumeAcceleration[1] + dNdZi* VolumeAcceleration[2]) * nodalVolume; } firstCol+=dimension; } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } KRATOS_CATCH("") } void BuildNodallyNoVolumetricStabilizedTerms( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double deltaPressure=0; double meanMeshSize=0; double characteristicLength=0; double density=0; double nodalVelocityNorm=0; double tauStab=0; /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(),NodesBegin,NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType& neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() +1 ; if(neighSize>1) { const double nodalVolume=itNode->FastGetSolutionStepValue(NODAL_VOLUME); LHS_Contribution= ZeroMatrix(neighSize,neighSize); RHS_Contribution= ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff=itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear=itNode->FastGetSolutionStepValue(YIELD_SHEAR); if(yieldShear>0){ double adaptiveExponent=itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate=itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent=-adaptiveExponent*equivalentStrainRate; if(equivalentStrainRate!=0){ deviatoricCoeff+=(yieldShear/equivalentStrainRate)*(1-exp(exponent)); } if(equivalentStrainRate<0.00001 && yieldShear!=0 && adaptiveExponent!=0){ // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff=adaptiveExponent*yieldShear; } } if(deviatoricCoeff>0.1){ deviatoricCoeff=0.1; } double volumetricCoeff=timeInterval*itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure=itNode->FastGetSolutionStepValue(PRESSURE,0)-itNode->FastGetSolutionStepValue(PRESSURE,1); LHS_Contribution(0,0)+= nodalVolume/volumetricCoeff; RHS_Contribution[0] += -deltaPressure*nodalVolume/volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE)*nodalVolume; const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0]=itNode->GetDof(PRESSURE,xDofPos).EquationId(); for (unsigned int i = 0; i< neighb_nodes.size(); i++) { EquationId[i+1]=neighb_nodes[i].GetDof(PRESSURE,xDofPos).EquationId(); } meanMeshSize=itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); characteristicLength=1.0*meanMeshSize; density=itNode->FastGetSolutionStepValue(DENSITY); /* double tauStab=1.0/(8.0*deviatoricCoeff/(meanMeshSize*meanMeshSize)+2.0*density/timeInterval); */ if(dimension==2){ nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y)); } else if(dimension==3){ nodalVelocityNorm = sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y) + itNode->FastGetSolutionStepValue(VELOCITY_Z)*itNode->FastGetSolutionStepValue(VELOCITY_Z)); } tauStab= 1.0 * (characteristicLength * characteristicLength * timeInterval) / ( density * nodalVelocityNorm * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval ); itNode->FastGetSolutionStepValue(NODAL_TAU)=tauStab; LHS_Contribution(0,0)+= +nodalVolume*tauStab*density/(volumetricCoeff*timeInterval); RHS_Contribution[0] += -nodalVolume*tauStab*density/(volumetricCoeff*timeInterval)*(deltaPressure-itNode->FastGetSolutionStepValue(PRESSURE_VELOCITY,0)*timeInterval); if(itNode->Is(FREE_SURFACE)){ // // double nodalFreesurfaceArea=itNode->FastGetSolutionStepValue(NODAL_FREESURFACE_AREA); // /* LHS_Contribution(0,0) += + 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize; */ // /* RHS_Contribution[0] += - 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize * itNode->FastGetSolutionStepValue(PRESSURE,0); */ LHS_Contribution(0,0) += + 4.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize); RHS_Contribution[0] += - 4.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE,0); array_1d<double, 3> &Normal = itNode->FastGetSolutionStepValue(NORMAL); Vector& SpatialDefRate=itNode->FastGetSolutionStepValue(NODAL_SPATIAL_DEF_RATE); array_1d<double, 3> nodalAcceleration= 0.5*(itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION,1); /* nodalAcceleration= (itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval; */ double nodalNormalAcceleration=0; double nodalNormalProjDefRate=0; if(dimension==2){ nodalNormalProjDefRate=Normal[0]*SpatialDefRate[0]*Normal[0] + Normal[1]*SpatialDefRate[1]*Normal[1] + 2*Normal[0]*SpatialDefRate[2]*Normal[1]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X,1) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1); */ // nodalNormalAcceleration=(0.5*(itNode->FastGetSolutionStepValue(VELOCITY_X,0)-itNode->FastGetSolutionStepValue(VELOCITY_X,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_X,1))*Normal[0] + // (0.5*(itNode->FastGetSolutionStepValue(VELOCITY_Y,0)-itNode->FastGetSolutionStepValue(VELOCITY_Y,1))/timeInterval+0.5*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1))*Normal[1]; nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1]; }else if(dimension==3){ nodalNormalProjDefRate=Normal[0]*SpatialDefRate[0]*Normal[0] + Normal[1]*SpatialDefRate[1]*Normal[1] + Normal[2]*SpatialDefRate[2]*Normal[2] + 2*Normal[0]*SpatialDefRate[3]*Normal[1] + 2*Normal[0]*SpatialDefRate[4]*Normal[2] + 2*Normal[1]*SpatialDefRate[5]*Normal[2]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y) + Normal[2]*itNode->FastGetSolutionStepValue(ACCELERATION_Z); */ /* nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1] + Normal[2]*nodalAcceleration[2]; */ } // RHS_Contribution[0] += tauStab * (density*nodalNormalAcceleration - 4.0*deviatoricCoeff*nodalNormalProjDefRate/meanMeshSize) * nodalFreesurfaceArea; double accelerationContribution=2.0*density*nodalNormalAcceleration/meanMeshSize; double deviatoricContribution=8.0*deviatoricCoeff*nodalNormalProjDefRate/(meanMeshSize*meanMeshSize); RHS_Contribution[0] += 1.0* tauStab * (accelerationContribution - deviatoricContribution) * nodalVolume; } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } KRATOS_CATCH("") } void BuildNodallyNotStabilized( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double deltaPressure=0; /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(),NodesBegin,NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType& neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() +1 ; if(neighSize>1) { const double nodalVolume=itNode->FastGetSolutionStepValue(NODAL_VOLUME); LHS_Contribution= ZeroMatrix(neighSize,neighSize); RHS_Contribution= ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff=itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear=itNode->FastGetSolutionStepValue(YIELD_SHEAR); if(yieldShear>0){ double adaptiveExponent=itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate=itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent=-adaptiveExponent*equivalentStrainRate; if(equivalentStrainRate!=0){ deviatoricCoeff+=(yieldShear/equivalentStrainRate)*(1-exp(exponent)); } if(equivalentStrainRate<0.00001 && yieldShear!=0 && adaptiveExponent!=0){ // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff=adaptiveExponent*yieldShear; } } if(deviatoricCoeff>0.1){ deviatoricCoeff=0.1; } double volumetricCoeff=timeInterval*itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure=itNode->FastGetSolutionStepValue(PRESSURE,0)-itNode->FastGetSolutionStepValue(PRESSURE,1); LHS_Contribution(0,0)+= nodalVolume/volumetricCoeff; RHS_Contribution[0] += -deltaPressure*nodalVolume/volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE)*nodalVolume; const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0]=itNode->GetDof(PRESSURE,xDofPos).EquationId(); for (unsigned int i = 0; i< neighb_nodes.size(); i++) { EquationId[i+1]=neighb_nodes[i].GetDof(PRESSURE,xDofPos).EquationId(); } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } KRATOS_CATCH("") } void BuildAll( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the continuity equation system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; double deltaPressure=0; /* #pragma omp parallel */ // { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(),NodesBegin,NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType& neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); const unsigned int neighSize = neighb_nodes.size() +1 ; if(neighSize>1) { // if (LHS_Contribution.size1() != neighSize) // LHS_Contribution.resize(neighSize, neighSize, false); //false says not to preserve existing storage!! // if (RHS_Contribution.size() != neighSize) // RHS_Contribution.resize(neighSize, false); //false says not to preserve existing storage!! // LHS_Contribution= ZeroMatrix(neighSize,neighSize); // RHS_Contribution= ZeroVector(neighSize); // if (EquationId.size() != neighSize) // EquationId.resize(neighSize, false); if (LHS_Contribution.size1() != 1) LHS_Contribution.resize(1, 1, false); //false says not to preserve existing storage!! if (RHS_Contribution.size() != 1) RHS_Contribution.resize(1, false); //false says not to preserve existing storage!! LHS_Contribution= ZeroMatrix(1,1); RHS_Contribution= ZeroVector(1); if (EquationId.size() != 1) EquationId.resize(1, false); double nodalVolume=itNode->FastGetSolutionStepValue(NODAL_VOLUME); if(nodalVolume>0){ // in interface nodes not in contact with fluid elements the nodal volume is zero double deviatoricCoeff=itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double yieldShear=itNode->FastGetSolutionStepValue(YIELD_SHEAR); if(yieldShear>0){ double adaptiveExponent=itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate=itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent=-adaptiveExponent*equivalentStrainRate; if(equivalentStrainRate!=0){ deviatoricCoeff+=(yieldShear/equivalentStrainRate)*(1-exp(exponent)); } if(equivalentStrainRate<0.00001 && yieldShear!=0 && adaptiveExponent!=0){ // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff=adaptiveExponent*yieldShear; } } if(deviatoricCoeff>0.1){ deviatoricCoeff=0.1; } double volumetricCoeff=timeInterval*itNode->FastGetSolutionStepValue(BULK_MODULUS); deltaPressure=itNode->FastGetSolutionStepValue(PRESSURE,0)-itNode->FastGetSolutionStepValue(PRESSURE,1); LHS_Contribution(0,0)+= nodalVolume/volumetricCoeff; RHS_Contribution[0] += -deltaPressure*nodalVolume/volumetricCoeff; RHS_Contribution[0] += itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE)*nodalVolume; } const unsigned int xDofPos = itNode->GetDofPosition(PRESSURE); EquationId[0]=itNode->GetDof(PRESSURE,xDofPos).EquationId(); #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } //} } // } ElementsArrayType& pElements = rModelPart.Elements(); int number_of_threads = OpenMPUtils::GetNumThreads(); #ifdef _OPENMP int A_size = A.size1(); //creating an array of lock variables of the size of the system matrix std::vector< omp_lock_t > lock_array(A.size1()); for(int i = 0; i<A_size; i++) omp_init_lock(&lock_array[i]); #endif DenseVector<unsigned int> element_partition; CreatePartition(number_of_threads, pElements.size(), element_partition); if (this->GetEchoLevel()>0) { KRATOS_WATCH( number_of_threads ); KRATOS_WATCH( element_partition ); } #pragma omp parallel for firstprivate(number_of_threads) schedule(static,1) for(int k=0; k<number_of_threads; k++) { //contributions to the system LocalSystemMatrixType elementalLHS_Contribution = LocalSystemMatrixType(0,0); LocalSystemVectorType elementalRHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType elementalEquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); typename ElementsArrayType::ptr_iterator it_begin=pElements.ptr_begin()+element_partition[k]; typename ElementsArrayType::ptr_iterator it_end=pElements.ptr_begin()+element_partition[k+1]; unsigned int pos = (rModelPart.Nodes().begin())->GetDofPosition(PRESSURE); // assemble all elements for (typename ElementsArrayType::ptr_iterator it=it_begin; it!=it_end; ++it) { //calculate elemental contribution //(*it)->InitializeNonLinearIteration(CurrentProcessInfo); (*it)->CalculateLocalSystem(elementalLHS_Contribution,elementalRHS_Contribution,CurrentProcessInfo); Geometry< Node<3> >& geom = (*it)->GetGeometry(); if(elementalEquationId.size() != geom.size()) elementalEquationId.resize(geom.size(),false); for(unsigned int i=0; i<geom.size(); i++) elementalEquationId[i] = geom[i].GetDof(PRESSURE,pos).EquationId(); //assemble the elemental contribution #ifdef _OPENMP this->Assemble(A,b,elementalLHS_Contribution,elementalRHS_Contribution,elementalEquationId,lock_array); #else this->Assemble(A,b,elementalLHS_Contribution,elementalRHS_Contribution,elementalEquationId); #endif } } #ifdef _OPENMP for(int i = 0; i<A_size; i++) omp_destroy_lock(&lock_array[i]); #endif KRATOS_CATCH("") } /** * @brief This is a call to the linear system solver * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void SystemSolve( TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b ) override { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else TSparseSpace::SetToZero(Dx); // Prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** *@brief This is a call to the linear system solver (taking into account some physical particularities of the problem) * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector * @param rModelPart The model part of the problem to solve */ void SystemSolveWithPhysics( TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b, ModelPart& rModelPart ) { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //provide physical data as needed if(BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded() ) BaseType::mpLinearSystemSolver->ProvideAdditionalData(A, Dx, b, BaseType::mDofSet, rModelPart); //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else { TSparseSpace::SetToZero(Dx); KRATOS_WARNING_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", rModelPart.GetCommunicator().MyPID() == 0) << "ATTENTION! setting the RHS to zero!" << std::endl; } // Prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the building and solving phase at the same time. * @details It is ideally the fastest and safer function to use when it is possible to solve * just after building * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { KRATOS_TRY Timer::Start("Build"); /* boost::timer c_build_time; */ ///////////////////////////////// ALL NODAL ///////////////////////////////// //BuildNodally(pScheme, rModelPart, A, b); ///////////////////////////////// ALL NODAL ///////////////////////////////// // /////////////////////// NODAL + ELEMENTAL LAPLACIAN /////////////////////// //BuildNodallyUnlessLaplacian(pScheme, rModelPart, A, b); //Build(pScheme, rModelPart, A, b); // /////////////////////// NODAL + ELEMENTAL LAPLACIAN /////////////////////// //////////////// NODAL + ELEMENTAL VOLUMETRIC STABILIZED TERMS//////////////// //BuildNodallyNoVolumetricStabilizedTerms(pScheme, rModelPart, A, b); //Build(pScheme, rModelPart, A, b); // /////////////////////// NODAL + ELEMENTAL LAPLACIAN /////////////////////// /////////////////////// NODAL + ELEMENTAL STABILIZATION ////////////////////// // BuildNodallyNotStabilized(pScheme, rModelPart, A, b); // Build(pScheme, rModelPart, A, b); BuildAll(pScheme, rModelPart, A, b); /////////////////////// NODAL + ELEMENTAL STABILIZATION ////////////////////// //////////////////////// ALL ELEMENTAL (FOR HYBRID) ////////////////////////// //Build(pScheme, rModelPart, A, b); //////////////////////// ALL ELEMENTAL (FOR HYBRID) ////////////////////////// Timer::Stop("Build"); // ApplyPointLoads(pScheme,rModelPart,b); // Does nothing...dirichlet conditions are naturally dealt with in defining the residual ApplyDirichletConditions(pScheme, rModelPart, A, Dx, b); KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; /* const double start_solve = OpenMPUtils::GetCurrentTime(); */ Timer::Start("Solve"); /* boost::timer c_solve_time; */ SystemSolveWithPhysics(A, Dx, b, rModelPart); /* std::cout << "CONTINUITY EQ: solve_time : " << c_solve_time.elapsed() << std::endl; */ Timer::Stop("Solve"); /* const double stop_solve = OpenMPUtils::GetCurrentTime(); */ KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; KRATOS_CATCH("") } void Build( typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A, TSystemVectorType& b) override { KRATOS_TRY if(!pScheme) KRATOS_THROW_ERROR(std::runtime_error, "No scheme provided!", ""); //getting the elements from the model ElementsArrayType& pElements = r_model_part.Elements(); // //getting the array of the conditions // ConditionsArrayType& ConditionsArray = r_model_part.Conditions(); //resetting to zero the vector of reactions TSparseSpace::SetToZero( *(BaseType::mpReactionsVector) ); //create a partition of the element array int number_of_threads = OpenMPUtils::GetNumThreads(); #ifdef _OPENMP int A_size = A.size1(); //creating an array of lock variables of the size of the system matrix std::vector< omp_lock_t > lock_array(A.size1()); for(int i = 0; i<A_size; i++) omp_init_lock(&lock_array[i]); #endif DenseVector<unsigned int> element_partition; CreatePartition(number_of_threads, pElements.size(), element_partition); if (this->GetEchoLevel()>0) { KRATOS_WATCH( number_of_threads ); KRATOS_WATCH( element_partition ); } double start_prod = OpenMPUtils::GetCurrentTime(); #pragma omp parallel for firstprivate(number_of_threads) schedule(static,1) for(int k=0; k<number_of_threads; k++) { //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0,0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); typename ElementsArrayType::ptr_iterator it_begin=pElements.ptr_begin()+element_partition[k]; typename ElementsArrayType::ptr_iterator it_end=pElements.ptr_begin()+element_partition[k+1]; unsigned int pos = (r_model_part.Nodes().begin())->GetDofPosition(PRESSURE); // assemble all elements for (typename ElementsArrayType::ptr_iterator it=it_begin; it!=it_end; ++it) { //calculate elemental contribution //(*it)->InitializeNonLinearIteration(CurrentProcessInfo); (*it)->CalculateLocalSystem(LHS_Contribution,RHS_Contribution,CurrentProcessInfo); Geometry< Node<3> >& geom = (*it)->GetGeometry(); if(EquationId.size() != geom.size()) EquationId.resize(geom.size(),false); for(unsigned int i=0; i<geom.size(); i++) EquationId[i] = geom[i].GetDof(PRESSURE,pos).EquationId(); //assemble the elemental contribution #ifdef _OPENMP this->Assemble(A,b,LHS_Contribution,RHS_Contribution,EquationId,lock_array); #else this->Assemble(A,b,LHS_Contribution,RHS_Contribution,EquationId); #endif } } if (this->GetEchoLevel()>0) { double stop_prod = OpenMPUtils::GetCurrentTime(); std::cout << "parallel building time: " << stop_prod - start_prod << std::endl; } #ifdef _OPENMP for(int i = 0; i<A_size; i++) omp_destroy_lock(&lock_array[i]); #endif KRATOS_CATCH("") } /** * @brief Builds the list of the DofSets involved in the problem by "asking" to each element * and condition its Dofs. * @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the * way the matrix and RHS are built * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void SetUpDofSet( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart ) override { KRATOS_TRY; KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << "Setting up the dofs" << std::endl; //Gets the array of elements from the modeler ElementsArrayType& pElements = rModelPart.Elements(); const int nelements = static_cast<int>(pElements.size()); Element::DofsVectorType ElementalDofList; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); unsigned int nthreads = OpenMPUtils::GetNumThreads(); // typedef boost::fast_pool_allocator< NodeType::DofType::Pointer > allocator_type; // typedef std::unordered_set < NodeType::DofType::Pointer, // DofPointerHasher, // DofPointerComparor, // allocator_type > set_type; #ifdef USE_GOOGLE_HASH typedef google::dense_hash_set < NodeType::DofType::Pointer, DofPointerHasher> set_type; #else typedef std::unordered_set < NodeType::DofType::Pointer, DofPointerHasher> set_type; #endif // std::vector<set_type> dofs_aux_list(nthreads); // std::vector<allocator_type> allocators(nthreads); for (int i = 0; i < static_cast<int>(nthreads); i++) { #ifdef USE_GOOGLE_HASH dofs_aux_list[i].set_empty_key(NodeType::DofType::Pointer()); #else // dofs_aux_list[i] = set_type( allocators[i]); dofs_aux_list[i].reserve(nelements); #endif } #pragma omp parallel for firstprivate(nelements, ElementalDofList) for (int i = 0; i < static_cast<int>(nelements); i++) { typename ElementsArrayType::iterator it = pElements.begin() + i; const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // gets list of Dof involved on every element pScheme->GetElementalDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); } // ConditionsArrayType& pConditions = rModelPart.Conditions(); // const int nconditions = static_cast<int>(pConditions.size()); // #pragma omp parallel for firstprivate(nconditions, ElementalDofList) // for (int i = 0; i < nconditions; i++) // { // typename ConditionsArrayType::iterator it = pConditions.begin() + i; // const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // // gets list of Dof involved on every element // pScheme->GetConditionDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); // dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); // } //here we do a reduction in a tree so to have everything on thread 0 unsigned int old_max = nthreads; unsigned int new_max = ceil(0.5*static_cast<double>(old_max)); while (new_max >= 1 && new_max != old_max) { // //just for debugging // std::cout << "old_max" << old_max << " new_max:" << new_max << std::endl; // for (int i = 0; i < new_max; i++) // { // if (i + new_max < old_max) // { // std::cout << i << " - " << i + new_max << std::endl; // } // } // std::cout << "********************" << std::endl; #pragma omp parallel for for (int i = 0; i < static_cast<int>(new_max); i++) { if (i + new_max < old_max) { dofs_aux_list[i].insert(dofs_aux_list[i + new_max].begin(), dofs_aux_list[i + new_max].end()); dofs_aux_list[i + new_max].clear(); } } old_max = new_max; new_max = ceil(0.5*static_cast<double>(old_max)); } DofsArrayType Doftemp; BaseType::mDofSet = DofsArrayType(); Doftemp.reserve(dofs_aux_list[0].size()); for (auto it = dofs_aux_list[0].begin(); it != dofs_aux_list[0].end(); it++) { Doftemp.push_back(it->get()); } Doftemp.Sort(); BaseType::mDofSet = Doftemp; // Throws an execption if there are no Degrees of freedom involved in the analysis KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl; BaseType::mDofSetIsInitialized = true; KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0) << "Finished setting up the dofs" << std::endl; #ifdef _OPENMP if (mlock_array.size() != 0) { for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) omp_destroy_lock(&mlock_array[i]); } mlock_array.resize(BaseType::mDofSet.size()); for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) omp_init_lock(&mlock_array[i]); #endif // If reactions are to be calculated, we check if all the dofs have reactions defined // This is tobe done only in debug mode #ifdef KRATOS_DEBUG if(BaseType::GetCalculateReactionsFlag()) { for(auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) { KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " <<std::endl << "Node : "<<dof_iterator->Id()<< std::endl << "Dof : "<<(*dof_iterator)<<std::endl<<"Not possible to calculate reactions."<<std::endl; } } #endif KRATOS_CATCH(""); } /** * @brief Organises the dofset in order to speed up the building phase * @param rModelPart The model part of the problem to solve */ void SetUpSystem( ModelPart& rModelPart ) override { // Set equation id for degrees of freedom // the free degrees of freedom are positioned at the beginning of the system, // while the fixed one are at the end (in opposite order). // // that means that if the EquationId is greater than "mEquationSystemSize" // the pointed degree of freedom is restrained // int free_id = 0; int fix_id = BaseType::mDofSet.size(); for (typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) if (dof_iterator->IsFixed()) dof_iterator->SetEquationId(--fix_id); else dof_iterator->SetEquationId(free_id++); BaseType::mEquationSystemSize = fix_id; } //************************************************************************** //************************************************************************** void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme, TSystemMatrixPointerType& pA, TSystemVectorPointerType& pDx, TSystemVectorPointerType& pb, ModelPart& rModelPart ) override { KRATOS_TRY /* boost::timer c_contruct_matrix; */ if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); pA.swap(pNewA); } if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0)); pDx.swap(pNewDx); } if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0)); pb.swap(pNewb); } if (BaseType::mpReactionsVector == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewReactionsVector = TSystemVectorPointerType(new TSystemVectorType(0)); BaseType::mpReactionsVector.swap(pNewReactionsVector); } TSystemMatrixType& A = *pA; TSystemVectorType& Dx = *pDx; TSystemVectorType& b = *pb; //resizing the system vectors and matrix if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized { A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); ConstructMatrixStructure(pScheme, A, rModelPart); } else { if (A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize) { KRATOS_WATCH("it should not come here!!!!!!!! ... this is SLOW"); KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl; A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, true); ConstructMatrixStructure(pScheme, A, rModelPart); } } if (Dx.size() != BaseType::mEquationSystemSize) Dx.resize(BaseType::mEquationSystemSize, false); if (b.size() != BaseType::mEquationSystemSize) b.resize(BaseType::mEquationSystemSize, false); //if needed resize the vector for the calculation of reactions if (BaseType::mCalculateReactionsFlag == true) { unsigned int ReactionsVectorSize = BaseType::mDofSet.size(); if (BaseType::mpReactionsVector->size() != ReactionsVectorSize) BaseType::mpReactionsVector->resize(ReactionsVectorSize, false); } /* std::cout << "CONTINUITY EQ: contruct_matrix : " << c_contruct_matrix.elapsed() << std::endl; */ KRATOS_CATCH("") } //************************************************************************** //************************************************************************** /** * @brief Applies the dirichlet conditions. This operation may be very heavy or completely * unexpensive depending on the implementation choosen and on how the System Matrix is built. * @details For explanation of how it works for a particular implementation the user * should refer to the particular Builder And Solver choosen * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { } /** * @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed */ void Clear() override { this->mDofSet = DofsArrayType(); if (this->mpReactionsVector != NULL) TSparseSpace::Clear((this->mpReactionsVector)); // this->mReactionsVector = TSystemVectorType(); this->mpLinearSystemSolver->Clear(); KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverContinuity", this->GetEchoLevel() > 1) << "Clear Function called" << std::endl; } /** * @brief This function is designed to be called once to perform all the checks needed * on the input provided. Checks can be "expensive" as the function is designed * to catch user's errors. * @param rModelPart The model part of the problem to solve * @return 0 all ok */ int Check(ModelPart& rModelPart) override { KRATOS_TRY return 0; KRATOS_CATCH(""); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ void Assemble( TSystemMatrixType& A, TSystemVectorType& b, const LocalSystemMatrixType& LHS_Contribution, const LocalSystemVectorType& RHS_Contribution, const Element::EquationIdVectorType& EquationId #ifdef _OPENMP ,std::vector< omp_lock_t >& lock_array #endif ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { #ifdef _OPENMP omp_set_lock(&lock_array[i_global]); #endif b[i_global] += RHS_Contribution(i_local); for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) { A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } #ifdef _OPENMP omp_unset_lock(&lock_array[i_global]); #endif } //note that assembly on fixed rows is not performed here } } //************************************************************************** virtual void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType& A, ModelPart& rModelPart) { //filling with zero the matrix (creating the structure) Timer::Start("MatrixStructure"); const std::size_t equation_size = BaseType::mEquationSystemSize; std::vector<std::unordered_set<std::size_t> > indices(equation_size); #pragma omp parallel for firstprivate(equation_size) for (int iii = 0; iii < static_cast<int>(equation_size); iii++) { indices[iii].reserve(40); } Element::EquationIdVectorType ids(3, 0); #pragma omp parallel firstprivate(ids) { // The process info ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // We repeat the same declaration for each thead std::vector<std::unordered_set<std::size_t> > temp_indexes(equation_size); #pragma omp for for (int index = 0; index < static_cast<int>(equation_size); ++index) temp_indexes[index].reserve(30); // Getting the size of the array of elements from the model const int number_of_elements = static_cast<int>(rModelPart.Elements().size()); // Element initial iterator const auto el_begin = rModelPart.ElementsBegin(); // We iterate over the elements #pragma omp for schedule(guided, 512) nowait for (int i_elem = 0; i_elem<number_of_elements; ++i_elem) { auto it_elem = el_begin + i_elem; pScheme->EquationId( *(it_elem.base()), ids, r_current_process_info); for (auto& id_i : ids) { if (id_i < BaseType::mEquationSystemSize) { auto& row_indices = temp_indexes[id_i]; for (auto& id_j : ids) if (id_j < BaseType::mEquationSystemSize) row_indices.insert(id_j); } } } // Getting the size of the array of the conditions const int number_of_conditions = static_cast<int>(rModelPart.Conditions().size()); // Condition initial iterator const auto cond_begin = rModelPart.ConditionsBegin(); // We iterate over the conditions #pragma omp for schedule(guided, 512) nowait for (int i_cond = 0; i_cond<number_of_conditions; ++i_cond) { auto it_cond = cond_begin + i_cond; pScheme->Condition_EquationId( *(it_cond.base()), ids, r_current_process_info); for (auto& id_i : ids) { if (id_i < BaseType::mEquationSystemSize) { auto& row_indices = temp_indexes[id_i]; for (auto& id_j : ids) if (id_j < BaseType::mEquationSystemSize) row_indices.insert(id_j); } } } // Merging all the temporal indexes #pragma omp critical { for (int i = 0; i < static_cast<int>(temp_indexes.size()); ++i) { indices[i].insert(temp_indexes[i].begin(), temp_indexes[i].end()); } } } //count the row sizes unsigned int nnz = 0; for (unsigned int i = 0; i < indices.size(); i++) nnz += indices[i].size(); A = boost::numeric::ublas::compressed_matrix<double>(indices.size(), indices.size(), nnz); double* Avalues = A.value_data().begin(); std::size_t* Arow_indices = A.index1_data().begin(); std::size_t* Acol_indices = A.index2_data().begin(); //filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Arow_indices[0] = 0; for (int i = 0; i < static_cast<int>(A.size1()); i++) Arow_indices[i + 1] = Arow_indices[i] + indices[i].size(); #pragma omp parallel for for (int i = 0; i < static_cast<int>(A.size1()); i++) { const unsigned int row_begin = Arow_indices[i]; const unsigned int row_end = Arow_indices[i + 1]; unsigned int k = row_begin; for (auto it = indices[i].begin(); it != indices[i].end(); it++) { Acol_indices[k] = *it; Avalues[k] = 0.0; k++; } std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); } A.set_filled(indices.size() + 1, nnz); Timer::Stop("MatrixStructure"); } void AssembleLHS( TSystemMatrixType& A, LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ #ifdef _OPENMP std::vector< omp_lock_t > mlock_array; #endif ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ inline void AddUnique(std::vector<std::size_t>& v, const std::size_t& candidate) { std::vector<std::size_t>::iterator i = v.begin(); std::vector<std::size_t>::iterator endit = v.end(); while (i != endit && (*i) != candidate) { i++; } if (i == endit) { v.push_back(candidate); } } inline void CreatePartition(unsigned int number_of_threads,const int number_of_rows, DenseVector<unsigned int>& partitions) { partitions.resize(number_of_threads+1); int partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for(unsigned int i = 1; i<number_of_threads; i++) partitions[i] = partitions[i-1] + partition_size ; } void AssembleRHS( TSystemVectorType& b, const LocalSystemVectorType& RHS_Contribution, const Element::EquationIdVectorType& EquationId ) { unsigned int local_size = RHS_Contribution.size(); if (BaseType::mCalculateReactionsFlag == false) { for (unsigned int i_local = 0; i_local < local_size; i_local++) { const unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //free dof { // ASSEMBLING THE SYSTEM VECTOR double& b_value = b[i_global]; const double& rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } } } else { TSystemVectorType& ReactionsVector = *BaseType::mpReactionsVector; for (unsigned int i_local = 0; i_local < local_size; i_local++) { const unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //free dof { // ASSEMBLING THE SYSTEM VECTOR double& b_value = b[i_global]; const double& rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } else //fixed dof { double& b_value = ReactionsVector[i_global - BaseType::mEquationSystemSize]; const double& rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } } } } //************************************************************************** void AssembleLHS_CompleteOnFreeRows( TSystemMatrixType& A, LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { for (unsigned int j_local = 0; j_local < local_size; j_local++) { int j_global = EquationId[j_local]; A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class NodalResidualBasedEliminationBuilderAndSolverContinuity */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER defined */
GB_binop__bset_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 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__bset_int64 // A.*B function (eWiseMult): GB_AemultB__bset_int64 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__bset_int64 // C+=b function (dense accum): GB_Cdense_accumb__bset_int64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__bset_int64 // C=scalar+B GB_bind1st__bset_int64 // C=scalar+B' GB_bind1st_tran__bset_int64 // C=A+scalar GB_bind2nd__bset_int64 // C=A'+scalar GB_bind2nd_tran__bset_int64 // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = GB_BITSET (aij, bij, int64_t, 64) #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) \ int64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int64_t bij = Bx [pB] // 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) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_BITSET (x, y, int64_t, 64) ; // 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_BSET || GxB_NO_INT64 || GxB_NO_BSET_INT64) //------------------------------------------------------------------------------ // 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__bset_int64 ( 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__bset_int64 ( 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__bset_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 (none) ( 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 int64_t *GB_RESTRICT Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( 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 int64_t *GB_RESTRICT Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #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__bset_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 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__bset_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 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__bset_int64 ( 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 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 < anz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = Bx [p] ; Cx [p] = GB_BITSET (x, bij, int64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__bset_int64 ( 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 ; 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 = Ax [p] ; Cx [p] = GB_BITSET (aij, y, int64_t, 64) ; } 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 = Ax [pA] ; \ Cx [pC] = GB_BITSET (x, aij, int64_t, 64) ; \ } GrB_Info GB_bind1st_tran__bset_int64 ( 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 \ 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 = Ax [pA] ; \ Cx [pC] = GB_BITSET (aij, y, int64_t, 64) ; \ } GrB_Info GB_bind2nd_tran__bset_int64 ( 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 int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
join.c
/* Copyright 2013-2015. The Regents of the University of California. * Copyright 2015. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2013, 2015 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2015 Jonathan Tamir <jtamir@eecs.berkeley.edu> */ #include <stdbool.h> #include <complex.h> #include <string.h> #include <unistd.h> #include "num/multind.h" #include "num/init.h" #include "misc/mmio.h" #include "misc/debug.h" #include "misc/misc.h" #include "misc/opts.h" #include "misc/io.h" #ifndef DIMS #define DIMS 16 #endif #ifndef CFL_SIZE #define CFL_SIZE sizeof(complex float) #endif static const char usage_str[] = "dimension <input1> ... <inputn> <output>"; static const char help_str[] = "Join input files along {dimensions}. All other dimensions must have the same size.\n" "\t Example 1: join 0 slice_001 slice_002 slice_003 full_data\n" "\t Example 2: join 0 `seq -f \"slice_%%03g\" 0 255` full_data\n"; int main_join(int argc, char* argv[]) { bool append = false; const struct opt_s opts[] = { OPT_SET('a', &append, "append - only works for cfl files!"), }; cmdline(&argc, argv, 3, 1000, usage_str, help_str, ARRAY_SIZE(opts), opts); num_init(); int N = DIMS; int dim = atoi(argv[1]); assert(dim < N); int count = argc - 3; if (append) { count += 1; assert(count > 1); int len = strlen(argv[argc - 1]); char buf[len + 5]; strcpy(buf, argv[argc - 1]); strcat(buf, ".cfl"); if (-1 == access(buf, F_OK)) { // make sure we do not have any other file format strcpy(buf, argv[argc - 1]); strcat(buf, ".coo"); assert(-1 == access(buf, F_OK)); strcpy(buf, argv[argc - 1]); strcat(buf, ".ra"); assert(-1 == access(buf, F_OK)); count--; append = false; } } long in_dims[count][N]; long offsets[count]; complex float* idata[count]; long sum = 0; // figure out size of output for (int l = 0, i = 0; i < count; i++) { const char* name = NULL; if (append && (i == 0)) { name = argv[argc - 1]; } else { name = argv[2 + l++]; } debug_printf(DP_DEBUG1, "loading %s\n", name); idata[i] = load_cfl(name, N, in_dims[i]); offsets[i] = sum; sum += in_dims[i][dim]; for (int j = 0; j < N; j++) assert((dim == j) || (in_dims[0][j] == in_dims[i][j])); if (append && (i == 0)) unmap_cfl(N, in_dims[i], idata[i]); } long out_dims[N]; for (int i = 0; i < N; i++) out_dims[i] = in_dims[0][i]; out_dims[dim] = sum; if (append) { // Here, we need to trick the IO subsystem into absolutely NOT // unlinking our input, as the same file is also an output here. io_unregister(argv[argc - 1]); } complex float* out_data = create_cfl(argv[argc - 1], N, out_dims); long ostr[N]; md_calc_strides(N, ostr, out_dims, CFL_SIZE); #pragma omp parallel for for (int i = 0; i < count; i++) { if (!(append && (0 == i))) { long pos[N]; md_singleton_strides(N, pos); pos[dim] = offsets[i]; long istr[N]; md_calc_strides(N, istr, in_dims[i], CFL_SIZE); md_copy_block(N, pos, out_dims, out_data, in_dims[i], idata[i], CFL_SIZE); unmap_cfl(N, in_dims[i], idata[i]); debug_printf(DP_DEBUG1, "done copying file %d\n", i); } } unmap_cfl(N, out_dims, out_data); return 0; }
GB_unaryop__ainv_int16_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_int16_uint8 // op(A') function: GB_tran__ainv_int16_uint8 // C type: int16_t // A type: uint8_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = -aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, x) \ int16_t z = (int16_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_INT16 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_int16_uint8 ( int16_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_int16_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
activations.c
#include "activations.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <float.h> char *get_activation_string(ACTIVATION a) { switch(a){ case LOGISTIC: return "logistic"; case LOGGY: return "loggy"; case RELU: return "relu"; case ELU: return "elu"; case SELU: return "selu"; case GELU: return "gelu"; case RELIE: return "relie"; case RAMP: return "ramp"; case LINEAR: return "linear"; case TANH: return "tanh"; case PLSE: return "plse"; case LEAKY: return "leaky"; case STAIR: return "stair"; case HARDTAN: return "hardtan"; case LHTAN: return "lhtan"; default: break; } return "relu"; } ACTIVATION get_activation(char *s) { if (strcmp(s, "logistic")==0) return LOGISTIC; if (strcmp(s, "swish") == 0) return SWISH; if (strcmp(s, "mish") == 0) return MISH; if (strcmp(s, "normalize_channels") == 0) return NORM_CHAN; if (strcmp(s, "normalize_channels_softmax") == 0) return NORM_CHAN_SOFTMAX; if (strcmp(s, "normalize_channels_softmax_maxval") == 0) return NORM_CHAN_SOFTMAX_MAXVAL; if (strcmp(s, "loggy")==0) return LOGGY; if (strcmp(s, "relu")==0) return RELU; if (strcmp(s, "relu6") == 0) return RELU6; if (strcmp(s, "elu")==0) return ELU; if (strcmp(s, "selu") == 0) return SELU; if (strcmp(s, "gelu") == 0) return GELU; if (strcmp(s, "relie")==0) return RELIE; if (strcmp(s, "plse")==0) return PLSE; if (strcmp(s, "hardtan")==0) return HARDTAN; if (strcmp(s, "lhtan")==0) return LHTAN; if (strcmp(s, "linear")==0) return LINEAR; if (strcmp(s, "ramp")==0) return RAMP; if (strcmp(s, "leaky")==0) return LEAKY; if (strcmp(s, "tanh")==0) return TANH; if (strcmp(s, "stair")==0) return STAIR; fprintf(stderr, "Couldn't find activation function %s, going with ReLU\n", s); return RELU; } float activate(float x, ACTIVATION a) { switch(a){ case LINEAR: return linear_activate(x); case LOGISTIC: return logistic_activate(x); case LOGGY: return loggy_activate(x); case RELU: return relu_activate(x); case ELU: return elu_activate(x); case SELU: return selu_activate(x); case GELU: return gelu_activate(x); case RELIE: return relie_activate(x); case RAMP: return ramp_activate(x); case LEAKY: return leaky_activate(x); case TANH: return tanh_activate(x); case PLSE: return plse_activate(x); case STAIR: return stair_activate(x); case HARDTAN: return hardtan_activate(x); case LHTAN: return lhtan_activate(x); } return 0; } void activate_array(float *x, const int n, const ACTIVATION a) { int i; if (a == LINEAR) {} else if (a == LEAKY) { #pragma omp parallel for for (i = 0; i < n; ++i) { x[i] = leaky_activate(x[i]); } } else if (a == LOGISTIC) { #pragma omp parallel for for (i = 0; i < n; ++i) { x[i] = logistic_activate(x[i]); } } else { for (i = 0; i < n; ++i) { x[i] = activate(x[i], a); } } } void activate_array_swish(float *x, const int n, float * output_sigmoid, float * output) { int i; #pragma omp parallel for for (i = 0; i < n; ++i) { float x_val = x[i]; float sigmoid = logistic_activate(x_val); output_sigmoid[i] = sigmoid; output[i] = x_val * sigmoid; } } // https://github.com/digantamisra98/Mish void activate_array_mish(float *x, const int n, float * activation_input, float * output) { const float MISH_THRESHOLD = 20; int i; #pragma omp parallel for for (i = 0; i < n; ++i) { float x_val = x[i]; activation_input[i] = x_val; // store value before activation output[i] = x_val * tanh_activate( softplus_activate(x_val, MISH_THRESHOLD) ); } } void activate_array_normalize_channels(float *x, const int n, int batch, int channels, int wh_step, float *output) { int size = n / channels; int i; #pragma omp parallel for for (i = 0; i < size; ++i) { int wh_i = i % wh_step; int b = i / wh_step; const float eps = 0.0001; if (i < size) { float sum = eps; int k; for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; if (val > 0) sum += val; } for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; if (val > 0) val = val / sum; else val = 0; output[wh_i + k * wh_step + b*wh_step*channels] = val; } } } } void activate_array_normalize_channels_softmax(float *x, const int n, int batch, int channels, int wh_step, float *output, int use_max_val) { int size = n / channels; int i; #pragma omp parallel for for (i = 0; i < size; ++i) { int wh_i = i % wh_step; int b = i / wh_step; const float eps = 0.0001; if (i < size) { float sum = eps; float max_val = -FLT_MAX; int k; if (use_max_val) { for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; if (val > max_val || k == 0) max_val = val; } } else max_val = 0; for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; sum += expf(val - max_val); } for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; val = expf(val - max_val) / sum; output[wh_i + k * wh_step + b*wh_step*channels] = val; } } } } void gradient_array_normalize_channels_softmax(float *x, const int n, int batch, int channels, int wh_step, float *delta) { int size = n / channels; int i; #pragma omp parallel for for (i = 0; i < size; ++i) { int wh_i = i % wh_step; int b = i / wh_step; if (i < size) { float grad = 0; int k; for (k = 0; k < channels; ++k) { const int index = wh_i + k * wh_step + b*wh_step*channels; float out = x[index]; float d = delta[index]; grad += out*d; } for (k = 0; k < channels; ++k) { const int index = wh_i + k * wh_step + b*wh_step*channels; float d = delta[index]; d = d * grad; delta[index] = d; } } } } void gradient_array_normalize_channels(float *x, const int n, int batch, int channels, int wh_step, float *delta) { int size = n / channels; int i; #pragma omp parallel for for (i = 0; i < size; ++i) { int wh_i = i % wh_step; int b = i / wh_step; if (i < size) { float grad = 0; int k; for (k = 0; k < channels; ++k) { const int index = wh_i + k * wh_step + b*wh_step*channels; float out = x[index]; float d = delta[index]; grad += out*d; } for (k = 0; k < channels; ++k) { const int index = wh_i + k * wh_step + b*wh_step*channels; if (x[index] > 0) { float d = delta[index]; d = d * grad; delta[index] = d; } } } } } float gradient(float x, ACTIVATION a) { switch(a){ case LINEAR: return linear_gradient(x); case LOGISTIC: return logistic_gradient(x); case LOGGY: return loggy_gradient(x); case RELU: return relu_gradient(x); case NORM_CHAN: //return relu_gradient(x); case NORM_CHAN_SOFTMAX_MAXVAL: //... case NORM_CHAN_SOFTMAX: printf(" Error: should be used custom NORM_CHAN or NORM_CHAN_SOFTMAX-function for gradient \n"); exit(0); return 0; case ELU: return elu_gradient(x); case SELU: return selu_gradient(x); case GELU: return gelu_gradient(x); case RELIE: return relie_gradient(x); case RAMP: return ramp_gradient(x); case LEAKY: return leaky_gradient(x); case TANH: return tanh_gradient(x); case PLSE: return plse_gradient(x); case STAIR: return stair_gradient(x); case HARDTAN: return hardtan_gradient(x); case LHTAN: return lhtan_gradient(x); } return 0; } void gradient_array(const float *x, const int n, const ACTIVATION a, float *delta) { int i; #pragma omp parallel for for(i = 0; i < n; ++i){ delta[i] *= gradient(x[i], a); } } // https://github.com/BVLC/caffe/blob/04ab089db018a292ae48d51732dd6c66766b36b6/src/caffe/layers/swish_layer.cpp#L54-L56 void gradient_array_swish(const float *x, const int n, const float * sigmoid, float * delta) { int i; #pragma omp parallel for for (i = 0; i < n; ++i) { float swish = x[i]; delta[i] *= swish + sigmoid[i]*(1 - swish); } } // https://github.com/digantamisra98/Mish void gradient_array_mish(const int n, const float * activation_input, float * delta) { int i; #pragma omp parallel for for (i = 0; i < n; ++i) { const float MISH_THRESHOLD = 20.0f; // implementation from TensorFlow: https://github.com/tensorflow/addons/commit/093cdfa85d334cbe19a37624c33198f3140109ed // implementation from Pytorch: https://github.com/thomasbrandon/mish-cuda/blob/master/csrc/mish.h#L26-L31 float inp = activation_input[i]; const float sp = softplus_activate(inp, MISH_THRESHOLD); const float grad_sp = 1 - exp(-sp); const float tsp = tanh(sp); const float grad_tsp = (1 - tsp*tsp) * grad_sp; const float grad = inp * grad_tsp + tsp; delta[i] *= grad; //float x = activation_input[i]; //float d = 2 * expf(x) + expf(2 * x) + 2; //float w = 4 * (x + 1) + 4 * expf(2 * x) + expf(3 * x) + expf(x)*(4 * x + 6); //float derivative = expf(x) * w / (d * d); //delta[i] *= derivative; } }
fabio_c.c
/* Contains the IO routines for fabio module */ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <float.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> //#if !defined(WIN32) #include <unistd.h> //#else //#include <io.h> //typedef int mode_t; //#endif #ifndef WIN32 #define FILE_MODE ( S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) #define DIR_MODE (FILE_MODE | S_IXUSR | S_IXGRP | S_IXOTH) #define O_BINARY 0 #else #define FILE_MODE (-1) #define DIR_MODE (-1) #endif #if defined(BL_FORT_USE_UNDERSCORE) #define FABIO_UNLINK_IF_EMPTY_STR fabio_unlink_if_empty_str_ #define FABIO_OPEN_STR fabio_open_str_ #define FABIO_MKDIR_STR fabio_mkdir_str_ #define FABIO_CLOSE fabio_close_ #define FAB_CONTAINS_NAN fab_contains_nan_ #define FAB_CONTAINS_INF fab_contains_inf_ #define VAL_IS_INF val_is_inf_ #define VAL_IS_NAN val_is_nan_ #elif defined(BL_FORT_USE_DBL_UNDERSCORE) #define FABIO_UNLINK_IF_EMPTY_STR fabio_unlink_if_empty_str__ #define FABIO_OPEN_STR fabio_open_str__ #define FABIO_MKDIR_STR fabio_mkdir_str__ #define FABIO_CLOSE fabio_close__ #define FAB_CONTAINS_NAN fab_contains_nan__ #define FAB_CONTAINS_INF fab_contains_inf__ #define VAL_IS_INF val_is_inf__ #define VAL_IS_NAN val_is_nan__ #elif defined(BL_FORT_USE_LOWERCASE) #define FABIO_UNLINK_IF_EMPTY_STR fabio_unlink_if_empty_str #define FABIO_OPEN_STR fabio_open_str #define FABIO_MKDIR_STR fabio_mkdir_str #define FABIO_CLOSE fabio_close #define FAB_CONTAINS_NAN fab_contains_nan #define FAB_CONTAINS_INF fab_contains_inf #define VAL_IS_INF val_is_inf #define VAL_IS_NAN val_is_nan #endif static const int BUFFER_SIZE = 512; static const int FABIO_MAX_PATH_NAME = 512; static void int_2_str(char f[], int n, const int* fi) { int i; for ( i = 0; i < n; ++i ) { if ( fi[i] < 0 ) { f[i] = 0; break; } f[i] = (char)fi[i]; } if ( i == n ) { fprintf(stderr, "name to long, probably not terminated ifilename\n"); exit(1); } } void FABIO_OPEN_STR(int* fdp, const int* ifilename, const int* flagp) { int lflag; int lmode; char filename[FABIO_MAX_PATH_NAME]; int_2_str(filename, sizeof(filename), ifilename); switch ( *flagp ) { case 0: lflag = O_RDONLY; break; case 1: lflag = O_WRONLY | O_CREAT | O_TRUNC | O_BINARY; lmode = FILE_MODE; break; case 2: lflag = O_RDWR; break; case 3: lflag = O_RDWR | O_APPEND; break; case 4: lflag = O_RDONLY | O_BINARY; break; default: fprintf(stderr, "FABIO_OPEN_STR: invalid flag, %d, must be <=0<=2", *flagp); exit(1); } *fdp = open(filename, lflag, lmode); if ( *fdp == -1 ) { fprintf(stderr, "FABIO_OPEN_STR: failed to open \"%s\": %s\n", filename, strerror(errno)); exit(1); } } /* * DOUBLE data * FAB ((8, (64 11 52 0 1 12 0 1023)),(8, (1 2 3 4 5 6 7 8)))((0,0) (63,63) (0,0)) 27 * FLOAT data * FAB ((8, (32 8 23 0 1 9 0 127)),(4, (1 2 3 4) ))((0,0) (63,63) (0,0)) 27 */ /* * NORDER_? : normal byte order floats(f), doubles(d) on this architecture */ static const char* str_ieee_d = "64 11 52 0 1 12 0 1023"; static const char* str_ieee_f = "32 8 23 0 1 9 0 127"; #if defined(BL_AIX) || defined(BL_Darwin) static const int norder_d[8] = { 1, 2, 3, 4, 5, 6, 7, 8}; static const char* str_norder_d = "1 2 3 4 5 6 7 8"; static const int norder_f[4] = { 1, 2, 3, 4}; static const char* str_norder_f = "1 2 3 4"; #else static const int norder_d[8] = { 8, 7, 6, 5, 4, 3, 2, 1}; static const char* str_norder_d = "8 7 6 5 4 3 2 1"; static const int norder_f[4] = { 4, 3, 2, 1 }; static const char* str_norder_f = "4 3 2 1"; #endif enum { FABIO_ERR = 0, /* cf. fabio.f90 */ FABIO_SINGLE = 2, FABIO_DOUBLE = 1 }; static int scan_buffer(const char* buffer, int border[]) { int i; int bcount; char bstr[1024]; /* first try for double data */ i = sscanf(buffer, "FAB ((8, (64 11 52 0 1 12 0 1023)),(%d, (%[^)])))", &bcount, bstr); if ( i == 2 ) { i = sscanf(bstr, "%d %d %d %d %d %d %d %d", border + 0, border + 1, border + 2, border + 3, border + 4, border + 5, border + 6, border + 7 ); if ( i != 8 ) { fprintf(stderr, "FABIO: scan_buffer failed to parse FAB border\n" "Not double precision data\n"); exit(1); } return FABIO_DOUBLE; } /* second, try for float data */ i = sscanf(buffer, "FAB ((8, (32 8 23 0 1 9 0 127)),(%d, (%[^)])))", &bcount, bstr); if ( i == 2 ) { i = sscanf(bstr, "%d %d %d %d", border + 0, border + 1, border + 2, border + 3 ); if ( i != 4) { fprintf(stderr, "FABIO: scan_buffer failed to parse FAB border\n" "Not double precision data\n"); exit(1); } return FABIO_SINGLE; } fprintf(stderr, "FABIO: scan_buffer failed to parse FAB header\n" "Architecture difference for floating point format\n"); exit(1); return FABIO_ERR; } void FABIO_READ_SKIP_D(const int* fdp, const long* offsetp, const long* skipp, double dp[], const long* countp) { int fd = *fdp; char c; size_t count = *countp; off_t offset = *offsetp; off_t skip = *skipp; int i,j; char buffer[1024]; int border[8]; int swap_bytes = 0; if ( lseek(fd, offset, SEEK_SET) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to seek to %ld: %s\n", offset, strerror(errno)); exit(1); } for (i=0;;i++) { if ( read(fd, &c, 1) != 1 ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to read a char: %s\n", strerror(errno)); exit(1); } if ( c == '\n' ) break; if ( i == sizeof(buffer) ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed FAB header\n"); exit(1); } buffer[i] = c; } buffer[i] = 0; i = scan_buffer(buffer, border); if ( i == FABIO_DOUBLE ) { /* should be positioned to read the doubles */ if ( skip && lseek(fd, skip*sizeof(double), SEEK_CUR) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to seek to comp %ld: %s\n", offset, strerror(errno)); exit(1); } if ( count*sizeof(double) != read(fd, dp, count*sizeof(double)) ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to read %ld doubles: %s\n", (long)count, strerror(errno)); exit(1); } for ( j = 0; j < 8; ++j ) { if (border[j] != norder_d[j] ) { swap_bytes = 1; break; } } if ( swap_bytes ) { unsigned char* cdp = (unsigned char*)dp; for ( i = 0; i < count; i++ ) { unsigned char t[8]; for ( j = 0; j < 8; j++ ) { t[j] = cdp[border[j]-1]; } for ( j = 0; j < 8; j++ ) { cdp[j] = t[norder_d[j]-1]; } cdp += 8; } } } else if ( i == FABIO_SINGLE ) { float* fp; if ( (fp = (float *) malloc(count*sizeof(float))) == NULL) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to allocate fp\n"); exit(1); } /* should be positioned to read the doubles */ if ( skip && lseek(fd, skip*sizeof(float), SEEK_CUR) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to seek to comp %ld: %s\n", offset, strerror(errno)); exit(1); } if ( count*sizeof(float) != read(fd, fp, count*sizeof(float)) ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to read %ld doubles: %s\n", (long)count, strerror(errno)); exit(1); } for ( j = 0; j < 4; ++j ) { if (border[j] != norder_f[j] ) { swap_bytes = 1; break; } } if ( swap_bytes ) { unsigned char* csp = (unsigned char*)fp; for ( i = 0; i < count; i++ ) { unsigned char t[4]; for ( j = 0; j < 4; j++ ) { t[j] = csp[border[j]-1]; } for ( j = 0; j < 4; j++ ) { csp[j] = t[norder_f[j]-1]; } csp += 4; } } for ( i = 0; i < count; i++) { dp[i] = (double)fp[i]; } free(fp); } } void FABIO_READ_SKIP_S(const int* fdp, const long* offsetp, const long* skipp, float sp[], const long* countp) { int fd = *fdp; char c; size_t count = *countp; off_t offset = *offsetp; off_t skip = *skipp; int i,j; char buffer[1024]; int border[8]; int swap_bytes = 0; if ( lseek(fd, offset, SEEK_SET) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to seek to %ld: %s\n", offset, strerror(errno)); exit(1); } for (i=0;;i++) { if ( read(fd, &c, 1) != 1 ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to read a char: %s\n", strerror(errno)); exit(1); } if ( c == '\n' ) break; if ( i == sizeof(buffer) ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed FAB header\n"); exit(1); } buffer[i] = c; } buffer[i] = 0; i = scan_buffer(buffer, border); if ( i == FABIO_DOUBLE ) { double* dp; if ( (dp = (double *) malloc(count*sizeof(double))) == NULL) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to allocate sp\n"); exit(1); } /* should be positioned to read the doubles */ if ( skip && lseek(fd, skip*sizeof(double), SEEK_CUR) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to seek to comp %ld: %s\n", offset, strerror(errno)); exit(1); } if ( count*sizeof(double) != read(fd, dp, count*sizeof(double)) ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to read %ld doubles: %s\n", (long)count, strerror(errno)); exit(1); } for ( j = 0; j < 8; ++j ) { if (border[j] != norder_d[j] ) { swap_bytes = 1; break; } } if ( swap_bytes ) { unsigned char* cdp = (unsigned char*)dp; for ( i = 0; i < count; i++ ) { unsigned char t[8]; for ( j = 0; j < 8; j++ ) { t[j] = cdp[border[j]-1]; } for ( j = 0; j < 8; j++ ) { cdp[j] = t[norder_d[j]-1]; } cdp += 8; } } free(dp); for ( i = 0; i < count; i++ ) { if ( dp[i] > FLT_MAX ) sp[i] = FLT_MAX; else if ( dp[i] < -FLT_MAX ) sp[i] = -FLT_MAX; else sp[i] = (float)dp[i]; } } else if ( i == FABIO_SINGLE ) { /* should be positioned to read the doubles */ if ( skip && lseek(fd, skip*sizeof(float), SEEK_CUR) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to seek to comp %ld: %s\n", offset, strerror(errno)); exit(1); } if ( count*sizeof(float) != read(fd, sp, count*sizeof(float)) ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to read %ld doubles: %s\n", (long)count, strerror(errno)); exit(1); } for ( j = 0; j < 4; ++j ) { if (border[j] != norder_f[j] ) { swap_bytes = 1; break; } } if ( swap_bytes ) { unsigned char* csp = (unsigned char*)sp; for ( i = 0; i < count; i++ ) { unsigned char t[4]; for ( j = 0; j < 4; j++ ) { t[j] = csp[border[j]-1]; } for ( j = 0; j < 4; j++ ) { csp[j] = t[norder_f[j]-1]; } csp += 4; } } } } /* ** These four guys are used by the particle code. */ void FABIO_WRITE_RAW_ARRAY_D(const int* fdp, const double* vp, const int* countp) { int fd = *fdp; size_t count = *countp; int ilen = sizeof(double) * count; lseek(fd, 0, SEEK_END); if ( ilen != write(fd, vp, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_ARRAY_D: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } } void FABIO_WRITE_RAW_ARRAY_I(const int* fdp, const int* vp, const int* countp) { int fd = *fdp; size_t count = *countp; int ilen = sizeof(int) * count; lseek(fd, 0, SEEK_END); if ( ilen != write(fd, vp, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_ARRAY_I: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } } void FABIO_READ_RAW_ARRAY_D(const int* fdp, double* vp, const int* countp) { int fd = *fdp; size_t count = *countp; int ilen = sizeof(double) * count; if ( ilen != read(fd, vp, ilen) ) { fprintf(stderr, "FABIO_READ_RAW_ARRAY_D: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } } void FABIO_READ_RAW_ARRAY_I(const int* fdp, int* vp, const int* countp) { int fd = *fdp; size_t count = *countp; int ilen = sizeof(int) * count; if ( ilen != read(fd, vp, ilen) ) { fprintf(stderr, "FABIO_READ_RAW_ARRAY_I: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } } void FABIO_WRITE_RAW_D(const int* fdp, long* offsetp, const double* vp, const long* countp, const int* dmp, const int lo[], const int hi[], const int nd[], const int* ncp) { int fd = *fdp; int dm = *dmp; int nc = *ncp; size_t count = *countp; off_t offset; char buffer[BUFFER_SIZE]; int ilen; double* dp = (double*)vp; offset = lseek(fd, 0, SEEK_END); if ( snprintf(buffer, BUFFER_SIZE, "FAB ((8, (%s)),(8, (%s)))", str_ieee_d, str_norder_d) >= BUFFER_SIZE ) { fprintf(stderr, "FABIO_WRITE_RAW_D: buffer too small"); exit(1); } ilen = strlen(buffer); if ( ilen != write(fd, buffer, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_D: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } switch ( dm ) { case 1: ilen = snprintf(buffer, BUFFER_SIZE, "((%d) (%d) (%d)) %d\n", lo[0], hi[0], nd[0], nc); break; case 2: ilen = snprintf(buffer, BUFFER_SIZE, "((%d,%d) (%d,%d) (%d,%d)) %d\n", lo[0], lo[1], hi[0], hi[1], nd[0], nd[1], nc); break; case 3: ilen = snprintf(buffer, BUFFER_SIZE, "((%d,%d,%d) (%d,%d,%d) (%d,%d,%d)) %d\n", lo[0], lo[1], lo[2], hi[0], hi[1], hi[2], nd[0], nd[1], nd[2], nc); break; default: fprintf(stderr, "FABIO_WRITE_RAW_D: strange dimension = %d\n", dm); exit(1); } if ( ilen >= BUFFER_SIZE ) { fprintf(stderr, "FABIO_WRITE_RAW_D: buffer too small"); exit(1); } ilen = write(fd, buffer, strlen(buffer)); if ( ilen != strlen(buffer) ) { fprintf(stderr, "FABIO_WRITE_RAW_D: write of buffer failed\n"); exit(1); } ilen = nc*count*sizeof(double); if ( ilen != write(fd, dp, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_D: failed to write %ld doubles: %s\n", (long)nc*count, strerror(errno)); exit(1); } if ( offset > LONG_MAX ) { fprintf(stderr, "FABIO_WRITE_RAW_D: offset will overflow offsetp"); exit(1); } *offsetp = offset; } void FABIO_WRITE_RAW_S(const int* fdp, long* offsetp, const float* vp, const long* countp, const int* dmp, const int lo[], const int hi[], const int nd[], const int* ncp) { int fd = *fdp; int dm = *dmp; int nc = *ncp; size_t count = *countp; off_t offset; char buffer[BUFFER_SIZE]; int ilen; float* sp = (float*)vp; offset = lseek(fd, 0, SEEK_END); if ( snprintf(buffer, BUFFER_SIZE, "FAB ((8, (%s)),(4, (%s)))", str_ieee_f, str_norder_f) >= BUFFER_SIZE ) { fprintf(stderr, "FABIO_WRITE_RAW_S: buffer too small"); exit(1); } ilen = strlen(buffer); if ( ilen != write(fd, buffer, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_S: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } switch ( dm ) { case 1: ilen = snprintf(buffer, BUFFER_SIZE, "((%d) (%d) (%d)) %d\n", lo[0], hi[0], nd[0], nc); break; case 2: ilen = snprintf(buffer, BUFFER_SIZE, "((%d,%d) (%d,%d) (%d,%d)) %d\n", lo[0], lo[1], hi[0], hi[1], nd[0], nd[1], nc); break; case 3: ilen = snprintf(buffer, BUFFER_SIZE, "((%d,%d,%d) (%d,%d,%d) (%d,%d,%d)) %d\n", lo[0], lo[1], lo[2], hi[0], hi[1], hi[2], nd[0], nd[1], nd[2], nc); break; default: fprintf(stderr, "FABIO_WRITE_RAW_S: strange dimension = %d\n", dm); exit(1); } if ( ilen >= BUFFER_SIZE ) { fprintf(stderr, "FABIO_WRITE_RAW_S: buffer too small"); exit(1); } ilen = write(fd, buffer, strlen(buffer)); if ( ilen != strlen(buffer) ) { fprintf(stderr, "FABIO_WRITE_RAW_S: write of buffer failed\n"); exit(1); } ilen = nc*count*sizeof(float); if ( ilen != write(fd, sp, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_S: failed to write %ld floats: %s\n", (long)nc*count, strerror(errno)); exit(1); } if ( offset > LONG_MAX ) { fprintf(stderr, "FABIO_WRITE_RAW_S: offset will overflow offsetp"); exit(1); } *offsetp = offset; } void FABIO_READ_D(const int* fdp, const long* offsetp, double dp[], const long* countp) { long skip = 0; FABIO_READ_SKIP_D(fdp, offsetp, &skip, dp, countp); } void FABIO_READ_S(const int* fdp, const long* offsetp, float sp[], const long* countp) { long skip = 0; FABIO_READ_SKIP_S(fdp, offsetp, &skip, sp, countp); } void FABIO_CLOSE(const int* fdp) { int fd = *fdp; if ( close(fd) < 0 ) { fprintf(stderr, "FABIO_CLOSE: failed to close %d: %s\n", fd, strerror(errno)); exit(1); } } #if defined(WIN32) #include <direct.h> #define mkdir(a,b) _mkdir((a)) /* static const char* path_sep_str = "\\"; */ #else /* static const char* path_sep_str = "/"; */ #endif void FABIO_MKDIR_STR(const int* idirname, int* statp) { mode_t mode = DIR_MODE; int st = *statp; char dirname[FABIO_MAX_PATH_NAME]; int_2_str(dirname, sizeof(dirname), idirname); *statp = 0; /* we allow the mkdir on an existing directory */ if ( mkdir(dirname, mode) <0 && errno != EEXIST ) { if ( st ) { *statp = 1; return; } else { fprintf(stderr, "FABIO_MKDIR_STR: mkdir(%s,%d): %s\n", dirname, mode, strerror(errno)); exit(1); } } } void FABIO_UNLINK_IF_EMPTY_STR(const int* ifilename) { int fd; char filename[FABIO_MAX_PATH_NAME]; int lmode = FILE_MODE; int pos; int_2_str(filename, sizeof(filename), ifilename); if ((fd = open(filename, O_RDONLY, lmode)) < 0) { fprintf(stderr, "FABIO_UNLINK_IF_EMPTY: open() failed: \"%s\": %s\n", filename, strerror(errno)); exit(1); } if ((pos = lseek(fd, 0, SEEK_END)) < 0) { fprintf(stderr, "FABIO_UNLINK_IF_EMPTY: lseek() failed: \"%s\": %s\n", filename, strerror(errno)); exit(1); } close(fd); if (pos == 0) { if (unlink(filename) < 0) { fprintf(stderr, "FABIO_UNLINK_IF_EMPTY: unlink() failed: \"%s\": %s\n", filename, strerror(errno)); exit(1); } } } void FAB_CONTAINS_NAN (double dptr[], const int* countp, int* result) { int i; int rr=0; #ifdef _OPENMP #pragma omp parallel reduction(+:rr) #endif { #ifdef _OPENMP #pragma omp for private(i) #endif for (i = 0; i < *countp; i++) { if (isnan(dptr[i])) { rr++; } } } *result = (rr>0) ? 1 : 0; } void FAB_CONTAINS_INF (double dptr[], const int* countp, int* result) { int i; int rr=0; #ifdef _OPENMP #pragma omp parallel reduction(+:rr) #endif { #ifdef _OPENMP #pragma omp for private(i) #endif for (i = 0; i < *countp; i++) { if (isinf(dptr[i])) { rr++; } } } *result = (rr>0) ? 1 : 0; } void VAL_IS_INF (double* val, int* result) { *result = (isinf(*val) ? 1 : 0); } void VAL_IS_NAN (double* val, int* result) { *result = (isnan(*val) ? 1 : 0); }
torch_kdtree_nearest.h
#ifndef TORCH_KDTREE_NEAREST_H_ #define TORCH_KDTREE_NEAREST_H_ // search for a single point // see: https://zhuanlan.zhihu.com/p/45346117 template<int dim> void TorchKDTree::_search_nearest(const float* point, int64_t* out_) { using start_end = std::tuple<refIdx_t, refIdx_t>; float dist = std::numeric_limits<float>::max(); float dist_plane = std::numeric_limits<float>::max(); float dist_best = std::numeric_limits<float>::max(); refIdx_t node_best, node_bro; // BFS std::queue<start_end> buffer; refIdx_t node_start, node_end; buffer.emplace(start_end(root, _search(point, root))); while (!buffer.empty()) { std::tie(node_start, node_end) = buffer.front(); buffer.pop(); // back trace until to the starting node while (true) { // update if current node is better dist = distance<dim>(point, coordinates + numDimensions * kdNodes[node_end].tuple); if (dist < dist_best) { dist_best = dist; node_best = node_end; } if (node_end != node_start) { node_bro = kdNodes[node_end].brother; if (node_bro >= 0) { // if intersect with plane, search another branch dist_plane = distance_plane<dim>(point, kdNodes[node_end].parent); if (dist_plane < dist_best) { buffer.emplace(start_end(node_bro, _search(point, node_bro))); } } // back trace node_end = kdNodes[node_end].parent; } else break; } } *out_ = int64_t(kdNodes[node_best].tuple); } template<int N> struct WorkerNearest { static void work(TorchKDTree* tree_ptr, float* points_ptr, int64_t* raw_ptr, int numDimensions, int numQuery) { #pragma omp parallel for for (sint i = 0; i < numQuery; ++i) tree_ptr->_search_nearest<N>(points_ptr + i * numDimensions, raw_ptr + i); } }; template<int N> struct WorkerCUDANearest { static void work(TorchKDTree* tree_ptr, float* points_ptr, int64_t* raw_ptr, int numQuery) { tree_ptr->device->Search_nearest<N>(points_ptr, raw_ptr, numQuery); } }; torch::Tensor TorchKDTree::search_nearest(torch::Tensor points) { CHECK_CONTIGUOUS(points); CHECK_FLOAT32(points); TORCH_CHECK(points.size(1) == numDimensions, "dimensions mismatch"); sint numQuery = points.size(0); float* points_ptr = points.data_ptr<float>(); torch::Tensor indices_tensor; if (is_cuda) { indices_tensor = torch::zeros({numQuery}, torch::TensorOptions() .dtype(torch::kInt64) .device(torch::kCUDA, device->getDevice())); int64_t* raw_ptr = indices_tensor.data_ptr<int64_t>(); Dispatcher<WorkerCUDANearest>::dispatch(numDimensions, this, points_ptr, raw_ptr, numQuery); } else { indices_tensor = torch::zeros({numQuery}, torch::kInt64); int64_t* raw_ptr = indices_tensor.data_ptr<int64_t>(); Dispatcher<WorkerNearest>::dispatch(numDimensions, this, points_ptr, raw_ptr, numDimensions, numQuery); } return indices_tensor; } #endif
cameraData.h
#pragma once #include "lights/light.h" #include "glmInclude.h" #include "util.h" #include "camera.h" #include <iostream> // writing on a text file #include <fstream> #include <algorithm> #include <vector> //for the parallel for #include <execution> //spawns all the rays in the scene class CameraData : public Camera { public: //per pixel per depth counter: std::vector<std::vector<uint16_t>> nodeIntersectionPerPixelCount; std::vector<std::vector<uint16_t>> leafIntersectionPerPixelCount; std::vector<std::vector<uint16_t>> shadowNodeIntersectionPerPixelCount; std::vector<std::vector<uint16_t>> shadowLeafIntersectionPerPixelCount; std::vector<std::vector<uint16_t>> childFullnessPerPixelCount; std::vector<std::vector<uint16_t>> primitiveFullnessPerPixelCount; //per pixel counter: std::vector<uint16_t> primitiveIntersectionsPerPixel; std::vector<uint16_t> shadowPrimitiveIntersectionsPerPixel; std::vector<uint16_t> successfulPrimitiveIntersectionsPerPixel; std::vector<uint16_t> successfulAabbIntersectionsPerPixel; std::vector<uint16_t> aabbIntersectionsPerPixel; std::vector<uint16_t> shadowRayCounter; std::vector<uint16_t> shadowSuccessfulPrimitiveIntersectionsPerPixel; std::vector<uint16_t> shadowSuccessfulAabbIntersectionsPerPixel; std::vector<uint16_t> shadowAabbIntersectionsPerPixel; //per depth counter: std::vector<uint64_t> primitiveFullness; std::vector<uint64_t> childFullness; std::vector<uint64_t> nodeIntersectionPerDepthCount; std::vector<uint64_t> leafIntersectionPerDepthCount; std::vector<uint64_t> shadowNodeIntersectionPerDepthCount; std::vector<uint64_t> shadowLeafIntersectionPerDepthCount; //per workGroup per step: (those are the only arrays that are reset for every camera) std::vector<std::vector<uint32_t>> nodeWorkPerStep; std::vector<std::vector<uint32_t>> leafWorkPerStep; std::vector<std::vector<uint32_t>> terminationsPerStep; std::vector<std::vector<uint32_t>> uniqueNodesPerStep; std::vector<std::vector<uint32_t>> uniqueLeafsPerStep; std::vector<std::vector<uint32_t>> secondaryNodeWorkPerStep; std::vector<std::vector<uint32_t>> secondaryLeafWorkPerStep; std::vector<std::vector<uint32_t>> secondaryTerminationsPerStep; std::vector<std::vector<uint32_t>> secondaryUniqueNodesPerStep; std::vector<std::vector<uint32_t>> secondaryUniqueLeafsPerStep; //extra counter to calculate per camrea values from other counter std::vector<uint32_t> nodeIntersectionPerPixelCountCameraSum; std::vector<uint32_t> shadowNodeIntersectionPerPixelCountCameraSum; std::vector<uint32_t> leafIntersectionPerPixelCountCameraSum; std::vector<uint32_t> shadowLeafIntersectionPerPixelCountCameraSum; //normal counter uint64_t nodeIntersectionCount; uint64_t leafIntersectionCount; uint64_t shadowNodeIntersectionCount; uint64_t shadowLeafIntersectionCount; uint64_t primitiveIntersections; uint64_t shadowPrimitiveIntersections; uint64_t successfulPrimitiveIntersections; uint64_t successfulAabbIntersections; uint64_t aabbIntersections; uint64_t shadowRayCount; uint64_t shadowSuccessfulPrimitiveIntersections; uint64_t shadowSuccessfulAabbIntersections; uint64_t shadowAabbIntersections; bool wideRender; CameraData(std::string path, std::string name, std::string problem, int workGroupSize, bool wideRender, std::vector<glm::vec3>& positions, std::vector<glm::vec3>& lookCenters, size_t width = 1920, size_t height = 1088, glm::vec3 upward = glm::vec3(0, 1, 0), float focalLength = 0.866f) :Camera(path, name, problem, workGroupSize, positions, lookCenters, width, height, upward, focalLength), wideRender(wideRender) { image.resize(height * width * 4); initializeVariables(); } CameraData(std::string path, std::string name, std::string problem, int workGroupSize, bool wideRender, std::vector<glm::mat4>& transforms, size_t width = 1920, size_t height = 1088, float focalLength = 0.866f) :Camera(path, name, problem, workGroupSize, transforms, width, height, focalLength), wideRender(wideRender) { image.resize(height * width * 4); initializeVariables(); } template<typename T> void renderImages(bool saveImage, bool saveDepthDebugImage, CompactNodeManager<T>& nodeManager , Bvh& bvh, std::vector<std::unique_ptr<Light>>& lights, unsigned ambientSampleCount, float ambientDistance, bool castShadows, int renderType, bool mute, bool doWorkGroupAnalysis, bool wideAlternative) { int workGroupSize = nonTemplateWorkGroupSize; int cameraCount = positions.size(); for (int cameraId = 0; cameraId < cameraCount; cameraId++) { //reset wide render storage arrays if (wideRender) { initializeWideRenderVariables(); } renderImage(saveImage, saveDepthDebugImage, nodeManager, bvh, lights, ambientSampleCount, ambientDistance, castShadows, renderType, mute, doWorkGroupAnalysis, cameraId, wideAlternative); //save image for each camera and the data from wideRender std::string cameraName = "_c" + std::to_string(cameraId); if (doWorkGroupAnalysis) { if (wideRender) { workGroupAnalysisPerImage(cameraName, wideAlternative); } else { std::cerr << "Workgroup analysis is not possible without wide renderer!" << std::endl; } } if (saveImage) { encodeTwoSteps(path + "/" + name + cameraName + ".png", image, width, height); } if (cameraId == 0 && saveDepthDebugImage) { createDepthDebugImage(bvh.bvhDepth); } } //gather data: leafIntersectionPerDepthCount.resize(bvh.bvhDepth); for (auto& perPixel : leafIntersectionPerPixelCount) { for (size_t i = 0; i < perPixel.size(); i++) { leafIntersectionPerDepthCount[i] += perPixel[i]; } } nodeIntersectionPerDepthCount.resize(bvh.bvhDepth); for (auto& perPixel : nodeIntersectionPerPixelCount) { for (size_t i = 0; i < perPixel.size(); i++) { nodeIntersectionPerDepthCount[i] += perPixel[i]; } } shadowLeafIntersectionPerDepthCount.resize(bvh.bvhDepth); for (auto& perPixel : shadowLeafIntersectionPerPixelCount) { for (size_t i = 0; i < perPixel.size(); i++) { shadowLeafIntersectionPerDepthCount[i] += perPixel[i]; } } shadowNodeIntersectionPerDepthCount.resize(bvh.bvhDepth); for (auto& perPixel : shadowNodeIntersectionPerPixelCount) { for (size_t i = 0; i < perPixel.size(); i++) { shadowNodeIntersectionPerDepthCount[i] += perPixel[i]; } } childFullness.resize(bvh.branchingFactor + 1); for (auto& perPixel : childFullnessPerPixelCount) { for (size_t i = 0; i < perPixel.size(); i++) { childFullness[i] += perPixel[i]; } } primitiveFullness.resize(bvh.leafSize + 1); for (auto& perPixel : primitiveFullnessPerPixelCount) { for (size_t i = 0; i < perPixel.size(); i++) { primitiveFullness[i] += perPixel[i]; } } leafIntersectionCount = std::accumulate(leafIntersectionPerDepthCount.begin(), leafIntersectionPerDepthCount.end(), 0ULL); nodeIntersectionCount = std::accumulate(nodeIntersectionPerDepthCount.begin(), nodeIntersectionPerDepthCount.end(), 0ULL); shadowLeafIntersectionCount = std::accumulate(shadowLeafIntersectionPerDepthCount.begin(), shadowLeafIntersectionPerDepthCount.end(), 0ULL); shadowNodeIntersectionCount = std::accumulate(shadowNodeIntersectionPerDepthCount.begin(), shadowNodeIntersectionPerDepthCount.end(), 0ULL); primitiveIntersections = std::accumulate(primitiveIntersectionsPerPixel.begin(), primitiveIntersectionsPerPixel.end(), 0ULL); successfulPrimitiveIntersections = std::accumulate(successfulPrimitiveIntersectionsPerPixel.begin(), successfulPrimitiveIntersectionsPerPixel.end(), 0ULL); successfulAabbIntersections = std::accumulate(successfulAabbIntersectionsPerPixel.begin(), successfulAabbIntersectionsPerPixel.end(), 0ULL); aabbIntersections = std::accumulate(aabbIntersectionsPerPixel.begin(), aabbIntersectionsPerPixel.end(), 0ULL); shadowRayCount = std::accumulate(shadowRayCounter.begin(), shadowRayCounter.end(), 0ULL); shadowSuccessfulPrimitiveIntersections = std::accumulate(shadowSuccessfulPrimitiveIntersectionsPerPixel.begin(), shadowSuccessfulPrimitiveIntersectionsPerPixel.end(), 0ULL); shadowSuccessfulAabbIntersections = std::accumulate(shadowSuccessfulAabbIntersectionsPerPixel.begin(), shadowSuccessfulAabbIntersectionsPerPixel.end(), 0ULL); shadowAabbIntersections = std::accumulate(shadowAabbIntersectionsPerPixel.begin(), shadowAabbIntersectionsPerPixel.end(), 0ULL); shadowPrimitiveIntersections = std::accumulate(shadowPrimitiveIntersectionsPerPixel.begin(), shadowPrimitiveIntersectionsPerPixel.end(), 0ULL); //normalize by ray int primaryRayCount = width * height * cameraCount; float factor = 1 / (float)(primaryRayCount); float shadowFactor = 1 / (float)shadowRayCount; float bothFactor = 1 / (float)(primaryRayCount + shadowRayCount); if (!mute) { std::cout << "intersections counts are normalized per Ray" << std::endl << std::endl; std::cout << "primary intersections node: " << nodeIntersectionCount * factor << std::endl; std::cout << "primary aabb intersections: " << aabbIntersections * factor << std::endl; std::cout << "primary aabb success ration: " << successfulAabbIntersections / (float)aabbIntersections << std::endl; //wastefactor = "verschwendungsgrad". // basically number of nodes visited / number of aabb tested //the minus primaryRayCount is basically -1 for each ray -> needed to get right values float wasteFactor = (leafIntersectionCount + nodeIntersectionCount - primaryRayCount) / (float)(nodeIntersectionCount * bvh.branchingFactor); std::cout << "primary waste factor: " << 1 - wasteFactor << std::endl; std::cout << "primary intersections leaf: " << leafIntersectionCount * factor << std::endl; std::cout << "primary primitive intersections: " << primitiveIntersections * factor << std::endl; std::cout << "primary primitive success ratio: " << successfulPrimitiveIntersections / (float)primitiveIntersections << std::endl; std::cout << std::endl; std::cout << "secondary intersections node: " << shadowNodeIntersectionCount * shadowFactor << std::endl; std::cout << "secondary aabb intersections: " << shadowAabbIntersections * shadowFactor << std::endl; std::cout << "secondary aabb success ration: " << shadowSuccessfulAabbIntersections / (float)shadowAabbIntersections << std::endl; wasteFactor = (shadowLeafIntersectionCount + shadowNodeIntersectionCount - shadowRayCount) / (float)(shadowNodeIntersectionCount * bvh.branchingFactor); std::cout << "secondary waste factor: " << 1 - wasteFactor << std::endl; std::cout << "secondary intersections leaf: " << shadowLeafIntersectionCount * shadowFactor << std::endl; std::cout << "secondary primitive intersections: " << shadowPrimitiveIntersections * shadowFactor << std::endl; std::cout << "secondary primitive success ratio: " << shadowSuccessfulPrimitiveIntersections / (float)shadowPrimitiveIntersections << std::endl; } std::ofstream myfile(path + "/" + name + problem + "_Info.txt"); if (myfile.is_open()) { myfile << "scenario " << name << " with branching factor of " << std::to_string(bvh.branchingFactor) << " and leafsize of " << bvh.leafSize << std::endl; myfile << "intersections counts are normalized per Ray" << std::endl << std::endl; myfile << "primary intersections node: " << nodeIntersectionCount * factor << std::endl; myfile << "primary aabb intersections: " << aabbIntersections * factor << std::endl; myfile << "primary aabb success ration: " << successfulAabbIntersections / (float)aabbIntersections << std::endl; float wasteFactor = (leafIntersectionCount + nodeIntersectionCount - primaryRayCount) / (float)(nodeIntersectionCount * bvh.branchingFactor); myfile << "primary waste factor: " << 1 - wasteFactor << std::endl; myfile << "primary intersections leaf: " << leafIntersectionCount * factor << std::endl; myfile << "primary primitive intersections: " << primitiveIntersections * factor << std::endl; myfile << "primary primitive success ratio: " << successfulPrimitiveIntersections / (float)primitiveIntersections << std::endl; myfile << std::endl; myfile << "secondary intersections node: " << shadowNodeIntersectionCount * shadowFactor << std::endl; myfile << "secondary aabb intersections: " << shadowAabbIntersections * shadowFactor << std::endl; myfile << "secondary aabb success ration: " << shadowSuccessfulAabbIntersections / (float)shadowAabbIntersections << std::endl; wasteFactor = (shadowLeafIntersectionCount + shadowNodeIntersectionCount - shadowRayCount) / (float)(shadowNodeIntersectionCount * bvh.branchingFactor); myfile << "secondary waste factor: " << 1 - wasteFactor << std::endl; myfile << "secondary intersections leaf: " << shadowLeafIntersectionCount * shadowFactor << std::endl; myfile << "secondary primitive intersections: " << shadowPrimitiveIntersections * shadowFactor << std::endl; myfile << "secondary primitive success ratio: " << shadowSuccessfulPrimitiveIntersections / (float)shadowPrimitiveIntersections << std::endl; //this number is smaller than the nodecount + leafcount because the depth 0 intersections are left out //In addition: with shadow rays those also dont fit because shadowrays can stop when they find a tirangle myfile << std::endl; myfile << "intersections with nodes with x children :" << std::endl; float sum = 0; for (size_t i = 0; i < childFullness.size(); i++) { sum += childFullness[i] * i; } sum /= std::accumulate(childFullness.begin(), childFullness.end(), 0); myfile << "average child fullness: " << std::to_string(sum) << std::endl; for (size_t i = 0; i < childFullness.size(); i++) { //myfile << i << " : " << childFullness[i] * bothFactor << std::endl; myfile << i << " : " << childFullness[i] * factor << std::endl; } sum = 0; myfile << std::endl; myfile << "intersections with leaf nodes with x primitives :" << std::endl; for (size_t i = 0; i < primitiveFullness.size(); i++) { sum += primitiveFullness[i] * i; } sum /= std::accumulate(primitiveFullness.begin(), primitiveFullness.end(), 0); myfile << "average leaf fullness: " << std::to_string(sum) << std::endl; for (size_t i = 0; i < primitiveFullness.size(); i++) { //myfile << i << " : " << primitiveFullness[i] * bothFactor << std::endl; myfile << i << " : " << primitiveFullness[i] * factor << std::endl; } myfile << std::endl; myfile << "primary node intersections at depth x :" << std::endl; for (size_t i = 0; i < nodeIntersectionPerDepthCount.size(); i++) { myfile << i << " : " << nodeIntersectionPerDepthCount[i] * factor << std::endl; } myfile << std::endl; myfile << "primary leaf intersections at depth x :" << std::endl; for (size_t i = 0; i < leafIntersectionPerDepthCount.size(); i++) { myfile << i << " : " << leafIntersectionPerDepthCount[i] * factor << std::endl; } myfile << std::endl; myfile << "secondary node intersections at depth x :" << std::endl; for (size_t i = 0; i < shadowNodeIntersectionPerDepthCount.size(); i++) { myfile << i << " : " << shadowNodeIntersectionPerDepthCount[i] * shadowFactor << std::endl; } myfile << std::endl; myfile << "secondary leaf intersections at depth x :" << std::endl; for (size_t i = 0; i < shadowLeafIntersectionPerDepthCount.size(); i++) { myfile << i << " : " << shadowLeafIntersectionPerDepthCount[i] * shadowFactor << std::endl; } if (!saveDepthDebugImage) { myfile.close(); } } else std::cerr << "Unable to open file for image analysis resutls" << std::endl; myfile.close(); } //spawns rays and collects results into image. Image is written on disk template<typename T> void renderImage(bool saveImage, bool saveDepthDebugImage, CompactNodeManager<T>& nodeManager , Bvh& bvh, std::vector<std::unique_ptr<Light>>& lights, unsigned ambientSampleCount, float ambientDistance, bool castShadows, int renderType, bool mute, bool doWorkGroupAnalysis, int cameraId, bool wideAlternative) { int workGroupSize = nonTemplateWorkGroupSize; /* glm::vec3 decScale; glm::quat decOrientation; glm::vec3 decTranslation; glm::vec3 decSkew; glm::vec4 decPerspective; glm::decompose(transform, decScale, decOrientation, decTranslation, decSkew, decPerspective); */ //simplified ortho version for now: if (!wideRender) { //normal render: #pragma omp parallel for schedule(dynamic, 4) for (int i = 0; i < (width / workGroupSize) * (height / workGroupSize); i++) { for (int j = 0; j < workGroupSquare; j++) { RenderInfo info( ((i * workGroupSize) % width - width / 2.f) + j % workGroupSize, -(((i * workGroupSize) / width) * workGroupSize - height / 2.f) - (j / workGroupSize), (i * workGroupSize) % width + j % workGroupSize + (((i * workGroupSize) / width) * workGroupSize + (j / workGroupSize)) * width); int realIndex = i * workGroupSquare + j; glm::vec3 targetPos = getRayTargetPosition(info, cameraId); auto ray = Ray(positions[cameraId], targetPos - positions[cameraId], bvh); bool result; switch (renderType) { case 0: result = bvh.intersect(ray); break; case 1: result = nodeManager.intersect(ray); break; case 2: result = nodeManager.intersectImmediately(ray, false); break; case 3: result = nodeManager.intersectImmediately(ray, true); break; default: result = nodeManager.intersectImmediately(ray, true); break; } //check shadows and ambient occlusion if ray hit something if (result) { //ambient occlusion: unsigned ambientResult = 0; for (size_t i = 0; i < ambientSampleCount; i++) { //deterministic random direction auto direction = getAmbientDirection(realIndex, ray.surfaceNormal, i); Ray ambientRay(ray.surfacePosition + ray.surfaceNormal * 0.001f, direction, bvh, true); ambientRay.tMax = ambientDistance; if (shootShadowRay(ambientRay, ray, info, bvh, nodeManager, renderType)) { ambientResult++; } } if (ambientSampleCount != 0) { float factor = 1 - ambientResult / (float)ambientSampleCount; factor = (factor + 1) / 2.f; ray.surfaceColor.scale(factor); //ray.surfaceColor = Color(factor); } float factor = 1; //resolve shadows for (auto& l : lights) { float lightDistance; glm::vec3 lightVector; //could use light color auto lightColor = l->getLightDirection(ray.surfacePosition, lightVector, lightDistance); float f = glm::dot(ray.surfaceNormal, lightVector); //add bias to vector to prevent shadow rays hitting the surface they where created for Ray shadowRay(ray.surfacePosition + ray.surfaceNormal * 0.001f, lightVector, bvh, true); shadowRay.tMax = lightDistance; //only shoot ray when surface points in light direction if (castShadows && factor > 0) { if (shootShadowRay(shadowRay, ray, info, bvh, nodeManager, renderType)) { factor = 0; } } factor = std::max(0.3f, factor); ray.surfaceColor.scale(factor); } } image[info.index * 4 + 0] = (uint8_t)(ray.surfaceColor.r * 255); image[info.index * 4 + 1] = (uint8_t)(ray.surfaceColor.g * 255); image[info.index * 4 + 2] = (uint8_t)(ray.surfaceColor.b * 255); image[info.index * 4 + 3] = (uint8_t)(ray.surfaceColor.a * 255); //renders normal //image[info.index * 4 + 0] = (uint8_t)(ray.surfaceNormal.x * 127 + 127); //image[info.index * 4 + 1] = (uint8_t)(ray.surfaceNormal.y * 127 + 127); //image[info.index * 4 + 2] = (uint8_t)(ray.surfaceNormal.z * 127 + 127); collectPrimaryRayData(ray, info.index); } } } else { //wide render #pragma omp parallel for schedule(dynamic, 4) for (int i = 0; i < (width / workGroupSize) * (height / workGroupSize); i++) { //prepare rays for render chunk std::vector<Ray> rays(workGroupSquare); int tmp0 = ((i * workGroupSize) / width) * workGroupSize - height / 2; int tmp1 = ((i * workGroupSize) % width - width / 2); for (int j = 0; j < workGroupSquare; j++) { glm::vec3 targetPos = getRayTargetPosition( (-tmp0 - (j / workGroupSize)), (tmp1 + j % workGroupSize), cameraId); rays[j] = Ray(positions[cameraId], targetPos - positions[cameraId], bvh); } //shoot primary rays if (wideAlternative) { nodeManager.intersectWideAlternative(rays, nodeWorkPerStep[i], leafWorkPerStep[i], uniqueNodesPerStep[i], uniqueLeafsPerStep[i], terminationsPerStep[i]); } else { nodeManager.intersectWide(rays, nodeWorkPerStep[i], leafWorkPerStep[i], uniqueNodesPerStep[i], uniqueLeafsPerStep[i], terminationsPerStep[i]); } //shoot secondary rays std::vector<Ray> secondaryRays(workGroupSquare); std::vector<uint8_t> ambientResult(workGroupSquare); for (int a = 0; a < ambientSampleCount; a++) { for (int j = 0; j < workGroupSquare; j++) { if (isnan(rays[j].surfacePosition.x)) { secondaryRays[j] = Ray(glm::vec3(NAN), glm::vec3(NAN), bvh, true); secondaryRays[j].tMax = NAN; } else { auto direction = getAmbientDirection(i * workGroupSquare + j, rays[j].surfaceNormal, a); secondaryRays[j] = Ray(rays[j].surfacePosition + rays[j].surfaceNormal * 0.001f, direction, bvh, true); secondaryRays[j].tMax = ambientDistance; } } if (wideAlternative) { nodeManager.intersectWideAlternative(secondaryRays, secondaryNodeWorkPerStep[i], secondaryLeafWorkPerStep[i], secondaryUniqueNodesPerStep[i], secondaryUniqueLeafsPerStep[i], secondaryTerminationsPerStep[i]); } else { nodeManager.intersectWide(secondaryRays, secondaryNodeWorkPerStep[i], secondaryLeafWorkPerStep[i], secondaryUniqueNodesPerStep[i], secondaryUniqueLeafsPerStep[i], secondaryTerminationsPerStep[i]); } for (int j = 0; j < workGroupSquare; j++) { if (isnan(secondaryRays[j].tMax)) { ambientResult[j] ++; } int id = (i * workGroupSize) % width + j % workGroupSize + (((i * workGroupSize) / width) * workGroupSize + (j / workGroupSize)) * width; collectSecondaryRayData(secondaryRays[j], id); } } //write image for (int j = 0; j < workGroupSquare; j++) { int id = (i * workGroupSize) % width + j % workGroupSize + (((i * workGroupSize) / width) * workGroupSize + (j / workGroupSize)) * width; float factor = 1 - (ambientResult[j] / (float)ambientSampleCount); //factor = rays[j].tMax / 100.0f; uint8_t imageResult = (uint8_t)(factor * 255); image[id * 4 + 0] = imageResult; image[id * 4 + 1] = imageResult; image[id * 4 + 2] = imageResult; image[id * 4 + 3] = 255; collectPrimaryRayData(rays[j], id); } } } } private: template<typename T> bool shootShadowRay(Ray& shadowRay, Ray& ray, RenderInfo& info, Bvh& bvh, CompactNodeManager<T>& nodeManager, int& renderType) { bool result; switch (renderType) { case 0: result = bvh.intersect(shadowRay); break; case 1: result = nodeManager.intersect(shadowRay); break; case 2: result = nodeManager.intersectImmediately(shadowRay, false); break; case 3: result = nodeManager.intersectImmediately(shadowRay, true); break; default: result = nodeManager.intersectImmediately(shadowRay, true); break; } collectSecondaryRayData(shadowRay, info.index); return result; } void collectPrimaryRayData(const Ray& ray, int id) { //make sure i call the method correct in the future: if (ray.shadowRay) { std::cerr << "collect Primary data primaryRay is not a primary ray" << std::endl; } if (nodeIntersectionPerPixelCount[id].size() < ray.nodeIntersectionCount.size()) { nodeIntersectionPerPixelCount[id].resize(ray.nodeIntersectionCount.size()); } for (size_t i = 0; i < ray.nodeIntersectionCount.size(); i++) { nodeIntersectionPerPixelCount[id][i] += ray.nodeIntersectionCount[i]; } if (leafIntersectionPerPixelCount[id].size() < ray.leafIntersectionCount.size()) { leafIntersectionPerPixelCount[id].resize(ray.leafIntersectionCount.size()); } for (size_t i = 0; i < ray.leafIntersectionCount.size(); i++) { leafIntersectionPerPixelCount[id][i] += ray.leafIntersectionCount[i]; } if (childFullnessPerPixelCount[id].size() < ray.childFullness.size()) { childFullnessPerPixelCount[id].resize(ray.childFullness.size()); } for (size_t i = 0; i < ray.childFullness.size(); i++) { childFullnessPerPixelCount[id][i] += ray.childFullness[i]; } if (primitiveFullnessPerPixelCount[id].size() < ray.primitiveFullness.size()) { primitiveFullnessPerPixelCount[id].resize(ray.primitiveFullness.size()); } for (size_t i = 0; i < ray.primitiveFullness.size(); i++) { primitiveFullnessPerPixelCount[id][i] += ray.primitiveFullness[i]; } primitiveIntersectionsPerPixel[id] += ray.primitiveIntersectionCount; successfulPrimitiveIntersectionsPerPixel[id] += ray.successfulPrimitiveIntersectionCount; successfulAabbIntersectionsPerPixel[id] += ray.successfulAabbIntersectionCount; aabbIntersectionsPerPixel[id] += ray.aabbIntersectionCount; } void collectSecondaryRayData(const Ray& shadowRay, int id) { //make sure i call the method correct in the future: if (!shadowRay.shadowRay) { std::cerr << "collect secondary data shadowray is not a shadowray" << std::endl; } shadowRayCounter[id] ++; if (shadowNodeIntersectionPerPixelCount[id].size() < shadowRay.nodeIntersectionCount.size()) { shadowNodeIntersectionPerPixelCount[id].resize(shadowRay.nodeIntersectionCount.size()); } for (size_t i = 0; i < shadowRay.nodeIntersectionCount.size(); i++) { shadowNodeIntersectionPerPixelCount[id][i] += shadowRay.nodeIntersectionCount[i]; } if (shadowLeafIntersectionPerPixelCount[id].size() < shadowRay.leafIntersectionCount.size()) { shadowLeafIntersectionPerPixelCount[id].resize(shadowRay.leafIntersectionCount.size()); } for (size_t i = 0; i < shadowRay.leafIntersectionCount.size(); i++) { shadowLeafIntersectionPerPixelCount[id][i] += shadowRay.leafIntersectionCount[i]; } shadowPrimitiveIntersectionsPerPixel[id] += shadowRay.primitiveIntersectionCount; shadowSuccessfulPrimitiveIntersectionsPerPixel[id] += shadowRay.successfulPrimitiveIntersectionCount; shadowSuccessfulAabbIntersectionsPerPixel[id] += shadowRay.successfulAabbIntersectionCount; shadowAabbIntersectionsPerPixel[id] += shadowRay.aabbIntersectionCount; } void workGroupAnalysisPerImage(std::string& cameraName, bool wideAlternative) { int workGroupSize = nonTemplateWorkGroupSize; //First part is the wisker plot of workload. -> need min, max, median , and standard deviation std::string sizeName = "WorkGroupSize_" + std::to_string(workGroupSize) + "_Version_" + std::to_string(wideAlternative);; std::ofstream fileWorkGroup0(path + "/" + sizeName + "/" + name + problem + cameraName + "_PrimaryWorkGroupWiskerPlot.txt"); std::ofstream fileWorkGroup1(path + "/" + sizeName + "/" + name + problem + cameraName + "_SecondaryWorkGroupWiskerPlot.txt"); //struct to store the per workgroup information so we can later sort it correctly struct StorageStruct { int median; int min; int max; float avg; float sd; StorageStruct() { } StorageStruct(int median, int min, int max, float avg, float sd) :median(median), min(min), max(max), avg(avg), sd(sd) { } bool operator< (const StorageStruct& other) const { if (median == other.median) { return max < other.max; } else { return median < other.median; } } }; //later sorted by median std::vector<StorageStruct> primaryStorage((width / workGroupSize) * (height / workGroupSize)); std::vector<StorageStruct> secondaryStorage((width / workGroupSize) * (height / workGroupSize)); if (fileWorkGroup0.is_open() && fileWorkGroup1.is_open()) { int medianId = workGroupSquare * 0.5f; for (int i = 0; i < (width / workGroupSize) * (height / workGroupSize); i++) { std::vector<int> primaryDepth; primaryDepth.reserve(workGroupSquare); std::vector<int> secondaryDepth; secondaryDepth.reserve(workGroupSquare); int primaryWorkSum = 0; int secondaryWorkSum = 0; //make sure terminations per step counter are correct if (std::accumulate(terminationsPerStep[i].begin(), terminationsPerStep[i].end(), 0) != workGroupSquare) { std::cerr << "primary ray workgroup termination count != rays" << std::endl; } if (std::accumulate(secondaryTerminationsPerStep[i].begin(), secondaryTerminationsPerStep[i].end(), 0) != workGroupSquare) { std::cerr << "secondary ray workgroup termination count != rays" << std::endl; } //write depth of each ray into vector to calculate median, max, average, ez. for (int tId = 0; tId < terminationsPerStep[i].size(); tId++) { primaryWorkSum += tId * terminationsPerStep[i][tId]; for (int j = 0; j < terminationsPerStep[i][tId]; j++) { primaryDepth.push_back(tId); } } for (int tId = 0; tId < secondaryTerminationsPerStep[i].size(); tId++) { secondaryWorkSum += tId * secondaryTerminationsPerStep[i][tId]; for (int j = 0; j < secondaryTerminationsPerStep[i][tId]; j++) { secondaryDepth.push_back(tId); } } if (primaryDepth.size() != workGroupSquare) { std::cerr << "primaryDepth array in workgroup analysis has wrong size " << std::endl; } if (secondaryDepth.size() != workGroupSquare) { std::cerr << "secondaryDepth array in workgroup analysis has wrong size " << std::endl; } //take sum and max of node and leaf intersections float primaryWorkAverage = primaryWorkSum / (float)workGroupSquare; float secondaryWorkAverage = secondaryWorkSum / (float)(workGroupSquare); float primaryVariance = 0; float primarySd = 0; float secondaryVariance = 0; float secondarySd = 0; //loop for standard deviation / variance for (int j = 0; j < workGroupSquare; j++) { primaryVariance += pow((primaryDepth[j]) - primaryWorkAverage, 2); secondaryVariance += pow((secondaryDepth[j]) - secondaryWorkAverage, 2); } primaryVariance /= workGroupSquare; secondaryVariance /= workGroupSquare; primarySd = sqrt(primaryVariance); secondarySd = sqrt(secondaryVariance); //median and quartile: int primaryMax = primaryDepth[workGroupSquare - 1]; int secondaryMax = secondaryDepth[workGroupSquare - 1]; primaryStorage[i] = StorageStruct(primaryDepth[medianId], primaryDepth[0], primaryMax, primaryWorkAverage, primarySd); secondaryStorage[i] = StorageStruct(secondaryDepth[medianId], secondaryDepth[0], secondaryMax, secondaryWorkAverage, secondarySd); } std::sort(primaryStorage.begin(), primaryStorage.end()); std::sort(secondaryStorage.begin(), secondaryStorage.end()); fileWorkGroup0 << "median, min, max, lowerStdDeviation, upperStdDeviation" << std::endl; fileWorkGroup1 << "median, min, max, lowerStdDeviation, upperStdDeviation" << std::endl; for (int i = 0; i < (width / workGroupSize) * (height / workGroupSize); i++) { fileWorkGroup0 << primaryStorage[i].median << ", "; fileWorkGroup0 << primaryStorage[i].min << ", "; fileWorkGroup0 << primaryStorage[i].max << ", "; fileWorkGroup0 << primaryStorage[i].avg << ", "; fileWorkGroup0 << primaryStorage[i].sd << std::endl; fileWorkGroup1 << secondaryStorage[i].median << ", "; fileWorkGroup1 << secondaryStorage[i].min << ", "; fileWorkGroup1 << secondaryStorage[i].max << ", "; fileWorkGroup1 << secondaryStorage[i].avg << ", "; fileWorkGroup1 << secondaryStorage[i].sd << std::endl; } fileWorkGroup0.close(); fileWorkGroup1.close(); } else std::cerr << "Unable to open file for work group whisker plots" << std::endl; //second part is detailed analysis of when what work is done. std::ofstream fileWorkGroup(path + "/" + sizeName + "/" + name + problem + cameraName + "_WorkGroupData.txt"); if (fileWorkGroup.is_open()) { //what i want to show: for now average and ?standard deviation? of the new values the workGroupRenderer collects //when what work is done, and the number of unique nodes / leafs that are used. For primary and secondary ray each //in addition also how many rays terminate at each step(avg). fileWorkGroup << "stepId, avgPrimaryNodeWork, avgPrimaryNodeUnique, avgPrimaryLeafWork, avgPrimaryLeafUnique, avgPrimaryRayTermination, primaryNodeWorkMax, primaryNodeWorkMin, primaryLeafWorkMax, primaryLeafWorkMin, " << "avgSecondaryNodeWork, avgSecondaryNodeUnique, avgSecondaryLeafWork, avgSecondaryLeafUnique, avgSecondaryRayTermination, secondaryNodeWorkMax, secondaryNodeWorkMin, secondaryLeafWorkMax, secondaryLeafWorkMin" << std::endl; //get max size of nodeWorkPerStep: int maxSize = 0; for (int i = 0; i < (width / workGroupSize) * (height / workGroupSize); i++) { if (nodeWorkPerStep[i].size() > maxSize) { maxSize = nodeWorkPerStep[i].size(); } if (nodeWorkPerStep[i].size() > maxSize) { maxSize = secondaryNodeWorkPerStep[i].size(); } } //average calculation is done per workStep std::vector<float> nodeWorkPerStepAverage(maxSize, 0); std::vector<float> leafWorkPerStepAverage(maxSize, 0); std::vector<float> uniqueNodesPerStepAverage(maxSize, 0); std::vector<float> uniqueLeafsPerStepAverage(maxSize, 0); std::vector<float> terminatedRaysStepAverage(maxSize, 0); std::vector<float> secondaryNodeWorkPerStepAverage(maxSize, 0); std::vector<float> secondaryLeafWorkPerStepAverage(maxSize, 0); std::vector<float> secondaryUniqueNodesPerStepAverage(maxSize, 0); std::vector<float> secondaryUniqueLeafsPerStepAverage(maxSize, 0); std::vector<float> secondaryTerminatedRaysStepAverage(maxSize, 0); //go trough workSteps for (int j = 0; j < maxSize; j++) { //counter to calculate average. //general counters go over workgroups that still do work in this step //unique counters go over workroups that at least woked with one node / leaf int primaryCount = 0; int primaryNodeUniqueCount = 0; int primaryLeafUniqueCount = 0; int secondaryCount = 0; int secondaryNodeUniqueCount = 0; int secondaryLeafUniqueCount = 0; uint32_t primaryNodeUniqueMax = 0; uint32_t primaryNodeUniqueMin = workGroupSquare + 1; uint32_t primaryLeafUniqueMax = 0; uint32_t primaryLeafUniqueMin = workGroupSquare + 1; uint32_t secondaryNodeUniqueMax = 0; uint32_t secondaryNodeUniqueMin = workGroupSquare + 1; uint32_t secondaryLeafUniqueMax = 0; uint32_t secondaryLeafUniqueMin = workGroupSquare + 1; for (int i = 0; i < (width / workGroupSize) * (height / workGroupSize); i++) { if (terminationsPerStep[i].size() > j) { primaryCount++; nodeWorkPerStepAverage[j] += nodeWorkPerStep[i][j]; leafWorkPerStepAverage[j] += leafWorkPerStep[i][j]; uniqueNodesPerStepAverage[j] += uniqueNodesPerStep[i][j]; uniqueLeafsPerStepAverage[j] += uniqueLeafsPerStep[i][j]; terminatedRaysStepAverage[j] += terminationsPerStep[i][j]; if (uniqueNodesPerStep[i][j] != 0) { primaryNodeUniqueCount++; primaryNodeUniqueMax = std::max(uniqueNodesPerStep[i][j], primaryNodeUniqueMax); primaryNodeUniqueMin = std::min(uniqueNodesPerStep[i][j], primaryNodeUniqueMin); } if (uniqueLeafsPerStep[i][j] != 0) { primaryLeafUniqueCount++; primaryLeafUniqueMax = std::max(uniqueLeafsPerStep[i][j], primaryLeafUniqueMax); primaryLeafUniqueMin = std::min(uniqueLeafsPerStep[i][j], primaryLeafUniqueMin); } } if (secondaryNodeWorkPerStep[i].size() > j) { secondaryCount++; secondaryNodeWorkPerStepAverage[j] += secondaryNodeWorkPerStep[i][j]; secondaryLeafWorkPerStepAverage[j] += secondaryLeafWorkPerStep[i][j]; secondaryUniqueNodesPerStepAverage[j] += secondaryUniqueNodesPerStep[i][j]; secondaryUniqueLeafsPerStepAverage[j] += secondaryUniqueLeafsPerStep[i][j]; secondaryTerminatedRaysStepAverage[j] += secondaryTerminationsPerStep[i][j]; if (secondaryUniqueNodesPerStep[i][j] != 0) { secondaryNodeUniqueCount++; secondaryNodeUniqueMax = std::max(secondaryUniqueNodesPerStep[i][j], secondaryNodeUniqueMax); secondaryNodeUniqueMin = std::min(secondaryUniqueNodesPerStep[i][j], secondaryNodeUniqueMin); } if (secondaryUniqueLeafsPerStep[i][j] != 0) { secondaryLeafUniqueCount++; secondaryLeafUniqueMax = std::max(secondaryUniqueLeafsPerStep[i][j], secondaryLeafUniqueMax); secondaryLeafUniqueMin = std::min(secondaryUniqueLeafsPerStep[i][j], secondaryLeafUniqueMin); } } } //fix nan error for 0/0: primaryCount = std::max(primaryCount, 1); primaryNodeUniqueCount = std::max(primaryNodeUniqueCount, 1); primaryLeafUniqueCount = std::max(primaryLeafUniqueCount, 1); secondaryCount = std::max(secondaryCount, 1); secondaryNodeUniqueCount = std::max(secondaryNodeUniqueCount, 1); secondaryLeafUniqueCount = std::max(secondaryLeafUniqueCount, 1); //set those min that didnt change 0: if (primaryNodeUniqueMin == workGroupSquare + 1) { primaryNodeUniqueMin = 0; } if (primaryLeafUniqueMin == workGroupSquare + 1) { primaryLeafUniqueMin = 0; } if (secondaryNodeUniqueMin == workGroupSquare + 1) { secondaryNodeUniqueMin = 0; } if (secondaryLeafUniqueMin == workGroupSquare + 1) { secondaryLeafUniqueMin = 0; } //calculate average nodeWorkPerStepAverage[j] /= (float)primaryCount; leafWorkPerStepAverage[j] /= (float)primaryCount; uniqueNodesPerStepAverage[j] /= (float)primaryNodeUniqueCount; uniqueLeafsPerStepAverage[j] /= (float)primaryLeafUniqueCount; terminatedRaysStepAverage[j] /= (float)(width / workGroupSize) * (height / workGroupSize); secondaryNodeWorkPerStepAverage[j] /= (float)secondaryCount; secondaryLeafWorkPerStepAverage[j] /= (float)secondaryCount; secondaryUniqueNodesPerStepAverage[j] /= (float)secondaryNodeUniqueCount; secondaryUniqueLeafsPerStepAverage[j] /= (float)secondaryLeafUniqueCount; secondaryTerminatedRaysStepAverage[j] /= (float)(width / workGroupSize) * (height / workGroupSize); //add Terminated rays together: if (j != 0) { terminatedRaysStepAverage[j] += terminatedRaysStepAverage[j - 1]; secondaryTerminatedRaysStepAverage[j] += secondaryTerminatedRaysStepAverage[j - 1]; } //could also do standard deviation? (mean doesnt really make sense) //values are written into file in step order. fileWorkGroup << j << ", "; fileWorkGroup << nodeWorkPerStepAverage[j] << ", "; fileWorkGroup << uniqueNodesPerStepAverage[j] << ", "; fileWorkGroup << leafWorkPerStepAverage[j] << ", "; fileWorkGroup << uniqueLeafsPerStepAverage[j] << ", "; fileWorkGroup << terminatedRaysStepAverage[j] << ", "; fileWorkGroup << primaryNodeUniqueMax << ", "; fileWorkGroup << primaryNodeUniqueMin << ", "; fileWorkGroup << primaryLeafUniqueMax << ", "; fileWorkGroup << primaryLeafUniqueMin << ", "; fileWorkGroup << secondaryNodeWorkPerStepAverage[j] << ", "; fileWorkGroup << secondaryUniqueNodesPerStepAverage[j] << ", "; fileWorkGroup << secondaryLeafWorkPerStepAverage[j] << ", "; fileWorkGroup << secondaryUniqueLeafsPerStepAverage[j] << ", "; fileWorkGroup << secondaryTerminatedRaysStepAverage[j] << ", "; fileWorkGroup << secondaryNodeUniqueMax << ", "; fileWorkGroup << secondaryNodeUniqueMin << ", "; fileWorkGroup << secondaryLeafUniqueMax << ", "; fileWorkGroup << secondaryLeafUniqueMin << std::endl; } fileWorkGroup.close(); } else std::cerr << "Unable to open file for work group analysis" << std::endl; //now ammount of unique nodes and leafs loaded per workgroup + average and min max of what would have been loaded without wide std::ofstream fileUniqueWork(path + "/" + sizeName + "/" + name + problem + cameraName + "_WorkGroupUniqueWork.txt"); if (fileUniqueWork.is_open()) { //The values are per workGroup fileUniqueWork << "loadedPrimaryNodes, loadedPrimaryLeafs, loadedPrimaryNodesMax, loadedPrimaryLeafsMax, loadedPrimaryNodesMin, loadedPrimaryLeafsMin, "; fileUniqueWork << "loadedSecondaryNodes, loadedSecondaryLeafs, loadedSecondaryNodesMax, loadedSecondaryLeafsMax, loadedSecondaryNodesMin, loadedSecondaryLeafsMin, "; fileUniqueWork << "loadedWidePrimaryNodes, loadedWidePrimaryLeafs, loadedWideSecondaryNodes, loadedWideSecondaryLeafs" << std::endl; for (int i = 0; i < (width / workGroupSize) * (height / workGroupSize); i++) { float loadedPrimaryNodes = 0; float loadedPrimaryLeafs = 0; int loadedPrimaryNodesMax = 0; int loadedPrimaryLeafsMax = 0; int loadedPrimaryNodesMin = 1000; int loadedPrimaryLeafsMin = 1000; float loadedSecondaryNodes = 0; float loadedSecondaryLeafs = 0; int loadedSecondaryNodesMax = 0; int loadedSecondaryLeafsMax = 0; int loadedSecondaryNodesMin = 1000; int loadedSecondaryLeafsMin = 1000; float loadedWidePrimaryNodes = std::accumulate(uniqueNodesPerStep[i].begin(), uniqueNodesPerStep[i].end(), 0); float loadedWidePrimaryLeafs = std::accumulate(uniqueLeafsPerStep[i].begin(), uniqueLeafsPerStep[i].end(), 0); float loadedWideSecondaryNodes = std::accumulate(secondaryUniqueNodesPerStep[i].begin(), secondaryUniqueNodesPerStep[i].end(), 0); float loadedWideSecondaryLeafs = std::accumulate(secondaryUniqueLeafsPerStep[i].begin(), secondaryUniqueLeafsPerStep[i].end(), 0); //loop over single rays for how many node and leafs have been intersected (-> loaded nodes) for (int j = 0; j < workGroupSquare; j++) { int index = (i * workGroupSize) % width + (j % workGroupSize) + (((i * workGroupSize) / width) * workGroupSize + (j / workGroupSize)) * width; int realIndex = i * workGroupSquare + j; int tmp0 = std::accumulate(nodeIntersectionPerPixelCount[index].begin(), nodeIntersectionPerPixelCount[index].end(), 0); tmp0 -= nodeIntersectionPerPixelCountCameraSum[index]; loadedPrimaryNodes += tmp0; loadedPrimaryNodesMax = std::max(tmp0, loadedPrimaryNodesMax); loadedPrimaryNodesMin = std::min(tmp0, loadedPrimaryNodesMin); int tmp1 = std::accumulate(shadowNodeIntersectionPerPixelCount[index].begin(), shadowNodeIntersectionPerPixelCount[index].end(), 0); tmp1 -= shadowNodeIntersectionPerPixelCountCameraSum[index]; loadedSecondaryNodes += tmp1; loadedSecondaryNodesMax = std::max(tmp1, loadedSecondaryNodesMax); loadedSecondaryNodesMin = std::min(tmp1, loadedSecondaryNodesMin); int tmp2 = std::accumulate(leafIntersectionPerPixelCount[index].begin(), leafIntersectionPerPixelCount[index].end(), 0); tmp2 -= leafIntersectionPerPixelCountCameraSum[index]; loadedPrimaryLeafs += tmp2; loadedPrimaryLeafsMax = std::max(tmp2, loadedPrimaryLeafsMax); loadedPrimaryLeafsMin = std::min(tmp2, loadedPrimaryLeafsMin); int tmp3 = std::accumulate(shadowLeafIntersectionPerPixelCount[index].begin(), shadowLeafIntersectionPerPixelCount[index].end(), 0); tmp3 -= shadowLeafIntersectionPerPixelCountCameraSum[index]; loadedSecondaryLeafs += tmp3; loadedSecondaryLeafsMax = std::max(tmp3, loadedSecondaryLeafsMax); loadedSecondaryLeafsMin = std::min(tmp3, loadedSecondaryLeafsMin); nodeIntersectionPerPixelCountCameraSum[index] += tmp0; shadowNodeIntersectionPerPixelCountCameraSum[index] += tmp1; leafIntersectionPerPixelCountCameraSum[index] += tmp2; shadowLeafIntersectionPerPixelCountCameraSum[index] += tmp3; } //set the min values that didnt have any values to 0 if (loadedPrimaryNodesMin == 1000) { loadedPrimaryNodesMin = 0; } if (loadedPrimaryLeafsMin == 1000) { loadedPrimaryLeafsMin = 0; } if (loadedSecondaryNodesMin == 1000) { loadedSecondaryNodesMin = 0; } if (loadedSecondaryLeafsMin == 1000) { loadedSecondaryLeafsMin = 0; } /* loadedPrimaryNodes /= (float)workGroupSquare; loadedPrimaryLeafs /= (float)workGroupSquare; loadedSecondaryNodes /= (float)workGroupSquare; loadedSecondaryLeafs /= (float)workGroupSquare; loadedWidePrimaryNodes /= (float)workGroupSquare; loadedWidePrimaryLeafs /= (float)workGroupSquare; loadedWideSecondaryNodes /= (float)workGroupSquare; loadedWideSecondaryLeafs /= (float)workGroupSquare; */ fileUniqueWork << loadedPrimaryNodes << ", "; fileUniqueWork << loadedPrimaryLeafs << ", "; fileUniqueWork << loadedPrimaryNodesMax << ", "; fileUniqueWork << loadedPrimaryLeafsMax << ", "; fileUniqueWork << loadedPrimaryNodesMin << ", "; fileUniqueWork << loadedPrimaryLeafsMin << ", "; fileUniqueWork << loadedSecondaryNodes << ", "; fileUniqueWork << loadedSecondaryLeafs << ", "; fileUniqueWork << loadedSecondaryNodesMax << ", "; fileUniqueWork << loadedSecondaryLeafsMax << ", "; fileUniqueWork << loadedSecondaryNodesMin << ", "; fileUniqueWork << loadedSecondaryLeafsMin << ", "; fileUniqueWork << loadedWidePrimaryNodes << ", "; fileUniqueWork << loadedWidePrimaryLeafs << ", "; fileUniqueWork << loadedWideSecondaryNodes << ", "; fileUniqueWork << loadedWideSecondaryLeafs << std::endl; } fileUniqueWork.close(); } } void initializeVariables() { nodeIntersectionPerPixelCount.resize(height * width); leafIntersectionPerPixelCount.resize(height * width); shadowNodeIntersectionPerPixelCount.resize(height * width); shadowLeafIntersectionPerPixelCount.resize(height * width); childFullnessPerPixelCount.resize(height * width); primitiveFullnessPerPixelCount.resize(height * width); primitiveIntersectionsPerPixel.resize(height * width); successfulPrimitiveIntersectionsPerPixel.resize(height * width); successfulAabbIntersectionsPerPixel.resize(height * width); aabbIntersectionsPerPixel.resize(height * width); shadowSuccessfulAabbIntersectionsPerPixel.resize(height * width); shadowRayCounter.resize(height * width); shadowAabbIntersectionsPerPixel.resize(height * width); shadowPrimitiveIntersectionsPerPixel.resize(height * width); shadowSuccessfulPrimitiveIntersectionsPerPixel.resize(height * width); nodeIntersectionCount = 0; leafIntersectionCount = 0; primitiveIntersections = 0; shadowPrimitiveIntersections = 0; successfulPrimitiveIntersections = 0; successfulAabbIntersections = 0; aabbIntersections = 0; shadowSuccessfulAabbIntersections = 0; shadowAabbIntersections = 0; shadowSuccessfulPrimitiveIntersections = 0; shadowRayCount = 0; shadowLeafIntersectionCount = 0; shadowNodeIntersectionCount = 0; if (wideRender) { nodeIntersectionPerPixelCountCameraSum.resize(height * width); shadowNodeIntersectionPerPixelCountCameraSum.resize(height * width); leafIntersectionPerPixelCountCameraSum.resize(height * width); shadowLeafIntersectionPerPixelCountCameraSum.resize(height * width); } //wide render data is initialized and reset in camrea loop since its only needed inside loop } void createDepthDebugImage(int maxDepth) { //save an image with all the aabb intersections for every depth for (size_t d = 0; d < maxDepth; d++) { uint16_t depthIntersections = 0; //find max element first to normalise to; #pragma omp parallel for schedule(static, 128) for (int i = 0; i < width * height; i++) { if (d < nodeIntersectionPerPixelCount[i].size()) { depthIntersections = std::max(nodeIntersectionPerPixelCount[i][d], depthIntersections); } } //go trough RenderInfo vector and use the stored nodeIntersectionPerPixelCount #pragma omp parallel for schedule(static, 128) for (int i = 0; i < width * height; i++) { uint16_t sum = 0; if (d < nodeIntersectionPerPixelCount[i].size()) { sum = nodeIntersectionPerPixelCount[i][d]; } //Color c(sum * 0.01f); Color c(sum * (1 / (float)depthIntersections)); image[i * 4 + 0] = (uint8_t)(c.r * 255); image[i * 4 + 1] = (uint8_t)(c.g * 255); image[i * 4 + 2] = (uint8_t)(c.b * 255); image[i * 4 + 3] = (uint8_t)(c.a * 255); } encodeTwoSteps(path + "/" + name + problem + "_NodeDepth" + std::to_string(d) + ".png", image, width, height); } unsigned maxNodeSum = 0; unsigned maxLeafSum = 0; //find min and max for nodeintersection and leafintersection: (and number of different depth intersections #pragma omp parallel for schedule(static, 128) for (int i = 0; i < width * height; i++) { unsigned sum = std::accumulate(nodeIntersectionPerPixelCount[i].begin(), nodeIntersectionPerPixelCount[i].end(), 0); maxNodeSum = std::max(sum, maxNodeSum); sum = std::accumulate(leafIntersectionPerPixelCount[i].begin(), leafIntersectionPerPixelCount[i].end(), 0); maxLeafSum = std::max(sum, maxLeafSum); } float normalisation = 1 / (float)maxNodeSum; //pixel bvh depth //std::cout << normalisation << std::endl; //std::cout << minSum << std::endl; //std::cout << maxSum << std::endl; #pragma omp parallel for schedule(static, 128) for (int i = 0; i < width * height; i++) { unsigned sum = std::accumulate(nodeIntersectionPerPixelCount[i].begin(), nodeIntersectionPerPixelCount[i].end(), 0); Color c(sum * normalisation); image[i * 4 + 0] = (uint8_t)(c.r * 255); image[i * 4 + 1] = (uint8_t)(c.g * 255); image[i * 4 + 2] = (uint8_t)(c.b * 255); image[i * 4 + 3] = (uint8_t)(c.a * 255); } encodeTwoSteps(path + "/" + name + problem + "_NodeIntersectionCount.png", image, width, height); normalisation = 1.0 / maxLeafSum; //std::cout << maxLeafSum << std::endl; #pragma omp parallel for schedule(static, 128) for (int i = 0; i < width * height; i++) { unsigned sum = std::accumulate(leafIntersectionPerPixelCount[i].begin(), leafIntersectionPerPixelCount[i].end(), 0); Color c(sum * normalisation); image[i * 4 + 0] = (uint8_t)(c.r * 255); image[i * 4 + 1] = (uint8_t)(c.g * 255); image[i * 4 + 2] = (uint8_t)(c.b * 255); image[i * 4 + 3] = (uint8_t)(c.a * 255); } encodeTwoSteps(path + "/" + name + problem + "_LeafIntersectionCount.png", image, width, height); } void initializeWideRenderVariables() { //reset and initialize the vectors. int size = (width / nonTemplateWorkGroupSize) * (height / nonTemplateWorkGroupSize); //reset if they already exist if (!nodeWorkPerStep.empty()) { nodeWorkPerStep.clear(); leafWorkPerStep.clear(); terminationsPerStep.clear(); uniqueNodesPerStep.clear(); uniqueLeafsPerStep.clear(); secondaryNodeWorkPerStep.clear(); secondaryLeafWorkPerStep.clear(); secondaryTerminationsPerStep.clear(); secondaryUniqueNodesPerStep.clear(); secondaryUniqueLeafsPerStep.clear(); } nodeWorkPerStep.resize(size); leafWorkPerStep.resize(size); terminationsPerStep.resize(size); uniqueNodesPerStep.resize(size); uniqueLeafsPerStep.resize(size); secondaryNodeWorkPerStep.resize(size); secondaryLeafWorkPerStep.resize(size); secondaryTerminationsPerStep.resize(size); secondaryUniqueNodesPerStep.resize(size); secondaryUniqueLeafsPerStep.resize(size); } };
mxnet_op.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file mxnet_op.h * \brief * \author Junyuan Xie */ #ifndef MXNET_OPERATOR_MXNET_OP_H_ #define MXNET_OPERATOR_MXNET_OP_H_ #include <dmlc/omp.h> #include <mxnet/base.h> #include <mxnet/engine.h> #include <mxnet/op_attr_types.h> #include <algorithm> #include "./operator_tune.h" #include "../engine/openmp.h" #ifdef __CUDACC__ #include "../common/cuda_utils.h" #endif // __CUDACC__ namespace mxnet { namespace op { namespace mxnet_op { using namespace mshadow; #ifdef __CUDA_ARCH__ __constant__ const float PI = 3.14159265358979323846; #else const float PI = 3.14159265358979323846; using std::isnan; #endif template<typename xpu> int get_num_threads(const int N); #ifdef __CUDACC__ #define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \ i < (n); \ i += blockDim.x * gridDim.x) inline cudaDeviceProp cuda_get_device_prop() { int device; CUDA_CALL(cudaGetDevice(&device)); cudaDeviceProp deviceProp; CUDA_CALL(cudaGetDeviceProperties(&deviceProp, device)); return deviceProp; } /*! * \brief Get the number of blocks for cuda kernel given N */ inline int cuda_get_num_blocks(const int N) { using namespace mshadow::cuda; return std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); } template<> inline int get_num_threads<gpu>(const int N) { using namespace mshadow::cuda; return kBaseThreadNum * cuda_get_num_blocks(N); } #endif // __CUDACC__ template<> inline int get_num_threads<cpu>(const int N) { return engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); } /*! \brief operator request type switch */ #define MXNET_ASSIGN_REQ_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } /*! \brief operator request type switch */ #define MXNET_REQ_TYPE_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ { \ const OpReqType ReqType = kNullOp; \ {__VA_ARGS__} \ } \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } #define MXNET_NDIM_SWITCH(NDim, ndim, ...) \ if (NDim == 0) { \ } else if (NDim == 1) { \ const int ndim = 1; \ {__VA_ARGS__} \ } else if (NDim == 2) { \ const int ndim = 2; \ {__VA_ARGS__} \ } else if (NDim == 3) { \ const int ndim = 3; \ {__VA_ARGS__} \ } else if (NDim == 4) { \ const int ndim = 4; \ {__VA_ARGS__} \ } else if (NDim == 5) { \ const int ndim = 5; \ {__VA_ARGS__} \ } else { \ LOG(FATAL) << "ndim=" << NDim << "too large "; \ } #define MXNET_NO_INT8_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_NO_FLOAT16_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ LOG(FATAL) << "This operation does not " \ "support float16"; \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_REAL_ACC_TYPE_SWITCH(type, DType, AType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ typedef float AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ typedef uint8_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types not uint8"; \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ typedef int8_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types not int8"; \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ typedef int32_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types, not int32"; \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ typedef int64_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types, not int64"; \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_ACC_TYPE_SWITCH(type, DType, AType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ typedef float AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ typedef uint32_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ typedef int32_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ typedef int64_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ typedef int64_t AType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } /*! * \brief assign the val to out according * to request in Kernel::Launch * \param out the data to be assigned * \param req the assignment request * \param val the value to be assigned to out * \tparam OType output type * \tparam VType value type */ #define KERNEL_ASSIGN(out, req, val) \ { \ switch (req) { \ case kNullOp: \ break; \ case kWriteTo: \ case kWriteInplace: \ (out) = (val); \ break; \ case kAddTo: \ (out) += (val); \ break; \ default: \ break; \ } \ } #define MXNET_ADD_ALL_TYPES \ .add_enum("float32", mshadow::kFloat32) \ .add_enum("float64", mshadow::kFloat64) \ .add_enum("float16", mshadow::kFloat16) \ .add_enum("uint8", mshadow::kUint8) \ .add_enum("int8", mshadow::kInt8) \ .add_enum("int32", mshadow::kInt32) \ .add_enum("int64", mshadow::kInt64) /* \brief Compute flattened index given coordinates and shape. */ template<int ndim> MSHADOW_XINLINE index_t ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) { index_t ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret = ret * shape[i] + (shape[i] > coord[i]) * coord[i]; } return ret; } /* Compute coordinates from flattened index given shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> unravel(const index_t idx, const Shape<ndim>& shape) { Shape<ndim> ret; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto tmp = j / shape[i]; ret[i] = j - tmp*shape[i]; j = tmp; } return ret; } /* Compute dot product of two vector */ template<int ndim> MSHADOW_XINLINE index_t dot(const Shape<ndim>& coord, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret += coord[i] * stride[i]; } return ret; } /* Combining unravel and dot */ template<int ndim> MSHADOW_XINLINE index_t unravel_dot(const index_t idx, const Shape<ndim>& shape, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto tmp = j / shape[i]; ret += (j - tmp*shape[i])*stride[i]; j = tmp; } return ret; } /* Calculate stride of each dim from shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) { Shape<ndim> stride; index_t cumprod = 1; #pragma unroll for (int i = ndim - 1; i >= 0; --i) { stride[i] = (shape[i] > 1) ? cumprod : 0; cumprod *= shape[i]; } return stride; } /* Increment coordinates and modify index */ template<int ndim> MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape, index_t* idx, const Shape<ndim>& stride) { ++(*coord)[ndim-1]; *idx += stride[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; *idx = *idx + stride[i-1] - shape[i] * stride[i]; } } /* Increment coordinates and modify index */ template<int ndim> MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape, index_t* idx1, const Shape<ndim>& stride1, index_t* idx2, const Shape<ndim>& stride2) { ++(*coord)[ndim-1]; *idx1 += stride1[ndim-1]; *idx2 += stride2[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; *idx1 = *idx1 + stride1[i-1] - shape[i] * stride1[i]; *idx2 = *idx2 + stride2[i-1] - shape[i] * stride2[i]; } } /*! * \brief Simple copy data from one blob to another * \param to Destination blob * \param from Source blob */ template <typename xpu> MSHADOW_CINLINE void copy(mshadow::Stream<xpu> *s, const TBlob& to, const TBlob& from) { CHECK_EQ(from.Size(), to.Size()); CHECK_EQ(from.dev_mask(), to.dev_mask()); MSHADOW_TYPE_SWITCH(to.type_flag_, DType, { if (to.type_flag_ == from.type_flag_) { mshadow::Copy(to.FlatTo1D<xpu, DType>(s), from.FlatTo1D<xpu, DType>(s), s); } else { MSHADOW_TYPE_SWITCH(from.type_flag_, SrcDType, { to.FlatTo1D<xpu, DType>(s) = mshadow::expr::tcast<DType>(from.FlatTo1D<xpu, SrcDType>(s)); }) } }) } /*! \brief Binary op backward gradient OP wrapper */ template<typename GRAD_OP> struct backward_grad { /* \brief Backward calc with grad * \param a - output grad * \param args... - data to grad calculation op (what this is -- input, output, etc. -- varies) * \return input grad */ template<typename DType, typename ...Args> MSHADOW_XINLINE static DType Map(DType a, Args... args) { return DType(a * GRAD_OP::Map(args...)); } }; /*! \brief Binary op backward gradient OP wrapper (tuned) */ template<typename GRAD_OP> struct backward_grad_tuned : public backward_grad<GRAD_OP>, public tunable { using backward_grad<GRAD_OP>::Map; }; /*! \brief Select assignment operation based upon the req value * Also useful for mapping mshadow Compute (F<OP>) to Kernel<OP>::Launch */ template<typename OP, int req> struct op_with_req { typedef OP Operation; /*! \brief input is one tensor */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i])); } /*! \brief inputs are two tensors */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *lhs, const DType *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief input is tensor and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value)); } /*! \brief input is tensor and two scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in, const DType value_1, const DType value_2) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value_1, value_2)); } /*! \brief No inputs (ie fill to constant value) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out) { KERNEL_ASSIGN(out[i], req, OP::Map()); } /*! \brief input is single scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(value)); } /*! \brief inputs are two tensors and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *input_1, const DType *input_2, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], value)); } /*! \brief inputs are three tensors (ie backward grad with binary grad function) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *input_1, const DType *input_2, const DType *input_3) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], input_3[i])); } }; template<typename OP, typename xpu> struct Kernel; /*! * \brief CPU Kernel launcher * \tparam OP Operator to launch */ template<typename OP> struct Kernel<OP, cpu> { /*! * \brief Launch a generic CPU kernel. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function */ template<typename ...Args> inline static bool Launch(mshadow::Stream<cpu> *, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); ++i) { OP::Map(i, args...); } } #else for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif return true; } /*! * \brief Launch a generic CPU kernel with dynamic schedule. This is recommended * for irregular workloads such as spmv. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function */ template<typename ...Args> inline static bool LaunchDynamic(mshadow::Stream<cpu> *, const int64_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(false); if (omp_threads < 2) { for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) schedule(dynamic) for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } } #else for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif return true; } /*! * \brief Launch CPU kernel which has OMP tuning data available. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam PRIMITIVE_OP The primitive operation to use for tuning * \tparam DType Data type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param dest Destination pointer (used to infer DType) * \param args Varargs to eventually pass to the OP::Map() function */ template<typename PRIMITIVE_OP, typename DType, typename ...Args> static void LaunchTuned(mshadow::Stream<cpu> *, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2 || !tuned_op<PRIMITIVE_OP, DType>::UseOMP( N, static_cast<size_t>(omp_threads))) { for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); ++i) { OP::Map(i, args...); } } #else for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif } /*! * \brief Launch custom-tuned kernel where each thread is set to * operate on a contiguous partition * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the UseOMP() and OP::Map() functions */ template<typename ...Args> inline static void LaunchEx(mshadow::Stream<cpu> *s, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { OP::Map(0, N, args...); } else { const auto length = (N + omp_threads - 1) / omp_threads; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); i += length) { OP::Map(i, i + length > N ? N - i : length, args...); } } #else OP::Map(0, N, args...); #endif } /*! * \brief Launch a tunable OP with implicitly-supplied data type * \tparam DType Data type * \tparam T OP type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param s Stream (usually null for CPU) * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function * \return Always true */ template<typename DType, typename T = OP, typename ...Args> static MSHADOW_CINLINE typename std::enable_if<std::is_base_of<tunable, T>::value, bool>::type Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) { LaunchTuned<T, DType>(s, N, dest, args...); return true; } /*! * \brief Launch a tunable OP wrapper with explicitly-supplied data type (ie op_with_req) * \tparam DType Data type * \tparam T Wrapper type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param s Stream (usually null for CPU) * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function * \return Always true */ template<typename DType, typename T = OP, typename ...Args> static MSHADOW_CINLINE typename std::enable_if<std::is_base_of<tunable, typename T::Operation>::value, bool>::type Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) { LaunchTuned<typename T::Operation, DType>(s, N, dest, args...); return true; } }; #ifdef __CUDACC__ template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, args...); } } template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel_ex(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, 1, args...); } } template<typename OP> struct Kernel<OP, gpu> { /*! \brief Launch GPU kernel */ template<typename ...Args> inline static void Launch(mshadow::Stream<gpu> *s, int N, Args... args) { if (0 == N) return; using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); mxnet_generic_kernel<OP, Args...> <<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>( N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel); } template<typename ...Args> inline static void LaunchEx(mshadow::Stream<gpu> *s, const int N, Args... args) { if (0 == N) return; using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); mxnet_generic_kernel_ex<OP, Args...> <<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>( N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel_ex); } }; #endif // __CUDACC__ /*! * \brief Set to immediate scalar value kernel * \tparam val Scalar immediate */ template<int val> struct set_to_int : public tunable { // mxnet_op version (when used directly with Kernel<>::Launch()) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out) { out[i] = DType(val); } // mshadow_op version (when used with op_with_req<>) MSHADOW_XINLINE static int Map() { return val; } }; /*! * \brief Special-case kernel shortcut for setting to zero and one */ using set_zero = set_to_int<0>; using set_one = set_to_int<1>; } // namespace mxnet_op } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_MXNET_OP_H_
GB_unop__lnot_bool_bool.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__lnot_bool_bool) // op(A') function: GB (_unop_tran__lnot_bool_bool) // C type: bool // A type: bool // cast: bool cij = aij // unaryop: cij = !aij #define GB_ATYPE \ bool #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !x ; // casting #define GB_CAST(z, aij) \ bool z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ bool z = aij ; \ Cx [pC] = !z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__lnot_bool_bool) ( bool *Cx, // Cx and Ax may be aliased const bool *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++) { bool aij = Ax [p] ; bool 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 ; bool aij = Ax [p] ; bool z = aij ; Cx [p] = !z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__lnot_bool_bool) ( 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
qr_decompose.h
/** * @file * \brief Library functions to compute [QR * decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of a given * matrix. * \author [Krishna Vedala](https://github.com/kvedala) */ #ifndef QR_DECOMPOSE_H #define QR_DECOMPOSE_H #include <math.h> #include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #endif /** * function to display matrix on stdout */ void print_matrix(double **A, /**< matrix to print */ int M, /**< number of rows of matrix */ int N) /**< number of columns of matrix */ { for (int row = 0; row < M; row++) { for (int col = 0; col < N; col++) printf("% 9.3g\t", A[row][col]); putchar('\n'); } putchar('\n'); } /** * Compute dot product of two vectors of equal lengths * * If \f$\vec{a}=\left[a_0,a_1,a_2,...,a_L\right]\f$ and * \f$\vec{b}=\left[b_0,b_1,b_1,...,b_L\right]\f$ then * \f$\vec{a}\cdot\vec{b}=\displaystyle\sum_{i=0}^L a_i\times b_i\f$ * * \returns \f$\vec{a}\cdot\vec{b}\f$ */ double vector_dot(double *a, double *b, int L) { double mag = 0.f; int i; #ifdef _OPENMP // parallelize on threads #pragma omp parallel for reduction(+ : mag) #endif for (i = 0; i < L; i++) mag += a[i] * b[i]; return mag; } /** * Compute magnitude of vector. * * If \f$\vec{a}=\left[a_0,a_1,a_2,...,a_L\right]\f$ then * \f$\left|\vec{a}\right|=\sqrt{\displaystyle\sum_{i=0}^L a_i^2}\f$ * * \returns \f$\left|\vec{a}\right|\f$ */ double vector_mag(double *vector, int L) { double dot = vector_dot(vector, vector, L); return sqrt(dot); } /** * Compute projection of vector \f$\vec{a}\f$ on \f$\vec{b}\f$ defined as * \f[\text{proj}_\vec{b}\vec{a}=\frac{\vec{a}\cdot\vec{b}}{\left|\vec{b}\right|^2}\vec{b}\f] * * \returns NULL if error, otherwise pointer to output */ double *vector_proj(double *a, double *b, double *out, int L) { const double num = vector_dot(a, b, L); const double deno = vector_dot(b, b, L); if (deno == 0) /*! check for division by zero */ return NULL; const double scalar = num / deno; int i; #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (i = 0; i < L; i++) out[i] = scalar * b[i]; return out; } /** * Compute vector subtraction * * \f$\vec{c}=\vec{a}-\vec{b}\f$ * * \returns pointer to output vector */ double *vector_sub(double *a, /**< minuend */ double *b, /**< subtrahend */ double *out, /**< resultant vector */ int L /**< length of vectors */ ) { int i; #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (i = 0; i < L; i++) out[i] = a[i] - b[i]; return out; } /** * Decompose matrix \f$A\f$ using [Gram-Schmidt *process](https://en.wikipedia.org/wiki/QR_decomposition). * * \f{eqnarray*}{ * \text{given that}\quad A &=& *\left[\mathbf{a}_1,\mathbf{a}_2,\ldots,\mathbf{a}_{N-1},\right]\\ * \text{where}\quad\mathbf{a}_i &=& *\left[a_{0i},a_{1i},a_{2i},\ldots,a_{(M-1)i}\right]^T\quad\ldots\mbox{(column *vectors)}\\ * \text{then}\quad\mathbf{u}_i &=& \mathbf{a}_i *-\sum_{j=0}^{i-1}\text{proj}_{\mathbf{u}_j}\mathbf{a}_i\\ * \mathbf{e}_i &=&\frac{\mathbf{u}_i}{\left|\mathbf{u}_i\right|}\\ * Q &=& \begin{bmatrix}\mathbf{e}_0 & \mathbf{e}_1 & \mathbf{e}_2 & \dots & *\mathbf{e}_{N-1}\end{bmatrix}\\ * R &=& \begin{bmatrix}\langle\mathbf{e}_0\,,\mathbf{a}_0\rangle & *\langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & *\langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots \\ * 0 & \langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & *\langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots\\ * 0 & 0 & \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots\\ * \vdots & \vdots & \vdots & \ddots * \end{bmatrix}\\ * \f} */ void qr_decompose(double **A, /**< input matrix to decompose */ double **Q, /**< output decomposed matrix */ double **R, /**< output decomposed matrix */ int M, /**< number of rows of matrix A */ int N /**< number of columns of matrix A */ ) { double *col_vector = (double *)malloc(M * sizeof(double)); double *col_vector2 = (double *)malloc(M * sizeof(double)); double *tmp_vector = (double *)malloc(M * sizeof(double)); for (int i = 0; i < N; i++) /* for each column => R is a square matrix of NxN */ { int j; #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (j = 0; j < i; j++) /* second dimension of column */ R[i][j] = 0.; /* make R upper triangular */ /* get corresponding Q vector */ #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (j = 0; j < M; j++) { tmp_vector[j] = A[j][i]; /* accumulator for uk */ col_vector[j] = A[j][i]; } for (j = 0; j < i; j++) { for (int k = 0; k < M; k++) col_vector2[k] = Q[k][j]; vector_proj(col_vector, col_vector2, col_vector2, M); vector_sub(tmp_vector, col_vector2, tmp_vector, M); } double mag = vector_mag(tmp_vector, M); #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (j = 0; j < M; j++) Q[j][i] = tmp_vector[j] / mag; /* compute upper triangular values of R */ for (int kk = 0; kk < M; kk++) col_vector[kk] = Q[kk][i]; for (int k = i; k < N; k++) { for (int kk = 0; kk < M; kk++) col_vector2[kk] = A[kk][k]; R[i][k] = vector_dot(col_vector, col_vector2, M); } } free(col_vector); free(col_vector2); free(tmp_vector); } #endif // QR_DECOMPOSE_H
GB_unaryop__identity_uint8_int32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_uint8_int32 // op(A') function: GB_tran__identity_uint8_int32 // C type: uint8_t // A type: int32_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint8_t z = (uint8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint8_int32 ( uint8_t *restrict Cx, const int32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_uint8_int32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
schur_eliminator_impl.h
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2010, 2011, 2012 Google Inc. All rights reserved. // http://code.google.com/p/ceres-solver/ // // 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 Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // // Author: sameeragarwal@google.com (Sameer Agarwal) // // TODO(sameeragarwal): row_block_counter can perhaps be replaced by // Chunk::start ? #ifndef CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_ #define CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_ // Eigen has an internal threshold switching between different matrix // multiplication algorithms. In particular for matrices larger than // EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD it uses a cache friendly // matrix matrix product algorithm that has a higher setup cost. For // matrix sizes close to this threshold, especially when the matrices // are thin and long, the default choice may not be optimal. This is // the case for us, as the default choice causes a 30% performance // regression when we moved from Eigen2 to Eigen3. #define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 10 #ifdef CERES_USE_OPENMP #include <omp.h> #endif #include <algorithm> #include <map> #include "ceres/blas.h" #include "ceres/block_random_access_matrix.h" #include "ceres/block_sparse_matrix.h" #include "ceres/block_structure.h" #include "ceres/internal/eigen.h" #include "ceres/internal/fixed_array.h" #include "ceres/internal/scoped_ptr.h" #include "ceres/map_util.h" #include "ceres/schur_eliminator.h" #include "ceres/stl_util.h" #include "Eigen/Dense" #include "glog/logging.h" namespace ceres { namespace internal { template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::~SchurEliminator() { STLDeleteElements(&rhs_locks_); } template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: Init(int num_eliminate_blocks, const CompressedRowBlockStructure* bs) { CHECK_GT(num_eliminate_blocks, 0) << "SchurComplementSolver cannot be initialized with " << "num_eliminate_blocks = 0."; num_eliminate_blocks_ = num_eliminate_blocks; const int num_col_blocks = bs->cols.size(); const int num_row_blocks = bs->rows.size(); buffer_size_ = 1; chunks_.clear(); lhs_row_layout_.clear(); int lhs_num_rows = 0; // Add a map object for each block in the reduced linear system // and build the row/column block structure of the reduced linear // system. lhs_row_layout_.resize(num_col_blocks - num_eliminate_blocks_); for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) { lhs_row_layout_[i - num_eliminate_blocks_] = lhs_num_rows; lhs_num_rows += bs->cols[i].size; } int r = 0; // Iterate over the row blocks of A, and detect the chunks. The // matrix should already have been ordered so that all rows // containing the same y block are vertically contiguous. Along // the way also compute the amount of space each chunk will need // to perform the elimination. while (r < num_row_blocks) { const int chunk_block_id = bs->rows[r].cells.front().block_id; if (chunk_block_id >= num_eliminate_blocks_) { break; } chunks_.push_back(Chunk()); Chunk& chunk = chunks_.back(); chunk.size = 0; chunk.start = r; int buffer_size = 0; const int e_block_size = bs->cols[chunk_block_id].size; // Add to the chunk until the first block in the row is // different than the one in the first row for the chunk. while (r + chunk.size < num_row_blocks) { const CompressedRow& row = bs->rows[r + chunk.size]; if (row.cells.front().block_id != chunk_block_id) { break; } // Iterate over the blocks in the row, ignoring the first // block since it is the one to be eliminated. for (int c = 1; c < row.cells.size(); ++c) { const Cell& cell = row.cells[c]; if (InsertIfNotPresent( &(chunk.buffer_layout), cell.block_id, buffer_size)) { buffer_size += e_block_size * bs->cols[cell.block_id].size; } } buffer_size_ = max(buffer_size, buffer_size_); ++chunk.size; } CHECK_GT(chunk.size, 0); r += chunk.size; } const Chunk& chunk = chunks_.back(); uneliminated_row_begins_ = chunk.start + chunk.size; if (num_threads_ > 1) { random_shuffle(chunks_.begin(), chunks_.end()); } buffer_.reset(new double[buffer_size_ * num_threads_]); // chunk_outer_product_buffer_ only needs to store e_block_size * // f_block_size, which is always less than buffer_size_, so we just // allocate buffer_size_ per thread. chunk_outer_product_buffer_.reset(new double[buffer_size_ * num_threads_]); STLDeleteElements(&rhs_locks_); rhs_locks_.resize(num_col_blocks - num_eliminate_blocks_); for (int i = 0; i < num_col_blocks - num_eliminate_blocks_; ++i) { rhs_locks_[i] = new Mutex; } } template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: Eliminate(const BlockSparseMatrixBase* A, const double* b, const double* D, BlockRandomAccessMatrix* lhs, double* rhs) { if (lhs->num_rows() > 0) { lhs->SetZero(); VectorRef(rhs, lhs->num_rows()).setZero(); } const CompressedRowBlockStructure* bs = A->block_structure(); const int num_col_blocks = bs->cols.size(); // Add the diagonal to the schur complement. if (D != NULL) { #pragma omp parallel for num_threads(num_threads_) schedule(dynamic) for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) { const int block_id = i - num_eliminate_blocks_; int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block_id, block_id, &r, &c, &row_stride, &col_stride); if (cell_info != NULL) { const int block_size = bs->cols[i].size; typename EigenTypes<kFBlockSize>::ConstVectorRef diag(D + bs->cols[i].position, block_size); CeresMutexLock l(&cell_info->m); MatrixRef m(cell_info->values, row_stride, col_stride); m.block(r, c, block_size, block_size).diagonal() += diag.array().square().matrix(); } } } // Eliminate y blocks one chunk at a time. For each chunk,x3 // compute the entries of the normal equations and the gradient // vector block corresponding to the y block and then apply // Gaussian elimination to them. The matrix ete stores the normal // matrix corresponding to the block being eliminated and array // buffer_ contains the non-zero blocks in the row corresponding // to this y block in the normal equations. This computation is // done in ChunkDiagonalBlockAndGradient. UpdateRhs then applies // gaussian elimination to the rhs of the normal equations, // updating the rhs of the reduced linear system by modifying rhs // blocks for all the z blocks that share a row block/residual // term with the y block. EliminateRowOuterProduct does the // corresponding operation for the lhs of the reduced linear // system. #pragma omp parallel for num_threads(num_threads_) schedule(dynamic) for (int i = 0; i < chunks_.size(); ++i) { #ifdef CERES_USE_OPENMP int thread_id = omp_get_thread_num(); #else int thread_id = 0; #endif double* buffer = buffer_.get() + thread_id * buffer_size_; const Chunk& chunk = chunks_[i]; const int e_block_id = bs->rows[chunk.start].cells.front().block_id; const int e_block_size = bs->cols[e_block_id].size; VectorRef(buffer, buffer_size_).setZero(); typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix ete(e_block_size, e_block_size); if (D != NULL) { const typename EigenTypes<kEBlockSize>::ConstVectorRef diag(D + bs->cols[e_block_id].position, e_block_size); ete = diag.array().square().matrix().asDiagonal(); } else { ete.setZero(); } FixedArray<double, 8> g(e_block_size); typename EigenTypes<kEBlockSize>::VectorRef gref(g.get(), e_block_size); gref.setZero(); // We are going to be computing // // S += F'F - F'E(E'E)^{-1}E'F // // for each Chunk. The computation is broken down into a number of // function calls as below. // Compute the outer product of the e_blocks with themselves (ete // = E'E). Compute the product of the e_blocks with the // corresonding f_blocks (buffer = E'F), the gradient of the terms // in this chunk (g) and add the outer product of the f_blocks to // Schur complement (S += F'F). ChunkDiagonalBlockAndGradient( chunk, A, b, chunk.start, &ete, g.get(), buffer, lhs); // Normally one wouldn't compute the inverse explicitly, but // e_block_size will typically be a small number like 3, in // which case its much faster to compute the inverse once and // use it to multiply other matrices/vectors instead of doing a // Solve call over and over again. typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix inverse_ete = ete .template selfadjointView<Eigen::Upper>() .llt() .solve(Matrix::Identity(e_block_size, e_block_size)); // For the current chunk compute and update the rhs of the reduced // linear system. // // rhs = F'b - F'E(E'E)^(-1) E'b FixedArray<double, 8> inverse_ete_g(e_block_size); MatrixVectorMultiply<kEBlockSize, kEBlockSize, 0>( inverse_ete.data(), e_block_size, e_block_size, g.get(), inverse_ete_g.get()); UpdateRhs(chunk, A, b, chunk.start, inverse_ete_g.get(), rhs); // S -= F'E(E'E)^{-1}E'F ChunkOuterProduct(bs, inverse_ete, buffer, chunk.buffer_layout, lhs); } // For rows with no e_blocks, the schur complement update reduces to // S += F'F. NoEBlockRowsUpdate(A, b, uneliminated_row_begins_, lhs, rhs); } template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: BackSubstitute(const BlockSparseMatrixBase* A, const double* b, const double* D, const double* z, double* y) { const CompressedRowBlockStructure* bs = A->block_structure(); #pragma omp parallel for num_threads(num_threads_) schedule(dynamic) for (int i = 0; i < chunks_.size(); ++i) { const Chunk& chunk = chunks_[i]; const int e_block_id = bs->rows[chunk.start].cells.front().block_id; const int e_block_size = bs->cols[e_block_id].size; double* y_ptr = y + bs->cols[e_block_id].position; typename EigenTypes<kEBlockSize>::VectorRef y_block(y_ptr, e_block_size); typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix ete(e_block_size, e_block_size); if (D != NULL) { const typename EigenTypes<kEBlockSize>::ConstVectorRef diag(D + bs->cols[e_block_id].position, e_block_size); ete = diag.array().square().matrix().asDiagonal(); } else { ete.setZero(); } for (int j = 0; j < chunk.size; ++j) { const CompressedRow& row = bs->rows[chunk.start + j]; const double* row_values = A->RowBlockValues(chunk.start + j); const Cell& e_cell = row.cells.front(); DCHECK_EQ(e_block_id, e_cell.block_id); FixedArray<double, 8> sj(row.block.size); typename EigenTypes<kRowBlockSize>::VectorRef(sj.get(), row.block.size) = typename EigenTypes<kRowBlockSize>::ConstVectorRef (b + bs->rows[chunk.start + j].block.position, row.block.size); for (int c = 1; c < row.cells.size(); ++c) { const int f_block_id = row.cells[c].block_id; const int f_block_size = bs->cols[f_block_id].size; const int r_block = f_block_id - num_eliminate_blocks_; MatrixVectorMultiply<kRowBlockSize, kFBlockSize, -1>( row_values + row.cells[c].position, row.block.size, f_block_size, z + lhs_row_layout_[r_block], sj.get()); } MatrixTransposeVectorMultiply<kRowBlockSize, kEBlockSize, 1>( row_values + e_cell.position, row.block.size, e_block_size, sj.get(), y_ptr); MatrixTransposeMatrixMultiply <kRowBlockSize, kEBlockSize, kRowBlockSize, kEBlockSize, 1>( row_values + e_cell.position, row.block.size, e_block_size, row_values + e_cell.position, row.block.size, e_block_size, ete.data(), 0, 0, e_block_size, e_block_size); } ete.llt().solveInPlace(y_block); } } // Update the rhs of the reduced linear system. Compute // // F'b - F'E(E'E)^(-1) E'b template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: UpdateRhs(const Chunk& chunk, const BlockSparseMatrixBase* A, const double* b, int row_block_counter, const double* inverse_ete_g, double* rhs) { const CompressedRowBlockStructure* bs = A->block_structure(); const int e_block_id = bs->rows[chunk.start].cells.front().block_id; const int e_block_size = bs->cols[e_block_id].size; int b_pos = bs->rows[row_block_counter].block.position; for (int j = 0; j < chunk.size; ++j) { const CompressedRow& row = bs->rows[row_block_counter + j]; const double *row_values = A->RowBlockValues(row_block_counter + j); const Cell& e_cell = row.cells.front(); typename EigenTypes<kRowBlockSize>::Vector sj = typename EigenTypes<kRowBlockSize>::ConstVectorRef (b + b_pos, row.block.size); MatrixVectorMultiply<kRowBlockSize, kEBlockSize, -1>( row_values + e_cell.position, row.block.size, e_block_size, inverse_ete_g, sj.data()); for (int c = 1; c < row.cells.size(); ++c) { const int block_id = row.cells[c].block_id; const int block_size = bs->cols[block_id].size; const int block = block_id - num_eliminate_blocks_; CeresMutexLock l(rhs_locks_[block]); MatrixTransposeVectorMultiply<kRowBlockSize, kFBlockSize, 1>( row_values + row.cells[c].position, row.block.size, block_size, sj.data(), rhs + lhs_row_layout_[block]); } b_pos += row.block.size; } } // Given a Chunk - set of rows with the same e_block, e.g. in the // following Chunk with two rows. // // E F // [ y11 0 0 0 | z11 0 0 0 z51] // [ y12 0 0 0 | z12 z22 0 0 0] // // this function computes twp matrices. The diagonal block matrix // // ete = y11 * y11' + y12 * y12' // // and the off diagonal blocks in the Guass Newton Hessian. // // buffer = [y11'(z11 + z12), y12' * z22, y11' * z51] // // which are zero compressed versions of the block sparse matrices E'E // and E'F. // // and the gradient of the e_block, E'b. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: ChunkDiagonalBlockAndGradient( const Chunk& chunk, const BlockSparseMatrixBase* A, const double* b, int row_block_counter, typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix* ete, double* g, double* buffer, BlockRandomAccessMatrix* lhs) { const CompressedRowBlockStructure* bs = A->block_structure(); int b_pos = bs->rows[row_block_counter].block.position; const int e_block_size = ete->rows(); // Iterate over the rows in this chunk, for each row, compute the // contribution of its F blocks to the Schur complement, the // contribution of its E block to the matrix EE' (ete), and the // corresponding block in the gradient vector. for (int j = 0; j < chunk.size; ++j) { const CompressedRow& row = bs->rows[row_block_counter + j]; const double *row_values = A->RowBlockValues(row_block_counter + j); if (row.cells.size() > 1) { EBlockRowOuterProduct(A, row_block_counter + j, lhs); } // Extract the e_block, ETE += E_i' E_i const Cell& e_cell = row.cells.front(); MatrixTransposeMatrixMultiply <kRowBlockSize, kEBlockSize, kRowBlockSize, kEBlockSize, 1>( row_values + e_cell.position, row.block.size, e_block_size, row_values + e_cell.position, row.block.size, e_block_size, ete->data(), 0, 0, e_block_size, e_block_size); // g += E_i' b_i MatrixTransposeVectorMultiply<kRowBlockSize, kEBlockSize, 1>( row_values + e_cell.position, row.block.size, e_block_size, b + b_pos, g); // buffer = E'F. This computation is done by iterating over the // f_blocks for each row in the chunk. for (int c = 1; c < row.cells.size(); ++c) { const int f_block_id = row.cells[c].block_id; const int f_block_size = bs->cols[f_block_id].size; double* buffer_ptr = buffer + FindOrDie(chunk.buffer_layout, f_block_id); MatrixTransposeMatrixMultiply <kRowBlockSize, kEBlockSize, kRowBlockSize, kFBlockSize, 1>( row_values + e_cell.position, row.block.size, e_block_size, row_values + row.cells[c].position, row.block.size, f_block_size, buffer_ptr, 0, 0, e_block_size, f_block_size); } b_pos += row.block.size; } } // Compute the outer product F'E(E'E)^{-1}E'F and subtract it from the // Schur complement matrix, i.e // // S -= F'E(E'E)^{-1}E'F. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: ChunkOuterProduct(const CompressedRowBlockStructure* bs, const Matrix& inverse_ete, const double* buffer, const BufferLayoutType& buffer_layout, BlockRandomAccessMatrix* lhs) { // This is the most computationally expensive part of this // code. Profiling experiments reveal that the bottleneck is not the // computation of the right-hand matrix product, but memory // references to the left hand side. const int e_block_size = inverse_ete.rows(); BufferLayoutType::const_iterator it1 = buffer_layout.begin(); #ifdef CERES_USE_OPENMP int thread_id = omp_get_thread_num(); #else int thread_id = 0; #endif double* b1_transpose_inverse_ete = chunk_outer_product_buffer_.get() + thread_id * buffer_size_; // S(i,j) -= bi' * ete^{-1} b_j for (; it1 != buffer_layout.end(); ++it1) { const int block1 = it1->first - num_eliminate_blocks_; const int block1_size = bs->cols[it1->first].size; MatrixTransposeMatrixMultiply <kEBlockSize, kFBlockSize, kEBlockSize, kEBlockSize, 0>( buffer + it1->second, e_block_size, block1_size, inverse_ete.data(), e_block_size, e_block_size, b1_transpose_inverse_ete, 0, 0, block1_size, e_block_size); BufferLayoutType::const_iterator it2 = it1; for (; it2 != buffer_layout.end(); ++it2) { const int block2 = it2->first - num_eliminate_blocks_; int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block2, &r, &c, &row_stride, &col_stride); if (cell_info != NULL) { const int block2_size = bs->cols[it2->first].size; CeresMutexLock l(&cell_info->m); MatrixMatrixMultiply <kFBlockSize, kEBlockSize, kEBlockSize, kFBlockSize, -1>( b1_transpose_inverse_ete, block1_size, e_block_size, buffer + it2->second, e_block_size, block2_size, cell_info->values, r, c, row_stride, col_stride); } } } } // For rows with no e_blocks, the schur complement update reduces to S // += F'F. This function iterates over the rows of A with no e_block, // and calls NoEBlockRowOuterProduct on each row. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: NoEBlockRowsUpdate(const BlockSparseMatrixBase* A, const double* b, int row_block_counter, BlockRandomAccessMatrix* lhs, double* rhs) { const CompressedRowBlockStructure* bs = A->block_structure(); for (; row_block_counter < bs->rows.size(); ++row_block_counter) { const CompressedRow& row = bs->rows[row_block_counter]; const double *row_values = A->RowBlockValues(row_block_counter); for (int c = 0; c < row.cells.size(); ++c) { const int block_id = row.cells[c].block_id; const int block_size = bs->cols[block_id].size; const int block = block_id - num_eliminate_blocks_; MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>( row_values + row.cells[c].position, row.block.size, block_size, b + row.block.position, rhs + lhs_row_layout_[block]); } NoEBlockRowOuterProduct(A, row_block_counter, lhs); } } // A row r of A, which has no e_blocks gets added to the Schur // Complement as S += r r'. This function is responsible for computing // the contribution of a single row r to the Schur complement. It is // very similar in structure to EBlockRowOuterProduct except for // one difference. It does not use any of the template // parameters. This is because the algorithm used for detecting the // static structure of the matrix A only pays attention to rows with // e_blocks. This is becase rows without e_blocks are rare and // typically arise from regularization terms in the original // optimization problem, and have a very different structure than the // rows with e_blocks. Including them in the static structure // detection will lead to most template parameters being set to // dynamic. Since the number of rows without e_blocks is small, the // lack of templating is not an issue. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: NoEBlockRowOuterProduct(const BlockSparseMatrixBase* A, int row_block_index, BlockRandomAccessMatrix* lhs) { const CompressedRowBlockStructure* bs = A->block_structure(); const CompressedRow& row = bs->rows[row_block_index]; const double *row_values = A->RowBlockValues(row_block_index); for (int i = 0; i < row.cells.size(); ++i) { const int block1 = row.cells[i].block_id - num_eliminate_blocks_; DCHECK_GE(block1, 0); const int block1_size = bs->cols[row.cells[i].block_id].size; int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block1, &r, &c, &row_stride, &col_stride); if (cell_info != NULL) { CeresMutexLock l(&cell_info->m); // This multiply currently ignores the fact that this is a // symmetric outer product. MatrixTransposeMatrixMultiply <Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, 1>( row_values + row.cells[i].position, row.block.size, block1_size, row_values + row.cells[i].position, row.block.size, block1_size, cell_info->values, r, c, row_stride, col_stride); } for (int j = i + 1; j < row.cells.size(); ++j) { const int block2 = row.cells[j].block_id - num_eliminate_blocks_; DCHECK_GE(block2, 0); DCHECK_LT(block1, block2); int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block2, &r, &c, &row_stride, &col_stride); if (cell_info != NULL) { const int block2_size = bs->cols[row.cells[j].block_id].size; CeresMutexLock l(&cell_info->m); MatrixTransposeMatrixMultiply <Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, 1>( row_values + row.cells[i].position, row.block.size, block1_size, row_values + row.cells[j].position, row.block.size, block2_size, cell_info->values, r, c, row_stride, col_stride); } } } } // For a row with an e_block, compute the contribition S += F'F. This // function has the same structure as NoEBlockRowOuterProduct, except // that this function uses the template parameters. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: EBlockRowOuterProduct(const BlockSparseMatrixBase* A, int row_block_index, BlockRandomAccessMatrix* lhs) { const CompressedRowBlockStructure* bs = A->block_structure(); const CompressedRow& row = bs->rows[row_block_index]; const double *row_values = A->RowBlockValues(row_block_index); for (int i = 1; i < row.cells.size(); ++i) { const int block1 = row.cells[i].block_id - num_eliminate_blocks_; DCHECK_GE(block1, 0); const int block1_size = bs->cols[row.cells[i].block_id].size; int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block1, &r, &c, &row_stride, &col_stride); if (cell_info != NULL) { CeresMutexLock l(&cell_info->m); // block += b1.transpose() * b1; MatrixTransposeMatrixMultiply <kRowBlockSize, kFBlockSize, kRowBlockSize, kFBlockSize, 1>( row_values + row.cells[i].position, row.block.size, block1_size, row_values + row.cells[i].position, row.block.size, block1_size, cell_info->values, r, c, row_stride, col_stride); } for (int j = i + 1; j < row.cells.size(); ++j) { const int block2 = row.cells[j].block_id - num_eliminate_blocks_; DCHECK_GE(block2, 0); DCHECK_LT(block1, block2); const int block2_size = bs->cols[row.cells[j].block_id].size; int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block2, &r, &c, &row_stride, &col_stride); if (cell_info != NULL) { // block += b1.transpose() * b2; CeresMutexLock l(&cell_info->m); MatrixTransposeMatrixMultiply <kRowBlockSize, kFBlockSize, kRowBlockSize, kFBlockSize, 1>( row_values + row.cells[i].position, row.block.size, block1_size, row_values + row.cells[j].position, row.block.size, block2_size, cell_info->values, r, c, row_stride, col_stride); } } } } } // namespace internal } // namespace ceres #endif // CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
z_solve.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB SP code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// #include "header.h" //--------------------------------------------------------------------- // this function performs the solution of the approximate factorization // step in the z-direction for all five matrix components // simultaneously. The Thomas algorithm is employed to solve the // systems for the z-lines. Boundary conditions are non-periodic //--------------------------------------------------------------------- void z_solve() { int i, j, k, k1, k2, m; double ru1, fac1, fac2; //kai // int k15; // consistent_data(&k15, "int", 1); //--------------------------------------------------------------------- // Prepare for z-solve, array redistribution //--------------------------------------------------------------------- if (timeron) timer_start(t_zsolve); #pragma omp parallel for default(shared) private(i,j,k,k1,k2,m, \ ru1,fac1,fac2) for (j = 1; j <= ny2; j++) { lhsinitj(nz2+1, nx2); //--------------------------------------------------------------------- // Computes the left hand side for the three z-factors //--------------------------------------------------------------------- //--------------------------------------------------------------------- // first fill the lhs for the u-eigenvalue //--------------------------------------------------------------------- for (i = 1; i <= nx2; i++) { for (k = 0; k <= nz2+1; k++) { ru1 = c3c4*rho_i[k][j][i]; cv[k] = ws[k][j][i]; rhos[k] = max(max(dz4+con43*ru1, dz5+c1c5*ru1), max(dzmax+ru1, dz1)); } for (k = 1; k <= nz2; k++) { lhs[k][i][0] = 0.0; lhs[k][i][1] = -dttz2 * cv[k-1] - dttz1 * rhos[k-1]; lhs[k][i][2] = 1.0 + c2dttz1 * rhos[k]; lhs[k][i][3] = dttz2 * cv[k+1] - dttz1 * rhos[k+1]; lhs[k][i][4] = 0.0; } } //--------------------------------------------------------------------- // add fourth order dissipation //--------------------------------------------------------------------- for (i = 1; i <= nx2; i++) { k = 1; lhs[k][i][2] = lhs[k][i][2] + comz5; lhs[k][i][3] = lhs[k][i][3] - comz4; lhs[k][i][4] = lhs[k][i][4] + comz1; k = 2; lhs[k][i][1] = lhs[k][i][1] - comz4; lhs[k][i][2] = lhs[k][i][2] + comz6; lhs[k][i][3] = lhs[k][i][3] - comz4; lhs[k][i][4] = lhs[k][i][4] + comz1; } for (k = 3; k <= nz2-2; k++) { for (i = 1; i <= nx2; i++) { lhs[k][i][0] = lhs[k][i][0] + comz1; lhs[k][i][1] = lhs[k][i][1] - comz4; lhs[k][i][2] = lhs[k][i][2] + comz6; lhs[k][i][3] = lhs[k][i][3] - comz4; lhs[k][i][4] = lhs[k][i][4] + comz1; } } for (i = 1; i <= nx2; i++) { k = nz2-1; lhs[k][i][0] = lhs[k][i][0] + comz1; lhs[k][i][1] = lhs[k][i][1] - comz4; lhs[k][i][2] = lhs[k][i][2] + comz6; lhs[k][i][3] = lhs[k][i][3] - comz4; k = nz2; lhs[k][i][0] = lhs[k][i][0] + comz1; lhs[k][i][1] = lhs[k][i][1] - comz4; lhs[k][i][2] = lhs[k][i][2] + comz5; } //--------------------------------------------------------------------- // subsequently, fill the other factors (u+c), (u-c) //--------------------------------------------------------------------- for (k = 1; k <= nz2; k++) { for (i = 1; i <= nx2; i++) { lhsp[k][i][0] = lhs[k][i][0]; lhsp[k][i][1] = lhs[k][i][1] - dttz2 * speed[k-1][j][i]; lhsp[k][i][2] = lhs[k][i][2]; lhsp[k][i][3] = lhs[k][i][3] + dttz2 * speed[k+1][j][i]; lhsp[k][i][4] = lhs[k][i][4]; lhsm[k][i][0] = lhs[k][i][0]; lhsm[k][i][1] = lhs[k][i][1] + dttz2 * speed[k-1][j][i]; lhsm[k][i][2] = lhs[k][i][2]; lhsm[k][i][3] = lhs[k][i][3] - dttz2 * speed[k+1][j][i]; lhsm[k][i][4] = lhs[k][i][4]; } } //--------------------------------------------------------------------- // FORWARD ELIMINATION //--------------------------------------------------------------------- for (k = 0; k <= grid_points[2]-3; k++) { k1 = k + 1; k2 = k + 2; for (i = 1; i <= nx2; i++) { fac1 = 1.0/lhs[k][i][2]; lhs[k][i][3] = fac1*lhs[k][i][3]; lhs[k][i][4] = fac1*lhs[k][i][4]; for (m = 0; m < 3; m++) { rhs[k][j][i][m] = fac1*rhs[k][j][i][m]; } lhs[k1][i][2] = lhs[k1][i][2] - lhs[k1][i][1]*lhs[k][i][3]; lhs[k1][i][3] = lhs[k1][i][3] - lhs[k1][i][1]*lhs[k][i][4]; for (m = 0; m < 3; m++) { rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhs[k1][i][1]*rhs[k][j][i][m]; } lhs[k2][i][1] = lhs[k2][i][1] - lhs[k2][i][0]*lhs[k][i][3]; lhs[k2][i][2] = lhs[k2][i][2] - lhs[k2][i][0]*lhs[k][i][4]; for (m = 0; m < 3; m++) { rhs[k2][j][i][m] = rhs[k2][j][i][m] - lhs[k2][i][0]*rhs[k][j][i][m]; } } } //--------------------------------------------------------------------- // The last two rows in this grid block are a bit different, // since they for (not have two more rows available for the // elimination of off-diagonal entries //--------------------------------------------------------------------- k = grid_points[2]-2; k1 = grid_points[2]-1; for (i = 1; i <= nx2; i++) { fac1 = 1.0/lhs[k][i][2]; lhs[k][i][3] = fac1*lhs[k][i][3]; lhs[k][i][4] = fac1*lhs[k][i][4]; for (m = 0; m < 3; m++) { rhs[k][j][i][m] = fac1*rhs[k][j][i][m]; } lhs[k1][i][2] = lhs[k1][i][2] - lhs[k1][i][1]*lhs[k][i][3]; lhs[k1][i][3] = lhs[k1][i][3] - lhs[k1][i][1]*lhs[k][i][4]; for (m = 0; m < 3; m++) { rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhs[k1][i][1]*rhs[k][j][i][m]; } //--------------------------------------------------------------------- // scale the last row immediately //--------------------------------------------------------------------- fac2 = 1.0/lhs[k1][i][2]; for (m = 0; m < 3; m++) { rhs[k1][j][i][m] = fac2*rhs[k1][j][i][m]; } } //--------------------------------------------------------------------- // for (the u+c and the u-c factors //--------------------------------------------------------------------- for (k = 0; k <= grid_points[2]-3; k++) { k1 = k + 1; k2 = k + 2; for (i = 1; i <= nx2; i++) { m = 3; fac1 = 1.0/lhsp[k][i][2]; lhsp[k][i][3] = fac1*lhsp[k][i][3]; lhsp[k][i][4] = fac1*lhsp[k][i][4]; rhs[k][j][i][m] = fac1*rhs[k][j][i][m]; lhsp[k1][i][2] = lhsp[k1][i][2] - lhsp[k1][i][1]*lhsp[k][i][3]; lhsp[k1][i][3] = lhsp[k1][i][3] - lhsp[k1][i][1]*lhsp[k][i][4]; rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhsp[k1][i][1]*rhs[k][j][i][m]; lhsp[k2][i][1] = lhsp[k2][i][1] - lhsp[k2][i][0]*lhsp[k][i][3]; lhsp[k2][i][2] = lhsp[k2][i][2] - lhsp[k2][i][0]*lhsp[k][i][4]; rhs[k2][j][i][m] = rhs[k2][j][i][m] - lhsp[k2][i][0]*rhs[k][j][i][m]; m = 4; fac1 = 1.0/lhsm[k][i][2]; lhsm[k][i][3] = fac1*lhsm[k][i][3]; lhsm[k][i][4] = fac1*lhsm[k][i][4]; rhs[k][j][i][m] = fac1*rhs[k][j][i][m]; lhsm[k1][i][2] = lhsm[k1][i][2] - lhsm[k1][i][1]*lhsm[k][i][3]; lhsm[k1][i][3] = lhsm[k1][i][3] - lhsm[k1][i][1]*lhsm[k][i][4]; rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhsm[k1][i][1]*rhs[k][j][i][m]; lhsm[k2][i][1] = lhsm[k2][i][1] - lhsm[k2][i][0]*lhsm[k][i][3]; lhsm[k2][i][2] = lhsm[k2][i][2] - lhsm[k2][i][0]*lhsm[k][i][4]; rhs[k2][j][i][m] = rhs[k2][j][i][m] - lhsm[k2][i][0]*rhs[k][j][i][m]; } } //--------------------------------------------------------------------- // And again the last two rows separately //--------------------------------------------------------------------- k = grid_points[2]-2; k1 = grid_points[2]-1; for (i = 1; i <= nx2; i++) { m = 3; fac1 = 1.0/lhsp[k][i][2]; lhsp[k][i][3] = fac1*lhsp[k][i][3]; lhsp[k][i][4] = fac1*lhsp[k][i][4]; rhs[k][j][i][m] = fac1*rhs[k][j][i][m]; lhsp[k1][i][2] = lhsp[k1][i][2] - lhsp[k1][i][1]*lhsp[k][i][3]; lhsp[k1][i][3] = lhsp[k1][i][3] - lhsp[k1][i][1]*lhsp[k][i][4]; rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhsp[k1][i][1]*rhs[k][j][i][m]; m = 4; fac1 = 1.0/lhsm[k][i][2]; lhsm[k][i][3] = fac1*lhsm[k][i][3]; lhsm[k][i][4] = fac1*lhsm[k][i][4]; rhs[k][j][i][m] = fac1*rhs[k][j][i][m]; lhsm[k1][i][2] = lhsm[k1][i][2] - lhsm[k1][i][1]*lhsm[k][i][3]; lhsm[k1][i][3] = lhsm[k1][i][3] - lhsm[k1][i][1]*lhsm[k][i][4]; rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhsm[k1][i][1]*rhs[k][j][i][m]; //--------------------------------------------------------------------- // Scale the last row immediately (some of this is overkill // if this is the last cell) //--------------------------------------------------------------------- rhs[k1][j][i][3] = rhs[k1][j][i][3]/lhsp[k1][i][2]; rhs[k1][j][i][4] = rhs[k1][j][i][4]/lhsm[k1][i][2]; } //--------------------------------------------------------------------- // BACKSUBSTITUTION //--------------------------------------------------------------------- k = grid_points[2]-2; k1 = grid_points[2]-1; for (i = 1; i <= nx2; i++) { for (m = 0; m < 3; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[k][i][3]*rhs[k1][j][i][m]; } rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[k][i][3]*rhs[k1][j][i][3]; rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[k][i][3]*rhs[k1][j][i][4]; } //--------------------------------------------------------------------- // Whether or not this is the last processor, we always have // to complete the back-substitution //--------------------------------------------------------------------- //--------------------------------------------------------------------- // The first three factors //--------------------------------------------------------------------- for (k = grid_points[2]-3; k >= 0; k--) { k1 = k + 1; k2 = k + 2; for (i = 1; i <= nx2; i++) { for (m = 0; m < 3; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[k][i][3]*rhs[k1][j][i][m] - lhs[k][i][4]*rhs[k2][j][i][m]; } //------------------------------------------------------------------- // And the remaining two //------------------------------------------------------------------- rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[k][i][3]*rhs[k1][j][i][3] - lhsp[k][i][4]*rhs[k2][j][i][3]; rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[k][i][3]*rhs[k1][j][i][4] - lhsm[k][i][4]*rhs[k2][j][i][4]; } } //kai k15 = j; } if (timeron) timer_stop(t_zsolve); tzetar(); }
barrier.c
/* Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Simone Atzeni (simone@cs.utah.edu), Joachim Protze (joachim.protze@tu-dresden.de), Jonas Hahnfeld (hahnfeld@itc.rwth-aachen.de), Ganesh Gopalakrishnan, Zvonimir Rakamaric, Dong H. Ahn, Gregory L. Lee, Ignacio Laguna, and Martin Schulz. LLNL-CODE-773957 All rights reserved. This file is part of Archer. For details, see https://pruners.github.io/archer. Please also read https://github.com/PRUNERS/archer/blob/master/LICENSE. 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. */ // RUN: %libarcher-compile-and-run | FileCheck %s #include <omp.h> #include <stdio.h> int main(int argc, char* argv[]) { int var = 0; #pragma omp parallel num_threads(2) shared(var) { if (omp_get_thread_num() == 0) { var++; } #pragma omp barrier if (omp_get_thread_num() == 1) { var++; } } fprintf(stderr, "DONE\n"); int error = (var != 2); return error; } // CHECK: DONE
optimisation_topo.c
/************************************************************************* * MediPy - Copyright (C) Universite de Strasbourg, 2011 * Distributed under the terms of the CeCILL-B license, as published by * the CEA-CNRS-INRIA. Refer to the LICENSE file or to * http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html * for details. ************************************************************************/ #include <config.h> #include "math/imx_matrix.h" #include "noyau/io/imx_log.h" #include "recalage/chps_3d.h" #include "recalage/topo/mtch_topo_3d.h" #include "recalage/topo/optimisation_topo.h" #include "recalage/topo/distance_topo.h" #include "recalage/topo/gradient_distance_topo.h" #include "recalage/topo/hessien_distance_topo.h" /******************************************************************************* ******************************************************************************** *************************** MINIMISATIONS ************************************** ******************************************************************************** *******************************************************************************/ /******************************************************************************* ** TOP_linemin_locale_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param,direc) ** ** minimisation unidimensionnelle suivant la direction direc ** par decoupage de l'intervalle de recherche ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** direc: vecteur donnant la direction de minimisation ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retournes dans param *******************************************************************************/ double TOP_linemin_locale_3d (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin, transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist, reg_func_locale_t regularisation, int nb_param, double *param, double *param_norm,double *moins_direc, int topi, int topj, int topk, double Jm, double JM,TSlpqr *Slpqr) { double cf,cfmax,cfopt,Emin,E,*p,*p_norm; double max_grad_cfmax; int i,j,l,nb_pas,topD,continuer; int width,height,depth,resol; int niter; double x0,x1,x2,x3=0,f1,f2,aux,dGOLD=0.61803; double precis; int i_min; //---Variables dediees au recalage symetrique ------- double opp_cfmax,*opp_param_norm,*opp_moins_direc; double lambda_ref = (1.0-TOPO_PONDERATION_RECALAGE_SYMETRIQUE)/TOPO_PONDERATION_RECALAGE_SYMETRIQUE; width=BASE3D.width;height=BASE3D.height;depth=BASE3D.depth; resol=BASE3D.resol; p=CALLOC(nb_param,double); p_norm=CALLOC(nb_param,double); topD=(int)pow(2.0,1.0*BASE3D.resol)-1; l = TOP_conv_ind(topi,topj,topk,nb_param); //--------------------------------------------------------------- //----- determination de cfmin et cfmax ------------------------- //--------------------------------------------------------------- moins_direc[l] = 1.0*moins_direc[l] / width; moins_direc[l+1] = 1.0*moins_direc[l+1] / height; moins_direc[l+2] = 1.0*moins_direc[l+2] / depth; cfmax = TOP_linemin_maxpas_3d(nb_param,param_norm,moins_direc,topi,topj,topk,Jm,JM,Slpqr); // ------------------------------------------------------------ //----- Dans le cas du recalage symetrique, on calcul aussi --- //----- le pas max pour la transfo symetrique et on prend le -- //----- le min des 2 ------------------------------------------ //------------------------------------------------------------- if((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) || ((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) { opp_param_norm=CALLOC(nb_param,double); opp_moins_direc=CALLOC(nb_param,double); for(i=0;i<nb_param;i++) { opp_param_norm[i]=-1.0*lambda_ref*param_norm[i]; opp_moins_direc[i]=-1.0*moins_direc[i]; } opp_cfmax = TOP_linemin_maxpas_3d(nb_param,opp_param_norm,opp_moins_direc,topi,topj,topk,Jm,JM,Slpqr); if (lambda_ref>0) opp_cfmax=opp_cfmax/lambda_ref; else opp_cfmax=HUGE_VAL; cfmax=MINI(cfmax,opp_cfmax); } //----- Recherche du deplacement relatif max ---- max_grad_cfmax=0; if (fabs(moins_direc[l])>max_grad_cfmax) max_grad_cfmax=fabs(moins_direc[l]); if (fabs(moins_direc[l+1])>max_grad_cfmax) max_grad_cfmax=fabs(moins_direc[l+1]); if (fabs(moins_direc[l+2])>max_grad_cfmax) max_grad_cfmax=fabs(moins_direc[l+2]); moins_direc[l] = 1.0*moins_direc[l] * width; moins_direc[l+1] = 1.0*moins_direc[l+1] * height; moins_direc[l+2] = 1.0*moins_direc[l+2] * depth; nb_pas = NB_PAS_LINEMIN_TOPO; cfopt=0.0; if ((max_grad_cfmax*cfmax)>(nb_pas*TOPO_QUANTIFICATION_PARAM)) // on ne fait une recherche lineaire que si les parametres sont susceptibles de bouger de plus de TOPO_QUANTIFICATION_PARAM { if (max_grad_cfmax*cfmax<(1./topD)) { //--------------------------------------------------------------- //---------- Recherche lineaire --------------------------------- //--------------------------------------------------------------- Emin=dist(imref,imreca,nb_param,param,param_norm,topi,topj,topk,Slpqr,regularisation); cfopt=0.0; continuer = 1; for (i=0; i<nb_param; i++) {p[i] = param[i];p_norm[i]=param_norm[i];} i_min=0; for (i=1; (i<=nb_pas)/*&&(continuer==1)*/; i++) { cf=1.0*i*cfmax/(1.0*nb_pas); for (j=l; j<l+3; j++) p[j] = param[j] - cf*moins_direc[j]; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; E=dist(imref, imreca,nb_param,p,p_norm,topi,topj,topk,Slpqr,regularisation); if (E<Emin) { Emin=E; cfopt=cf;i_min=i;} if (E>Emin) {continuer=0;} } i--; for (j=l; j<l+3; j++) p[j] = param[j] - cfopt*moins_direc[j]; for (j=l; j<l+3; j++) if (fabs(p[j])<TOPO_QUANTIFICATION_PARAM) /* C'est pour en finir avec les bug num�riques ... */ p[j]=0.0; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; i=i_min; while ((TOP_verification_locale(nb_param,p,p_norm,Jm,JM,topi,topj,topk,Slpqr)==0)&&(i>0)) { i--; cf=1.0*i*cfmax/(1.0*nb_pas); cfopt = cf; for (j=l; j<l+3; j++) p[j] = param[j] - cf*moins_direc[j]; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; #ifndef TOPO_VERBOSE printf("Avertissements ci-dessus pris en compte....\n\n"); #endif } } else { //--------------------------------------------------------------- //----- Recherche par nombre d'or ------------------------------- //--------------------------------------------------------------- for (j=0; j<nb_param; j++) {p[j] = param[j];p_norm[j]=param_norm[j];} Emin=dist(imref,imreca,nb_param,param,param_norm,topi,topj,topk,Slpqr,regularisation); i_min=0; // Initialisation for (i=1;i<nb_pas;i++) { cf=0.1*i*cfmax; for (j=l; j<l+3; j++) p[j] = param[j] - cf*moins_direc[j]; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; E=dist(imref, imreca,nb_param,p,p_norm,topi,topj,topk,Slpqr,regularisation); if (E<Emin) {Emin = E; i_min = i;} } if (i_min == 0) { x0=0; x3=0.1*cfmax; x1=dGOLD*x3; x2=x1+(1-dGOLD)*(x3-x1); } else { x0=0.1*(i_min-1)*cfmax; x1=0.1*i_min*cfmax; x2=x1+(1-dGOLD)*(x3-x1); x3=0.1*(i_min+1)*cfmax; } for (j=l; j<l+3; j++) p[j] = param[j] - x1*moins_direc[j]; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; f1=dist(imref,imreca,nb_param,p,p_norm,topi,topj,topk,Slpqr,regularisation); for (j=l; j<l+3; j++) p[j] = param[j] - x2*moins_direc[j]; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; f2=dist(imref,imreca,nb_param,p,p_norm,topi,topj,topk,Slpqr,regularisation); niter=0; aux=fabs(1.0*max_grad_cfmax*(x0-x3)); precis= 0.1/topD; while (aux>precis) { if (f2<f1) { aux=dGOLD*x2+(1-dGOLD)*x3; x0=x1;x1=x2;x2=aux; f1=f2; for (j=l; j<l+3; j++) p[j] = param[j] - x2*moins_direc[j]; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; f2=dist(imref,imreca,nb_param,p,p_norm,topi,topj,topk,Slpqr,regularisation); } else { aux=dGOLD*x1+(1-dGOLD)*x0; x3=x2;x2=x1;x1=aux; f2=f1; for (j=l; j<l+3; j++) p[j] = param[j] - x1*moins_direc[j]; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; f1=dist(imref,imreca,nb_param,p,p_norm,topi,topj,topk,Slpqr,regularisation); } niter++; aux=fabs(1.0*max_grad_cfmax*(x0-x3)); } if ((Emin<f1)&&(Emin<f2)){cfopt=0;} else if (f1<f2) { cfopt = x1; Emin = f1;} else {cfopt = x2; Emin = f2;} i=nb_pas; while ((TOP_verification_locale(nb_param,p,p_norm,Jm,JM,topi,topj,topk,Slpqr)==0)&&(i>0)) { i--; cf=1.0*i*cfopt/(1.0*nb_pas); cfopt = cf; for (j=l; j<l+3; j++) p[j] = param[j] - cf*moins_direc[j]; p_norm[l] =1.0*p[l] /width; p_norm[l+1]=1.0*p[l+1]/height; p_norm[l+2]=1.0*p[l+2]/depth; #ifndef TOPO_VERBOSE printf("Avertissements ci-dessus pris en compte....\n"); #endif } } } // ------------------------------------------------------------ //----- On verifie que le pas est aussi acceptable pour la ---- //----- transfo symetrique ------------------------------------ //------------------------------------------------------------- if(((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d))&&(cfopt != 0)) { opp_param_norm[l] = -1.0*lambda_ref*(param[l] + cf*moins_direc[l])/width; opp_param_norm[l+1] = -1.0* lambda_ref*(param[l+1] + cf*moins_direc[l+1])/height; opp_param_norm[l+2] = -1.0* lambda_ref*(param[l+2] + cf*moins_direc[l+2])/depth; i=nb_pas; while ((TOP_verification_locale(nb_param,p,opp_param_norm,Jm,JM,topi,topj,topk,Slpqr)==0)&&(i>0)) { i--; cf=1.0*i*cfopt/(1.0*nb_pas); cfopt = cf; opp_param_norm[l] = -1.0* lambda_ref*(param[l] + cf*moins_direc[l])/width; opp_param_norm[l+1] = -1.0* lambda_ref*(param[l+1] + cf*moins_direc[l+1])/height; opp_param_norm[l+2] = -1.0* lambda_ref*(param[l+2] + cf*moins_direc[l+2])/depth; } } //--------------------------------------------------------------- //----- mise a jour des parametres ------------------------------ //--------------------------------------------------------------- if (cfopt != 0) { for (j=l; j<l+3; j++) param[j] = param[j] - cfopt*moins_direc[j]; } param_norm[l] =1.0*param[l] /width; param_norm[l+1]=1.0*param[l+1]/height; param_norm[l+2]=1.0*param[l+2]/depth; Emin=dist(imref,imreca,nb_param,param,param_norm,topi,topj,topk,Slpqr,regularisation); // ------------------------------------------------------------ //----- Liberation de variables uniquement allouees lors du---- //----- recalage symetrique------------------------------------ //------------------------------------------------------------- if((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d)) { free(opp_param_norm); free(opp_moins_direc); } free(p);free(p_norm); return(Emin); } /******************************************************************************* ** TOP_min_desc_grad_locale_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param) ** ** recalage par descente de gradient ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retourne dans param *******************************************************************************/ double TOP_min_desc_grad_locale_3d (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin,transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist, reg_func_locale_t regularisation, int nb_param, double *param, int ***masque_param,double Jmin, double Jmax,char *nomfichiertrf) { int wdth,hght,dpth,i; field3d *gradIref,*maskgradIref=NULL; double *grad,*p,*p_i,gradl[3],*param_norm; double Edebut,Efin,E1,E2,E,Eprec; int nb,nbreduc,stop; double prreduc,maxpx,maxpy,maxpz,precis,precisx,precisy,precisz; int topi,topj,topk,topD,resol; int pari,parj,park; int compt,topD1; int ***masque_bloc; transf3d *transfo; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11,l; double xm,xM,ym,yM,zm,zM; int (*gradient)(); reg_grad_locale_t gradient_reg; #ifndef SAVE_INTERMEDIAIRE char nomfichier[255]; char temp[2]; char *ext; #endif wdth=imref->width;hght=imref->height;dpth=imref->depth; resol=BASE3D.resol; topD=(int)pow(2.0,1.0*resol)-1; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_Lp_locale_3d) gradient=gradient_base_Lp_locale_3d; if (dist==Energie_Lp_sym_locale_3d) gradient=gradient_base_Lp_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) gradient=gradient_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) gradient=gradient_base_L1L2_sym_locale_3d; if (dist==Energie_L1norm_locale_3d) gradient=gradient_base_L1norm_locale_3d; if (dist==Energie_quad_topo_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) gradient=gradient_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) gradient=gradient_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) gradient=gradient_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) gradient=gradient_base_ICP_sym_locale_3d; if (dist==Energie_atrophie_jacobien_locale_3d) gradient=gradient_atrophie_jacobien_locale_3d; if (dist==Energie_atrophie_log_jacobien_locale_3d) gradient=gradient_atrophie_log_jacobien_locale_3d; if (dist==Energie_atrophie_log_jacobien_locale_3d) gradient=gradient_atrophie_log_jacobien_locale_3d; if (dist==Energie_quad_locale_symetrique_3d) gradient=gradient_quad_locale_symetrique_3d; if (dist==Energie_quad_locale_symetrique_coupe_3d) gradient=gradient_quad_locale_symetrique_coupe_3d; if (dist==Energie_quad_sous_champ_locale_3d) gradient=gradient_quad_sous_champ_locale_3d; if (dist==Energie_groupwise_variance_locale_3d) gradient=gradient_groupwise_variance_locale_3d; if (dist==Energie_groupwise_variance_locale_nonsym_3d) gradient=gradient_groupwise_variance_locale_nonsym_3d; gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) gradient_reg=gradient_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) gradient_reg=gradient_regularisation_log_jacobien_local; if (regularisation==regularisation_energie_membrane_jacobien_local) gradient_reg=gradient_regularisation_energie_membrane_jacobien_local; if (regularisation==regularisation_log_jacobien_centre_local) gradient_reg=gradient_regularisation_log_jacobien_centre_local; if (regularisation==regularisation_dist_identite_local) gradient_reg=gradient_regularisation_dist_identite_local; if (regularisation==regularisation_patch_imagebased_local) gradient_reg=gradient_regularisation_patch_imagebased_local; /*allocation memoire des variables*/ //p=alloc_dvector(nb_param); p_i=alloc_dvector(nb_param); param_norm=alloc_dvector(nb_param); grad=alloc_dvector(nb_param); if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) gradIref=cr_field3d(wdth,hght,dpth); else gradIref=NULL; if (dist==Energie_groupwise_variance_locale_3d) { _ParamRecalageBspline.grad_reca_groupwise=cr_field3d(wdth,hght,dpth); _ParamRecalageBspline.grad_ref_groupwise=cr_field3d(wdth,hght,dpth); _ParamRecalageBspline.grad_ref2_groupwise=cr_field3d(wdth,hght,dpth); } masque_bloc=alloc_imatrix_3d(topD,topD,topD); if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) maskgradIref=cr_field3d(wdth,hght,dpth); transfo=cr_transf3d(wdth,hght,dpth,NULL); transfo->nb_param=nb_param;transfo->param=CALLOC(nb_param,double); transfo->typetrans=BSPLINE3D; transfo->resol=BASE3D.resol;transfo->degre=1; // Valeur codee en dur car ca ne marche que pour les splines de degre 1 p = transfo->param; /*Initialisation de masque_bloc*/ for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) masque_bloc[topi][topj][topk]=1; for (i=0;i<nb_param;i++) p_i[i]=p[i]=param[i]; /* initialisation des parametres normalises sur [0,1] */ for (i=0;i<nb_param/3;i++) { param_norm[3*i] =1.0*p[3*i] /wdth; param_norm[3*i+1]=1.0*p[3*i+1]/hght; param_norm[3*i+2]=1.0*p[3*i+2]/dpth; } //Mise a jour de Jm et JM dans les Slpqr for (i=0;i<8;i++) { Slpqr[i].Jm=Jmin; Slpqr[i].JM=Jmax; } /*calcul de l'energie de depart*/ Edebut=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); E2=Edebut; /* calcul du gradient de l'image a recaler */ if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_ICP_locale_3d)) imx_gradient_3d_p(imreca,gradIref,0,4); else if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) imx_gradient_3d_p(imreca,gradIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_gradient_3d_p(imreca->mask,maskgradIref,0,4); //------------------------------------------------------- //----- Pour le recalage symetrique, on calcule aussi---- //----- le gradient de imref ---------------------------- //------------------------------------------------------- if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_gradient_3d_p(imref,maskgradIref,2,4); if (dist==Energie_groupwise_variance_locale_3d) { imx_gradient_3d_p(_ParamRecalageBspline.reca_groupwise,_ParamRecalageBspline.grad_reca_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_reca_groupwise,_ParamRecalageBspline.grad_reca_groupwise, _ParamRecalageBspline.reca_groupwise->rcoeff); imx_gradient_3d_p(_ParamRecalageBspline.ref_groupwise,_ParamRecalageBspline.grad_ref_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_ref_groupwise, _ParamRecalageBspline.grad_ref_groupwise, _ParamRecalageBspline.ref_groupwise->rcoeff); imx_gradient_3d_p(_ParamRecalageBspline.ref2_groupwise,_ParamRecalageBspline.grad_ref2_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_ref2_groupwise, _ParamRecalageBspline.grad_ref2_groupwise, _ParamRecalageBspline.ref2_groupwise->rcoeff); /*// calcul plus chiade du gradient de ref2 field3d *grad_tmp; grad_tmp=cr_field3d(wdth,hght,dpth); for(i=0; i<wdth; i++) for(j=0; j<hght; j++) for(k=0; k<dpth; k++) { _ParamRecalageBspline.grad_ref2_groupwise->raw[i][j][k].x=0.0; _ParamRecalageBspline.grad_ref2_groupwise->raw[i][j][k].y=0.0; _ParamRecalageBspline.grad_ref2_groupwise->raw[i][j][k].z=0.0; } for (l=0; l< _ParamRecalageBspline.nb_tot_groupwise; l++) if (l!=_ParamRecalageBspline.nb_reca_groupwise) { rcoef2=_ParamRecalageBspline.serie_groupwise[l]->rcoeff*_ParamRecalageBspline.serie_groupwise[l]->rcoeff; imx_gradient_3d_p(_ParamRecalageBspline.serie_groupwise[l],grad_tmp,2,4); for(i=0; i<wdth; i++) for(j=0; j<hght; j++) for(k=0; k<dpth; k++) { tmp=_ParamRecalageBspline.serie_groupwise[l]->mri[i][j][k]*rcoef2; _ParamRecalageBspline.grad_ref2_groupwise->raw[i][j][k].x+=grad_tmp->raw[i][j][k].x*tmp; _ParamRecalageBspline.grad_ref2_groupwise->raw[i][j][k].y+=grad_tmp->raw[i][j][k].y*tmp; _ParamRecalageBspline.grad_ref2_groupwise->raw[i][j][k].z+=grad_tmp->raw[i][j][k].z*tmp; } } tmp=2.0; mul_field_3d(_ParamRecalageBspline.grad_ref2_groupwise, _ParamRecalageBspline.grad_ref2_groupwise, tmp); free_field3d(grad_tmp);*/ } aff_log("Edebut: %.2f nb_param: %d \n",Edebut,nb_param); nb=nbreduc=0;prreduc=0.1/100.0; stop=1; // --- On fixe la pr�cision � 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la pr�cision en recalage sym�trique soit �quivalent que celle obtenue en non symetrique if ((dist==Energie_atrophie_log_jacobien_locale_3d)|| (dist==Energie_atrophie_jacobien_locale_3d)) precis=pow(0.1,PRECISION_SIMULATION)*precis; // on augmente un peu la precision pour la simulation d'atrophie precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. debut resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif E=0; do { Eprec=E; E=0; E1=E2; compt=1; stop=0; for(pari=MINI(2,resol)-1;pari>=0;pari--) for(parj=MINI(2,resol)-1;parj>=0;parj--) for(park=MINI(2,resol)-1;park>=0;park--) { for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) if ((topi%2==pari)&&(topj%2==parj)&&(topk%2==park)) if ((masque_param[topi][topj][topk]!=0)&&(masque_bloc[topi][topj][topk]!=0)) { //--------------------------------------------------------------- //----- initialisation Slpqr ------------------------- //--------------------------------------------------------------- l=TOP_conv_ind(topi,topj,topk,nb_param); xm = 1.0*x00[l/3]/wdth; xM = 1.0*x11[l/3]/wdth; ym = 1.0*y00[l/3]/hght; yM = 1.0*y11[l/3]/hght; zm = 1.0*z00[l/3]/dpth; zM =1.0*z11[l/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; /* Calcul du gradient*/ gradient(imref,imreca,nb_param,p,param_norm,gradIref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); topD1 = l; // printf("%d ieme bloc sur %d \r",topD1/3,nb_param/3); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; if((gradl[0]!=0)||(gradl[1]!=0)||(gradl[2]!=0)) { if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); E2=TOP_linemin_locale_3d(imref,imreca,imres,champ_fin,the_transf,inter,dist,regularisation,nb_param,p,param_norm,grad,topi,topj,topk,Jmin,Jmax,Slpqr); E=E+E2; if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } //-------Evaluation du deplacement max------------ maxpx=1.0*fabs(p_i[topD1]-p[topD1]); maxpy=1.0*fabs(p_i[topD1+1]-p[topD1+1]); maxpz=1.0*fabs(p_i[topD1+2]-p[topD1+2]); if ((maxpx<precisx)&&(maxpy<precisy)&&(maxpz<precisz)) masque_bloc[topi][topj][topk]=0; else {/* on debloque les blocs voisins */ if (maxpx>precisx) { if (topi>0) masque_bloc[topi-1][topj][topk]=1; if (topi<topD-1) masque_bloc[topi+1][topj][topk]=1; } if (maxpy>precisy) { if (topj>0) masque_bloc[topi][topj-1][topk]=1; if (topj<topD-1) masque_bloc[topi][topj+1][topk]=1; } if (maxpz>precisz) { if (topk>0) masque_bloc[topi][topj][topk-1]=1; if (topk<topD-1) masque_bloc[topi][topj][topk+1]=1; } } stop++; } } for (i=0;i<nb_param;i++) p_i[i]=p[i]; printf("Minimisation sur %f %% des blocs Eprec : %f E : %f\n",300.0*stop/nb_param,Eprec,E); if (nomfichiertrf!=NULL) { #ifndef TOPO_COMPARE_CRITERE compare_critere(imref,imreca,imres,champ_fin,p,param_norm,nb_param,masque_param,nb); #endif } nb++; } while (nb<50 && Eprec!=E); /*calcul de l'energie finale*/ Efin=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); aff_log("nbiter: %d Efin: %.2f reduction: %.2f %% \n",nb,Efin,(Edebut-Efin)/Edebut*100.0); for (i=0;i<nb_param;i++) param[i]=p[i]; #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif #ifndef SAVE_INTERMEDIAIRE if (nomfichiertrf!=NULL) { /*si l'extension .trf existe on la supprime*/ strcpy(nomfichier,nomfichiertrf); ext=strstr(nomfichier,".trf"); if (ext!=NULL) *ext='\0'; strcat(nomfichier,"_"); temp[0]=(char)(resol+48); temp[1]=0; strcat(nomfichier,temp); save_transf_3d(transfo,nomfichier); } #endif /*liberation memoire des variables*/ //free_dvector(p,nb_param); free_dvector(p_i,nb_param); free_dvector(param_norm,nb_param); free_dvector(grad,nb_param); if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) free_field3d(gradIref); if (dist==Energie_groupwise_variance_locale_3d) { free_field3d(_ParamRecalageBspline.grad_reca_groupwise); free_field3d(_ParamRecalageBspline.grad_ref_groupwise); free_field3d(_ParamRecalageBspline.grad_ref2_groupwise); } free_transf3d(transfo); if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) free_field3d(maskgradIref); free_imatrix_3d(masque_bloc); return(Efin); } /******************************************************************************* ** TOP_min_icm_locale_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param) ** ** recalage par ICM ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retourne dans param *******************************************************************************/ double TOP_min_icm_locale_3d (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin, transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist, reg_func_locale_t regularisation, int nb_param, double *param, int ***masque_param, double Jmin, double Jmax,char *nomfichiertrf) { int wdth,hght,dpth,i,j; double *grad,*p,*p_i,*param_norm; double Edebut,Efin,E1,E2,E,Eprec; int nb,nbreduc,stop; double prreduc,maxpx,maxpy,maxpz,precis,precisx,precisy,precisz; int topi,topj,topk,topD,resol; int pari,parj,park; int compt,topD1; int ***masque_bloc; transf3d *transfo; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11,l; double xm,xM,ym,yM,zm,zM; #ifndef SAVE_INTERMEDIAIRE char nomfichier[255]; char temp[2]; char *ext; #endif wdth=imref->width;hght=imref->height;dpth=imref->depth; resol=BASE3D.resol; topD=(int)pow(2.0,1.0*resol)-1; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; /*allocation memoire des variables*/ //p=alloc_dvector(nb_param); p_i=alloc_dvector(nb_param); param_norm=alloc_dvector(nb_param); grad=alloc_dvector(nb_param); masque_bloc=alloc_imatrix_3d(topD,topD,topD); transfo=cr_transf3d(wdth,hght,dpth,NULL); transfo->nb_param=nb_param;transfo->param=CALLOC(nb_param,double); transfo->typetrans=BSPLINE3D; transfo->resol=BASE3D.resol;transfo->degre=1; // Valeur codee en dur car ca ne marche que pour les splines de degre 1 p = transfo->param; /*Initialisation de masque_bloc*/ for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) masque_bloc[topi][topj][topk]=1; for (i=0;i<nb_param;i++) p_i[i]=p[i]=param[i]; /* initialisation des parametres normalises sur [0,1] */ for (i=0;i<nb_param/3;i++) { param_norm[3*i] =1.0*p[3*i] /wdth; param_norm[3*i+1]=1.0*p[3*i+1]/hght; param_norm[3*i+2]=1.0*p[3*i+2]/dpth; } //Mise a jour de Jm et JM dans les Slpqr for (i=0;i<8;i++) { Slpqr[i].Jm=Jmin; Slpqr[i].JM=Jmax; } /*calcul de l'energie de depart*/ Edebut=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); E2=Edebut; aff_log("Edebut: %.2f nb_param: %d \n",Edebut,nb_param); nb=nbreduc=0;prreduc=0.1/100.0; stop=1; // --- On fixe la pr�cision � 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la pr�cision en recalage sym�trique soit �quivalent que celle obtenue en non symetrique precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. debut resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif E=0; do { Eprec=E; E=0; E1=E2; compt=1; stop=0; /*for (pari=0;pari<MINI(2,resol);pari++) for (parj=0;parj<MINI(2,resol);parj++) for (park=0;park<MINI(2,resol);park++)*/ for(pari=MINI(2,resol)-1;pari>=0;pari--) for(parj=MINI(2,resol)-1;parj>=0;parj--) for(park=MINI(2,resol)-1;park>=0;park--) { for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) if ((topi%2==pari)&&(topj%2==parj)&&(topk%2==park)) if ((masque_param[topi][topj][topk]!=0)&&(masque_bloc[topi][topj][topk]!=0)) { //--------------------------------------------------------------- //----- initialisation Slpqr ------------------------- //--------------------------------------------------------------- l=TOP_conv_ind(topi,topj,topk,nb_param); xm = 1.0*x00[l/3]/wdth; xM = 1.0*x11[l/3]/wdth; ym = 1.0*y00[l/3]/hght; yM = 1.0*y11[l/3]/hght; zm = 1.0*z00[l/3]/dpth; zM =1.0*z11[l/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; /* Calcul du gradient*/ topD1 = l;; // printf("%d ieme bloc sur %d \r",topD1/3,nb_param/3); if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); for (i=0;i<3;i++) for (j=-1;j<2;j=j+2) { grad[topD1]=0;grad[topD1+1]=0;grad[topD1+2]=0; grad[topD1+i]=j; E2=TOP_linemin_locale_3d(imref,imreca,imres,champ_fin,the_transf,inter,dist,regularisation,nb_param,p,param_norm,grad,topi,topj,topk,Jmin,Jmax,Slpqr); E=E+E2; } if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); //-------Evaluation du deplacement max------------ maxpx=1.0*fabs(p_i[topD1]-p[topD1]); maxpy=1.0*fabs(p_i[topD1+1]-p[topD1+1]); maxpz=1.0*fabs(p_i[topD1+2]-p[topD1+2]); if ((maxpx<precisx)&&(maxpy<precisy)&&(maxpz<precisz)) masque_bloc[topi][topj][topk]=0; else {/* on debloque les blocs voisins */ /*for (i=MAXI(topi-1,0);i<=MINI(topi+1,topD-1);i++) for (j=MAXI(topj-1,0);j<=MINI(topj+1,topD-1);j++) for (k=MAXI(topk-1,0);k<=MINI(topk+1,topD-1);k++) masque_bloc[i][j][k]=1;*/ if (maxpx>precisx) { if (topi>0) masque_bloc[topi-1][topj][topk]=1; if (topi<topD-1) masque_bloc[topi+1][topj][topk]=1; } if (maxpy>precisy) { if (topj>0) masque_bloc[topi][topj-1][topk]=1; if (topj<topD-1) masque_bloc[topi][topj+1][topk]=1; } if (maxpz>precisz) { if (topk>0) masque_bloc[topi][topj][topk-1]=1; if (topk<topD-1) masque_bloc[topi][topj][topk+1]=1; } } stop++; } } for (i=0;i<nb_param;i++) p_i[i]=p[i]; printf("Minimisation sur %f %% des blocs Eprec : %f E : %f\n",300.0*stop/nb_param,Eprec,E); #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin iteration ..... "); #endif TOP_verification_all(nb_param,p,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif if (nomfichiertrf!=NULL) { #ifndef TOPO_COMPARE_CRITERE compare_critere(imref,imreca,imres,champ_fin,p,param_norm,nb_param,masque_param,nb); #endif } nb++; } while (nb<50 && Eprec!=E); /*calcul de l'energie finale*/ Efin=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); aff_log("nbiter: %d Efin: %.2f reduction: %.2f %% \n",nb,Efin,(Edebut-Efin)/Edebut*100.0); for (i=0;i<nb_param;i++) param[i]=p[i]; #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif #ifndef SAVE_INTERMEDIAIRE if (nomfichiertrf!=NULL) { /*si l'extension .trf existe on la supprime*/ strcpy(nomfichier,nomfichiertrf); ext=strstr(nomfichier,".trf"); if (ext!=NULL) *ext='\0'; strcat(nomfichier,"_"); temp[0]=(char)(resol+48); temp[1]=0; strcat(nomfichier,temp); save_transf_3d(transfo,nomfichier); } #endif /*liberation memoire des variables*/ //free_dvector(p,nb_param); free_dvector(p_i,nb_param); free_dvector(param_norm,nb_param); free_dvector(grad,nb_param); free_imatrix_3d(masque_bloc); free_transf3d(transfo); return(Efin); } double TOP_min_marquardt_locale_3d_bloc(grphic3d *imref, grphic3d *imreca, grphic3d *imres, double *p, double *p_i, double *param_norm, double *opp_param_norm, int nb_param, double *grad, dist_func_locale_t dist, reg_func_locale_t regularisation, reg_grad_locale_t gradient_reg, field3d *gradIref, field3d *maskgradIref, reg_hessien_locale_t hessien_reg, int (*gradient)(), int (*func_hessien)(), hessien3d *hessienIref, hessien3d *maskhessienIref, double Jmin, double Jmax, int ***masque_param, int ***masque_bloc, int topi, int topj, int topk) { int topD1,i,j,itmp,imin; double xm,xM,ym,yM,zm,zM,p_ini[3], Etmp,Emin,gradl[3],p_tmp[3], E; int wdth,hght,dpth; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11; int res_inv=0,continu,nb_iter,tutu; double nuk,ck=10,ck1,seuil_nuk; mat3d pseudo_hessien,hessien,inv_hessien; double energie_precision = 0.01; double lambda_ref = (1.0-TOPO_PONDERATION_RECALAGE_SYMETRIQUE)/TOPO_PONDERATION_RECALAGE_SYMETRIQUE; double maxpx,maxpy,maxpz,precis,precisx,precisy,precisz; int nb_pas = NB_PAS_LINEMIN_TOPO; int resol=BASE3D.resol; int topD=(int)pow(2.0,1.0*resol)-1; double max_delta_p=0, delta_p; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; wdth=imref->width;hght=imref->height;dpth=imref->depth; // --- On fixe la précision à 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la précision en recalage symétrique soit équivalent que celle obtenue en non symetrique if ((dist==Energie_atrophie_log_jacobien_locale_3d)||(dist==Energie_atrophie_jacobien_locale_3d)) {precis=pow(0.1,PRECISION_SIMULATION)*precis;} precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); topD1=TOP_conv_ind(topi,topj,topk,nb_param); // printf("%d ieme bloc sur %d \r",topD1/3,nb_param/3); //--------------------------------------------------------------- //----- initialisation Slpqr ------------------------- //--------------------------------------------------------------- xm = 1.0*x00[topD1/3]/wdth; xM = 1.0*x11[topD1/3]/wdth; ym = 1.0*y00[topD1/3]/hght; yM = 1.0*y11[topD1/3]/hght; zm = 1.0*z00[topD1/3]/dpth; zM =1.0*z11[topD1/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; for (i=0;i<3;i++) p_ini[i]=p[topD1+i]; if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); continu=0; nuk=0; ck=10; ck1=10; seuil_nuk=0; nb_iter=0; tutu=1; if (Etmp==0) continu=1; do{ Emin=Etmp; if (tutu>0) { // Calcul du gradient gradient(imref,imreca,nb_param,p,param_norm,gradIref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; func_hessien(imref, imreca, nb_param,p,param_norm,gradIref,maskgradIref,hessienIref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=hessien.H[i][j]; if ((nuk==0)&&(seuil_nuk==0)) { nuk=0.01*sqrt(hessien.H[0][0]*hessien.H[0][0]+hessien.H[1][1]*hessien.H[1][1]+hessien.H[2][2]*hessien.H[2][2]); seuil_nuk=100.0*sqrt(gradl[0]*gradl[0]+gradl[1]*gradl[1]+gradl[2]*gradl[2]); if ((seuil_nuk<100*nuk)||(nuk<0.0001)) { nuk=0.01;seuil_nuk=1000000; //on fixe des valeurs arbitraires } } } if((gradl[0]!=0)||(gradl[1]!=0)||(gradl[2]!=0)) { // Calcul du pseudo hessien Hk=H+nuk*I jusqu'a ce qu'il soit defini positif res_inv=0; while (res_inv==0) { for (i=0;i<3;i++) pseudo_hessien.H[i][i]=hessien.H[i][i]+nuk; res_inv=inversion_mat3d(&pseudo_hessien,&inv_hessien); if(res_inv==0) nuk=nuk*ck; } if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; max_delta_p=0; for (i=0;i<3;i++) for (j=0;j<3;j++) { delta_p=inv_hessien.H[i][j]*gradl[j]; max_delta_p=MAXI(max_delta_p,fabs(delta_p)); p[topD1+i]=p[topD1+i]-delta_p; } if (max_delta_p>TOPO_QUANTIFICATION_PARAM) // on ne calcul le critere que si la modif des params est superieur a TOPO_QUANTIFICATION_PARAM { for (i=0;i<3;i++) if (fabs(p[topD1+i])<TOPO_QUANTIFICATION_PARAM) /* C'est pour en finir avec les bug num�riques ... */ p[topD1+i]=0.0; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); } else Etmp=HUGE_VAL; if (Etmp>Emin) { for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; nuk=nuk*ck; Etmp=Emin; if (nuk>seuil_nuk) {continu=1;} tutu=0; nb_iter=0; } else{ { nuk=1.0*nuk/ck1; tutu=2; nb_iter++; if (((1.0*fabs((Emin-Etmp)/Emin))<energie_precision)||(nb_iter>10)||(Emin==0)) {continu=1;Emin=Etmp;} } } if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } else { continu=1; } }while (continu==0); // V�rification de la conservation de la topologie pour les nouveaux param if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) || ((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) { for(i=0;i<nb_param;i++) opp_param_norm[i]=-1.0*lambda_ref*param_norm[i]; } if ((TOP_verification_locale(nb_param,p,param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)||(res_inv==-1) ||(TOP_verification_locale(nb_param,p,opp_param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)) { for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); Emin=HUGE_VAL;imin=0; continu=1; for (itmp=0;((itmp<nb_pas)&&(continu==1));itmp++) { for (i=0;i<3;i++) p[topD1+i]=p_ini[i]+1.0*itmp/nb_pas*(p_tmp[i]-p_ini[i]); for (i=0;i<3;i++) if (fabs(p[topD1+i])<TOPO_QUANTIFICATION_PARAM) /* C'est pour en finir avec les bug num�riques ... */ p[topD1+i]=0.0; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) ||((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) { for(i=0;i<3;i++) opp_param_norm[topD1+i]=-1.0*lambda_ref*param_norm[topD1+i]; } if ((TOP_verification_locale(nb_param,p,param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0) ||(TOP_verification_locale(nb_param,p,opp_param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)) continu=0; else if (Etmp<Emin) {Emin=Etmp;imin=itmp;} } for (i=0;i<3;i++) p[topD1+i]=p_ini[i]+1.0*imin/nb_pas*(p_tmp[i]-p_ini[i]); param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) ||((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) { for(i=0;i<3;i++) opp_param_norm[topD1+i]=-1.0*lambda_ref*param_norm[topD1+i]; } if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } if (Emin==HUGE_VAL) {//printf("c'est un bug issu des pb numerique de topologie ...\n"); if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); for (i=0;i<3;i++) p[topD1+i]=p_ini[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Emin=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } E=E+Emin; //-------Evaluation du deplacement max------------ maxpx=1.0*fabs(p_i[topD1]-p[topD1]); maxpy=1.0*fabs(p_i[topD1+1]-p[topD1+1]); maxpz=1.0*fabs(p_i[topD1+2]-p[topD1+2]); if ((maxpx<precisx)&&(maxpy<precisy)&&(maxpz<precisz)) masque_bloc[topi][topj][topk]=0; else {/* on debloque les blocs voisins */ if (maxpx>precisx) { if (topi>0) masque_bloc[topi-1][topj][topk]=1; if (topi<topD-1) masque_bloc[topi+1][topj][topk]=1; } if (maxpy>precisy) { if (topj>0) masque_bloc[topi][topj-1][topk]=1; if (topj<topD-1) masque_bloc[topi][topj+1][topk]=1; } if (maxpz>precisz) { if (topk>0) masque_bloc[topi][topj][topk-1]=1; if (topk<topD-1) masque_bloc[topi][topj][topk+1]=1; } } return(Emin); } /******************************************************************************* ** TOP_min_marquardt_locale_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param) ** ** Minimisation par la m�thode de Levenberg-Marquardt ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retourne dans param *******************************************************************************/ double TOP_min_marquardt_locale_3d_parallel (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin, transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist, reg_func_locale_t regularisation, int nb_param, double *param, int ***masque_param,double Jmin, double Jmax,char *nomfichiertrf) { int wdth,hght,dpth,i; field3d *gradIref,*maskgradIref=NULL; double *grad,*p,*p_i,*param_norm; double Edebut,Efin,E1,E2,E,Eprec,Etmp; int nb,nbreduc,stop,nb_tmp; double prreduc,precis,precisx,precisy,precisz; int topi,topj,topk,topD,resol; int pari,parj,park; int compt; int ***masque_bloc; transf3d *transfo; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11; int (*gradient)(); int (*func_hessien)(); reg_grad_locale_t gradient_reg; reg_hessien_locale_t hessien_reg; hessien3d *hessienIref,*maskhessienIref=NULL; #ifndef SAVE_INTERMEDIAIRE char nomfichier[255]; char temp[2]; char *ext; #endif double energie_precision = 0.01; double *opp_param_norm=NULL; int nb_iter_max=50; if (dist==Energie_IM_locale_3d) energie_precision=0.0001; /* les variations relatives de l'IM sont en g�n�ral bcp plus faibles */ wdth=imref->width;hght=imref->height;dpth=imref->depth; resol=BASE3D.resol; topD=(int)pow(2.0,1.0*resol)-1; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) gradient=gradient_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) gradient=gradient_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) gradient=gradient_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) gradient=gradient_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) gradient=gradient_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) gradient=gradient_base_ICP_sym_locale_3d; if (dist==Energie_atrophie_jacobien_locale_3d) gradient=gradient_atrophie_jacobien_locale_3d; if (dist==Energie_atrophie_log_jacobien_locale_3d) gradient=gradient_atrophie_log_jacobien_locale_3d; if (dist==Energie_quad_locale_symetrique_3d) gradient=gradient_quad_locale_symetrique_3d; if (dist==Energie_quad_locale_symetrique_coupe_3d) gradient=gradient_quad_locale_symetrique_coupe_3d; if (dist==Energie_quad_sous_champ_locale_3d) gradient=gradient_quad_sous_champ_locale_3d; if (dist==Energie_groupwise_variance_locale_3d) gradient=gradient_groupwise_variance_locale_3d; if (dist==Energie_groupwise_variance_locale_nonsym_3d) gradient=gradient_groupwise_variance_locale_nonsym_3d; func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) func_hessien=hessien_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) func_hessien=hessien_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) func_hessien=hessien_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) func_hessien=hessien_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) func_hessien=hessien_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) func_hessien=hessien_base_ICP_sym_locale_3d; if (dist==Energie_atrophie_jacobien_locale_3d) func_hessien=hessien_atrophie_jacobien_locale_3d; if (dist==Energie_atrophie_log_jacobien_locale_3d) func_hessien=hessien_atrophie_log_jacobien_locale_3d; if (dist==Energie_quad_locale_symetrique_3d) func_hessien=hessien_quad_locale_symetrique_3d; if (dist==Energie_quad_locale_symetrique_coupe_3d) func_hessien=hessien_quad_locale_symetrique_coupe_3d; if (dist==Energie_quad_sous_champ_locale_3d) func_hessien=hessien_quad_sous_champ_locale_3d; if (dist==Energie_groupwise_variance_locale_3d) func_hessien=hessien_groupwise_variance_locale_3d; if (dist==Energie_groupwise_variance_locale_nonsym_3d) func_hessien=hessien_groupwise_variance_locale_nonsym_3d; gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) gradient_reg=gradient_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) gradient_reg=gradient_regularisation_log_jacobien_local; if (regularisation==regularisation_dist_identite_local) gradient_reg=gradient_regularisation_dist_identite_local; if (regularisation==regularisation_patch_imagebased_local) gradient_reg=gradient_regularisation_patch_imagebased_local; hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) hessien_reg=hessien_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) hessien_reg=hessien_regularisation_log_jacobien_local; if (regularisation==regularisation_dist_identite_local) hessien_reg=hessien_regularisation_dist_identite_local; if (regularisation==regularisation_patch_imagebased_local) hessien_reg=hessien_regularisation_patch_imagebased_local; //allocation memoire des variables //p=alloc_dvector(nb_param); p_i=alloc_dvector(nb_param); param_norm=alloc_dvector(nb_param); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) ||((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) opp_param_norm=alloc_dvector(nb_param); grad=alloc_dvector(nb_param); //gradIref=cr_field3d(wdth,hght,dpth); // pour economiser de la place memoire gradIref=champ_fin; masque_bloc=alloc_imatrix_3d(topD,topD,topD); if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) hessienIref=cr_hessien3d(wdth,hght,dpth); else hessienIref=NULL; if (dist==Energie_groupwise_variance_locale_3d) { _ParamRecalageBspline.grad_reca_groupwise=cr_field3d(wdth,hght,dpth); _ParamRecalageBspline.grad_ref_groupwise=cr_field3d(wdth,hght,dpth); _ParamRecalageBspline.grad_ref2_groupwise=cr_field3d(wdth,hght,dpth); _ParamRecalageBspline.hessien_reca_groupwise=cr_hessien3d(wdth,hght,dpth); _ParamRecalageBspline.hessien_ref_groupwise=cr_hessien3d(wdth,hght,dpth); _ParamRecalageBspline.hessien_ref2_groupwise=cr_hessien3d(wdth,hght,dpth); } if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) { maskhessienIref=cr_hessien3d(wdth,hght,dpth); maskgradIref=cr_field3d(wdth,hght,dpth); } transfo=cr_transf3d(wdth,hght,dpth,NULL); transfo->nb_param=nb_param;transfo->param=CALLOC(nb_param,double); transfo->typetrans=BSPLINE3D; transfo->resol=BASE3D.resol;transfo->degre=1; // Valeur codee en dur car ca ne marche que pour les splines de degre 1 p = transfo->param; //Initialisation de masque_bloc for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) masque_bloc[topi][topj][topk]=1; for (i=0;i<nb_param;i++) p_i[i]=p[i]=param[i]; // initialisation des parametres normalises sur [0,1] for (i=0;i<nb_param/3;i++) { param_norm[3*i] =1.0*p[3*i] /wdth; param_norm[3*i+1]=1.0*p[3*i+1]/hght; param_norm[3*i+2]=1.0*p[3*i+2]/dpth; } //Mise a jour de Jm et JM dans les Slpqr for (i=0;i<8;i++) { Slpqr[i].Jm=Jmin; Slpqr[i].JM=Jmax; } //calcul de l'energie de depart Edebut=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); E2=Edebut; // calcul du gradient de l'image a recaler if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_ICP_locale_3d)) imx_gradient_3d_p(imreca,gradIref,0,4); else if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) imx_gradient_3d_p(imreca,gradIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_gradient_3d_p(imreca->mask,maskgradIref,0,4); //--- Pour le recalage symetrique, on calcule le gradient de imref ----- if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_gradient_3d_p(imref,maskgradIref,2,4); // calcul du Hessien de l'image if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_ICP_locale_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_hessien_3d_p(imreca,hessienIref,0,4); else if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) imx_hessien_3d_p(imreca,hessienIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_hessien_3d_p(imreca->mask,maskhessienIref,0,4); //--- Pour le recalage symetrique, on calcule le hessien de imref ----- if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_hessien_3d_p(imref,maskhessienIref,2,4); //---- Pour le recalage groupwise, calcul des gradients et hessiens if (dist==Energie_groupwise_variance_locale_3d) { imx_gradient_3d_p(_ParamRecalageBspline.reca_groupwise,_ParamRecalageBspline.grad_reca_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_reca_groupwise,_ParamRecalageBspline.grad_reca_groupwise, _ParamRecalageBspline.reca_groupwise->rcoeff); imx_gradient_3d_p(_ParamRecalageBspline.ref_groupwise,_ParamRecalageBspline.grad_ref_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_ref_groupwise,_ParamRecalageBspline.grad_ref_groupwise, _ParamRecalageBspline.ref_groupwise->rcoeff); imx_gradient_3d_p(_ParamRecalageBspline.ref2_groupwise,_ParamRecalageBspline.grad_ref2_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_ref2_groupwise,_ParamRecalageBspline.grad_ref2_groupwise, _ParamRecalageBspline.ref2_groupwise->rcoeff); imx_hessien_3d_p(_ParamRecalageBspline.reca_groupwise,_ParamRecalageBspline.hessien_reca_groupwise,2,4); mul_hessien_3d(_ParamRecalageBspline.hessien_reca_groupwise, _ParamRecalageBspline.hessien_reca_groupwise, _ParamRecalageBspline.reca_groupwise->rcoeff); imx_hessien_3d_p(_ParamRecalageBspline.ref_groupwise,_ParamRecalageBspline.hessien_ref_groupwise,2,4); mul_hessien_3d(_ParamRecalageBspline.hessien_ref_groupwise, _ParamRecalageBspline.hessien_ref_groupwise, _ParamRecalageBspline.ref_groupwise->rcoeff); imx_hessien_3d_p(_ParamRecalageBspline.ref2_groupwise,_ParamRecalageBspline.hessien_ref2_groupwise,2,4); mul_hessien_3d(_ParamRecalageBspline.hessien_ref2_groupwise, _ParamRecalageBspline.hessien_ref2_groupwise, _ParamRecalageBspline.ref2_groupwise->rcoeff); } aff_log("Edebut: %.2f nb_param: %d \n",Edebut,nb_param); nb=nbreduc=0;prreduc=0.1/100.0; stop=1; // --- On fixe la pr�cision � 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la pr�cision en recalage sym�trique soit �quivalent que celle obtenue en non symetrique if ((dist==Energie_atrophie_log_jacobien_locale_3d)||(dist==Energie_atrophie_jacobien_locale_3d)) {precis=pow(0.1,PRECISION_SIMULATION)*precis; nb_iter_max=200;} precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); E=0; do { Eprec=E; E=0; E1=E2; compt=1; stop=0; nb_tmp=0; for(pari=MINI(2,resol)-1;pari>=0;pari--) for(parj=MINI(2,resol)-1;parj>=0;parj--) for(park=MINI(2,resol)-1;park>=0;park--) { #pragma omp parallel for private(topi,topj,topk,Etmp) shared(E) schedule(dynamic) for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) if ((topi%2==pari)&&(topj%2==parj)&&(topk%2==park)) if ((masque_param[topi][topj][topk]!=0)&&(masque_bloc[topi][topj][topk]!=0)) { Etmp=TOP_min_marquardt_locale_3d_bloc(imref, imreca,imres, p, p_i, param_norm, opp_param_norm, nb_param, grad, dist, regularisation, gradient_reg, gradIref, maskgradIref, hessien_reg, gradient,func_hessien, hessienIref, maskhessienIref, Jmin, Jmax, masque_param, masque_bloc, topi, topj, topk); E=E+Etmp; } #pragma end parallel for stop++; } for (i=0;i<nb_param;i++) p_i[i]=p[i]; printf("Minimisation sur %f %% des blocs Eprec : %f E : %f\n",300.0*stop/nb_param,Eprec,E); #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin iteration ..... "); #endif TOP_verification_all(nb_param,p,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif if (nomfichiertrf!=NULL) { #ifndef TOPO_COMPARE_CRITERE compare_critere(imref,imreca,imres,champ_fin,p,param_norm,nb_param,masque_param,nb); #endif } nb++; } while (nb<nb_iter_max && Eprec!=E); //calcul de l'energie finale Efin=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); aff_log("nbiter: %d Efin: %.2f reduction: %.2f %% \n",nb,Efin,(Edebut-Efin)/Edebut*100.0); for (i=0;i<nb_param;i++) param[i]=p[i]; #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif #ifndef SAVE_INTERMEDIAIRE if (nomfichiertrf!=NULL) { //si l'extension .trf existe on la supprime strcpy(nomfichier,nomfichiertrf); ext=strstr(nomfichier,".trf"); if (ext!=NULL) *ext='\0'; strcat(nomfichier,"_"); temp[0]=(char)(resol+48); temp[1]=0; strcat(nomfichier,temp); save_transf_3d(transfo,nomfichier); } #endif //liberation memoire des variables free_dvector(p_i,nb_param); free_dvector(param_norm,nb_param); free_dvector(grad,nb_param); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) ||((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) free_dvector(opp_param_norm,nb_param); free_imatrix_3d(masque_bloc); if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) free_hessien3d(hessienIref); free_transf3d(transfo); if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) {free_hessien3d(maskhessienIref); free_field3d(maskgradIref); } if (dist==Energie_groupwise_variance_locale_3d) { free_field3d(_ParamRecalageBspline.grad_reca_groupwise); free_field3d(_ParamRecalageBspline.grad_ref_groupwise); free_field3d(_ParamRecalageBspline.grad_ref2_groupwise); free_hessien3d(_ParamRecalageBspline.hessien_reca_groupwise); free_hessien3d(_ParamRecalageBspline.hessien_ref_groupwise); free_hessien3d(_ParamRecalageBspline.hessien_ref2_groupwise); } return(Efin); } /******************************************************************************* ** TOP_min_marquardt_locale_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param) ** ** Minimisation par la méthode de Levenberg-Marquardt ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retourne dans param *******************************************************************************/ double TOP_min_marquardt_locale_3d (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin, transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist, reg_func_locale_t regularisation, int nb_param, double *param, int ***masque_param,double Jmin, double Jmax,char *nomfichiertrf) { int wdth,hght,dpth,i,j/*,k*/; field3d *gradIref,*maskgradIref=NULL; double *grad,*p,*p_i,gradl[3],*param_norm,p_ini[3],p_tmp[3]; double Edebut,Efin,E1,E2,E,Eprec,Emin,Etmp; int nb,nbreduc,stop,nb_iter,nb_tmp; double prreduc,maxpx,maxpy,maxpz,precis,precisx,precisy,precisz; int topi,topj,topk,topD,resol; int pari,parj,park; int compt,topD1; int ***masque_bloc; transf3d *transfo; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11; int (*gradient)(); int (*func_hessien)(); reg_grad_locale_t gradient_reg; reg_hessien_locale_t hessien_reg; hessien3d *hessienIref,*maskhessienIref=NULL; mat3d pseudo_hessien,hessien,inv_hessien; //double cfmax; double xm,xM,ym,yM,zm,zM; int res_inv=0,continu; double nuk,ck=10,ck1,seuil_nuk; int tutu; #ifndef SAVE_INTERMEDIAIRE char nomfichier[255]; char temp[2]; char *ext; #endif int nb_pas = NB_PAS_LINEMIN_TOPO,itmp,imin; double energie_precision = 0.01; double *opp_param_norm=NULL; double lambda_ref = (1.0-TOPO_PONDERATION_RECALAGE_SYMETRIQUE)/TOPO_PONDERATION_RECALAGE_SYMETRIQUE; int nb_iter_max=50; double max_delta_p=0, delta_p; if (dist==Energie_IM_locale_3d) energie_precision=0.0001; /* les variations relatives de l'IM sont en général bcp plus faibles */ wdth=imref->width;hght=imref->height;dpth=imref->depth; resol=BASE3D.resol; topD=(int)pow(2.0,1.0*resol)-1; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) gradient=gradient_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) gradient=gradient_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) gradient=gradient_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) gradient=gradient_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) gradient=gradient_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) gradient=gradient_base_ICP_sym_locale_3d; if (dist==Energie_atrophie_jacobien_locale_3d) gradient=gradient_atrophie_jacobien_locale_3d; if (dist==Energie_atrophie_log_jacobien_locale_3d) gradient=gradient_atrophie_log_jacobien_locale_3d; if (dist==Energie_quad_locale_symetrique_3d) gradient=gradient_quad_locale_symetrique_3d; if (dist==Energie_quad_locale_symetrique_coupe_3d) gradient=gradient_quad_locale_symetrique_coupe_3d; if (dist==Energie_quad_sous_champ_locale_3d) gradient=gradient_quad_sous_champ_locale_3d; if (dist==Energie_groupwise_variance_locale_3d) gradient=gradient_groupwise_variance_locale_3d; if (dist==Energie_groupwise_variance_locale_nonsym_3d) gradient=gradient_groupwise_variance_locale_nonsym_3d; func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) func_hessien=hessien_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) func_hessien=hessien_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) func_hessien=hessien_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) func_hessien=hessien_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) func_hessien=hessien_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) func_hessien=hessien_base_ICP_sym_locale_3d; if (dist==Energie_atrophie_jacobien_locale_3d) func_hessien=hessien_atrophie_jacobien_locale_3d; if (dist==Energie_atrophie_log_jacobien_locale_3d) func_hessien=hessien_atrophie_log_jacobien_locale_3d; if (dist==Energie_quad_locale_symetrique_3d) func_hessien=hessien_quad_locale_symetrique_3d; if (dist==Energie_quad_locale_symetrique_coupe_3d) func_hessien=hessien_quad_locale_symetrique_coupe_3d; if (dist==Energie_quad_sous_champ_locale_3d) func_hessien=hessien_quad_sous_champ_locale_3d; if (dist==Energie_groupwise_variance_locale_3d) func_hessien=hessien_groupwise_variance_locale_3d; if (dist==Energie_groupwise_variance_locale_nonsym_3d) func_hessien=hessien_groupwise_variance_locale_nonsym_3d; gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) gradient_reg=gradient_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) gradient_reg=gradient_regularisation_log_jacobien_local; if (regularisation==regularisation_dist_identite_local) gradient_reg=gradient_regularisation_dist_identite_local; if (regularisation==regularisation_patch_imagebased_local) gradient_reg=gradient_regularisation_patch_imagebased_local; hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) hessien_reg=hessien_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) hessien_reg=hessien_regularisation_log_jacobien_local; if (regularisation==regularisation_dist_identite_local) hessien_reg=hessien_regularisation_dist_identite_local; if (regularisation==regularisation_patch_imagebased_local) hessien_reg=hessien_regularisation_patch_imagebased_local; //allocation memoire des variables //p=alloc_dvector(nb_param); p_i=alloc_dvector(nb_param); param_norm=alloc_dvector(nb_param); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) ||((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) opp_param_norm=alloc_dvector(nb_param); grad=alloc_dvector(nb_param); //gradIref=cr_field3d(wdth,hght,dpth); // pour economiser de la place memoire gradIref=champ_fin; masque_bloc=alloc_imatrix_3d(topD,topD,topD); if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) hessienIref=cr_hessien3d(wdth,hght,dpth); else hessienIref=NULL; if (dist==Energie_groupwise_variance_locale_3d) { _ParamRecalageBspline.grad_reca_groupwise=cr_field3d(wdth,hght,dpth); _ParamRecalageBspline.grad_ref_groupwise=cr_field3d(wdth,hght,dpth); _ParamRecalageBspline.grad_ref2_groupwise=cr_field3d(wdth,hght,dpth); _ParamRecalageBspline.hessien_reca_groupwise=cr_hessien3d(wdth,hght,dpth); _ParamRecalageBspline.hessien_ref_groupwise=cr_hessien3d(wdth,hght,dpth); _ParamRecalageBspline.hessien_ref2_groupwise=cr_hessien3d(wdth,hght,dpth); } if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) { maskhessienIref=cr_hessien3d(wdth,hght,dpth); maskgradIref=cr_field3d(wdth,hght,dpth); } transfo=cr_transf3d(wdth,hght,dpth,NULL); transfo->nb_param=nb_param;transfo->param=CALLOC(nb_param,double); transfo->typetrans=BSPLINE3D; transfo->resol=BASE3D.resol;transfo->degre=1; // Valeur codee en dur car ca ne marche que pour les splines de degre 1 p = transfo->param; //Initialisation de masque_bloc for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) masque_bloc[topi][topj][topk]=1; for (i=0;i<nb_param;i++) p_i[i]=p[i]=param[i]; // initialisation des parametres normalises sur [0,1] for (i=0;i<nb_param/3;i++) { param_norm[3*i] =1.0*p[3*i] /wdth; param_norm[3*i+1]=1.0*p[3*i+1]/hght; param_norm[3*i+2]=1.0*p[3*i+2]/dpth; } //Mise a jour de Jm et JM dans les Slpqr for (i=0;i<8;i++) { Slpqr[i].Jm=Jmin; Slpqr[i].JM=Jmax; } //calcul de l'energie de depart Edebut=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); E2=Edebut; // calcul du gradient de l'image a recaler if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_ICP_locale_3d)) imx_gradient_3d_p(imreca,gradIref,0,4); else if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) imx_gradient_3d_p(imreca,gradIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_gradient_3d_p(imreca->mask,maskgradIref,0,4); //--- Pour le recalage symetrique, on calcule le gradient de imref ----- if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_gradient_3d_p(imref,maskgradIref,2,4); // calcul du Hessien de l'image if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_ICP_locale_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_hessien_3d_p(imreca,hessienIref,0,4); else if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) imx_hessien_3d_p(imreca,hessienIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_hessien_3d_p(imreca->mask,maskhessienIref,0,4); //--- Pour le recalage symetrique, on calcule le hessien de imref ----- if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_hessien_3d_p(imref,maskhessienIref,2,4); //---- Pour le recalage groupwise, calcul des gradients et hessiens if (dist==Energie_groupwise_variance_locale_3d) { imx_gradient_3d_p(_ParamRecalageBspline.reca_groupwise,_ParamRecalageBspline.grad_reca_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_reca_groupwise,_ParamRecalageBspline.grad_reca_groupwise, _ParamRecalageBspline.reca_groupwise->rcoeff); imx_gradient_3d_p(_ParamRecalageBspline.ref_groupwise,_ParamRecalageBspline.grad_ref_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_ref_groupwise,_ParamRecalageBspline.grad_ref_groupwise, _ParamRecalageBspline.ref_groupwise->rcoeff); imx_gradient_3d_p(_ParamRecalageBspline.ref2_groupwise,_ParamRecalageBspline.grad_ref2_groupwise,2,4); mul_field_3d(_ParamRecalageBspline.grad_ref2_groupwise,_ParamRecalageBspline.grad_ref2_groupwise, _ParamRecalageBspline.ref2_groupwise->rcoeff); imx_hessien_3d_p(_ParamRecalageBspline.reca_groupwise,_ParamRecalageBspline.hessien_reca_groupwise,2,4); mul_hessien_3d(_ParamRecalageBspline.hessien_reca_groupwise, _ParamRecalageBspline.hessien_reca_groupwise, _ParamRecalageBspline.reca_groupwise->rcoeff); imx_hessien_3d_p(_ParamRecalageBspline.ref_groupwise,_ParamRecalageBspline.hessien_ref_groupwise,2,4); mul_hessien_3d(_ParamRecalageBspline.hessien_ref_groupwise, _ParamRecalageBspline.hessien_ref_groupwise, _ParamRecalageBspline.ref_groupwise->rcoeff); imx_hessien_3d_p(_ParamRecalageBspline.ref2_groupwise,_ParamRecalageBspline.hessien_ref2_groupwise,2,4); mul_hessien_3d(_ParamRecalageBspline.hessien_ref2_groupwise, _ParamRecalageBspline.hessien_ref2_groupwise, _ParamRecalageBspline.ref2_groupwise->rcoeff); } aff_log("Edebut: %.2f nb_param: %d \n",Edebut,nb_param); nb=nbreduc=0;prreduc=0.1/100.0; stop=1; // --- On fixe la précision à 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la précision en recalage symétrique soit équivalent que celle obtenue en non symetrique if ((dist==Energie_atrophie_log_jacobien_locale_3d)||(dist==Energie_atrophie_jacobien_locale_3d)) {precis=pow(0.1,PRECISION_SIMULATION)*precis; nb_iter_max=200;} precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); E=0; do { Eprec=E; E=0; E1=E2; compt=1; stop=0; nb_tmp=0; for(pari=MINI(2,resol)-1;pari>=0;pari--) for(parj=MINI(2,resol)-1;parj>=0;parj--) for(park=MINI(2,resol)-1;park>=0;park--) { for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) if ((topi%2==pari)&&(topj%2==parj)&&(topk%2==park)) if ((masque_param[topi][topj][topk]!=0)&&(masque_bloc[topi][topj][topk]!=0)) { topD1=TOP_conv_ind(topi,topj,topk,nb_param); // printf("%d ieme bloc sur %d \r",topD1/3,nb_param/3); //--------------------------------------------------------------- //----- initialisation Slpqr ------------------------- //--------------------------------------------------------------- xm = 1.0*x00[topD1/3]/wdth; xM = 1.0*x11[topD1/3]/wdth; ym = 1.0*y00[topD1/3]/hght; yM = 1.0*y11[topD1/3]/hght; zm = 1.0*z00[topD1/3]/dpth; zM =1.0*z11[topD1/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; for (i=0;i<3;i++) p_ini[i]=p[topD1+i]; if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); continu=0; nuk=0; ck=10; ck1=10; seuil_nuk=0; nb_iter=0; tutu=1; if (Etmp==0) continu=1; do{ Emin=Etmp; if (tutu>0) { // Calcul du gradient gradient(imref,imreca,nb_param,p,param_norm,gradIref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; func_hessien(imref, imreca, nb_param,p,param_norm,gradIref,maskgradIref,hessienIref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=hessien.H[i][j]; if ((nuk==0)&&(seuil_nuk==0)) { nuk=0.01*sqrt(hessien.H[0][0]*hessien.H[0][0]+hessien.H[1][1]*hessien.H[1][1]+hessien.H[2][2]*hessien.H[2][2]); seuil_nuk=100.0*sqrt(gradl[0]*gradl[0]+gradl[1]*gradl[1]+gradl[2]*gradl[2]); if ((seuil_nuk<100*nuk)||(nuk<0.0001)) { nuk=0.01;seuil_nuk=1000000; //on fixe des valeurs arbitraires } } } if((gradl[0]!=0)||(gradl[1]!=0)||(gradl[2]!=0)) { // Calcul du pseudo hessien Hk=H+nuk*I jusqu'a ce qu'il soit defini positif res_inv=0; while (res_inv==0) { for (i=0;i<3;i++) pseudo_hessien.H[i][i]=hessien.H[i][i]+nuk; res_inv=inversion_mat3d(&pseudo_hessien,&inv_hessien); if(res_inv==0) nuk=nuk*ck; } if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; max_delta_p=0; for (i=0;i<3;i++) for (j=0;j<3;j++) { delta_p=inv_hessien.H[i][j]*gradl[j]; max_delta_p=MAXI(max_delta_p,fabs(delta_p)); p[topD1+i]=p[topD1+i]-delta_p; } if (max_delta_p>TOPO_QUANTIFICATION_PARAM) // on ne calcul le critere que si la modif des params est superieur a TOPO_QUANTIFICATION_PARAM { for (i=0;i<3;i++) if (fabs(p[topD1+i])<TOPO_QUANTIFICATION_PARAM) /* C'est pour en finir avec les bug numériques ... */ p[topD1+i]=0.0; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); } else Etmp=HUGE_VAL; if (Etmp>Emin) { for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; nuk=nuk*ck; Etmp=Emin; if (nuk>seuil_nuk) {continu=1;} tutu=0; nb_iter=0; } else{ { nuk=1.0*nuk/ck1; tutu=2; nb_iter++; if (((1.0*fabs((Emin-Etmp)/Emin))<energie_precision)||(nb_iter>10)||(Emin==0)) {continu=1;Emin=Etmp;} } } if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } else { continu=1; } }while (continu==0); // Vérification de la conservation de la topologie pour les nouveaux param if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) || ((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) { for(i=0;i<nb_param;i++) opp_param_norm[i]=-1.0*lambda_ref*param_norm[i]; } if ((TOP_verification_locale(nb_param,p,param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)||(res_inv==-1) ||(TOP_verification_locale(nb_param,p,opp_param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)) { for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); Emin=HUGE_VAL;imin=0; continu=1; for (itmp=0;((itmp<nb_pas)&&(continu==1));itmp++) { for (i=0;i<3;i++) p[topD1+i]=p_ini[i]+1.0*itmp/nb_pas*(p_tmp[i]-p_ini[i]); for (i=0;i<3;i++) if (fabs(p[topD1+i])<TOPO_QUANTIFICATION_PARAM) /* C'est pour en finir avec les bug numériques ... */ p[topD1+i]=0.0; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) ||((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) { for(i=0;i<3;i++) opp_param_norm[topD1+i]=-1.0*lambda_ref*param_norm[topD1+i]; } if ((TOP_verification_locale(nb_param,p,param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0) ||(TOP_verification_locale(nb_param,p,opp_param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)) continu=0; else if (Etmp<Emin) {Emin=Etmp;imin=itmp;} } for (i=0;i<3;i++) p[topD1+i]=p_ini[i]+1.0*imin/nb_pas*(p_tmp[i]-p_ini[i]); param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) ||((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) { for(i=0;i<3;i++) opp_param_norm[topD1+i]=-1.0*lambda_ref*param_norm[topD1+i]; } if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } if (Emin==HUGE_VAL) {//printf("c'est un bug issu des pb numerique de topologie ...\n"); if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); for (i=0;i<3;i++) p[topD1+i]=p_ini[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Emin=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } E=E+Emin; //-------Evaluation du deplacement max------------ maxpx=1.0*fabs(p_i[topD1]-p[topD1]); maxpy=1.0*fabs(p_i[topD1+1]-p[topD1+1]); maxpz=1.0*fabs(p_i[topD1+2]-p[topD1+2]); if ((maxpx<precisx)&&(maxpy<precisy)&&(maxpz<precisz)) masque_bloc[topi][topj][topk]=0; else {/* on debloque les blocs voisins */ if (maxpx>precisx) { if (topi>0) masque_bloc[topi-1][topj][topk]=1; if (topi<topD-1) masque_bloc[topi+1][topj][topk]=1; } if (maxpy>precisy) { if (topj>0) masque_bloc[topi][topj-1][topk]=1; if (topj<topD-1) masque_bloc[topi][topj+1][topk]=1; } if (maxpz>precisz) { if (topk>0) masque_bloc[topi][topj][topk-1]=1; if (topk<topD-1) masque_bloc[topi][topj][topk+1]=1; } } stop++; } } for (i=0;i<nb_param;i++) p_i[i]=p[i]; printf("Minimisation sur %f %% des blocs Eprec : %f E : %f\n",300.0*stop/nb_param,Eprec,E); #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin iteration ..... "); #endif TOP_verification_all(nb_param,p,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif if (nomfichiertrf!=NULL) { #ifndef TOPO_COMPARE_CRITERE compare_critere(imref,imreca,imres,champ_fin,p,param_norm,nb_param,masque_param,nb); #endif } nb++; } while (nb<nb_iter_max && Eprec!=E); //calcul de l'energie finale Efin=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); aff_log("nbiter: %d Efin: %.2f reduction: %.2f %% \n",nb,Efin,(Edebut-Efin)/Edebut*100.0); for (i=0;i<nb_param;i++) param[i]=p[i]; #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif #ifndef SAVE_INTERMEDIAIRE if (nomfichiertrf!=NULL) { //si l'extension .trf existe on la supprime strcpy(nomfichier,nomfichiertrf); ext=strstr(nomfichier,".trf"); if (ext!=NULL) *ext='\0'; strcat(nomfichier,"_"); temp[0]=(char)(resol+48); temp[1]=0; strcat(nomfichier,temp); save_transf_3d(transfo,nomfichier); } #endif //liberation memoire des variables free_dvector(p_i,nb_param); free_dvector(param_norm,nb_param); free_dvector(grad,nb_param); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)||(dist==Energie_groupwise_variance_locale_3d) ||((dist==Energie_quad_sous_champ_locale_3d)&&(TOPO_PONDERATION_RECALAGE_SYMETRIQUE > 0.0))) free_dvector(opp_param_norm,nb_param); free_imatrix_3d(masque_bloc); if ((dist!=Energie_quad_sous_champ_locale_3d)&&(dist!=Energie_groupwise_variance_locale_3d)) free_hessien3d(hessienIref); free_transf3d(transfo); if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) {free_hessien3d(maskhessienIref); free_field3d(maskgradIref); } if (dist==Energie_groupwise_variance_locale_3d) { free_field3d(_ParamRecalageBspline.grad_reca_groupwise); free_field3d(_ParamRecalageBspline.grad_ref_groupwise); free_field3d(_ParamRecalageBspline.grad_ref2_groupwise); free_hessien3d(_ParamRecalageBspline.hessien_reca_groupwise); free_hessien3d(_ParamRecalageBspline.hessien_ref_groupwise); free_hessien3d(_ParamRecalageBspline.hessien_ref2_groupwise); } return(Efin); } /******************************************************************************* ** TOP_min_marquardt_locale_lent_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param) ** ** Minimisation par la m�thode de Levenberg-Marquardt ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retourne dans param *******************************************************************************/ double TOP_min_marquardt_locale_lent_3d (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin, transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist, reg_func_locale_t regularisation, int nb_param, double *param, int ***masque_param,double Jmin, double Jmax,char *nomfichiertrf) { int wdth,hght,dpth,i,j/*,k*/; field3d *gradIref,*maskgradIref=NULL; double *grad,*p,*p_i,gradl[3],*param_norm,p_ini[3],p_tmp[3]; double Edebut,Efin,E1,E2,E,Eprec,Emin,Etmp; int nb,nbreduc,stop,nb_iter,nb_tmp; double prreduc,maxpx,maxpy,maxpz,precis,precisx,precisy,precisz; int topi,topj,topk,topD,resol; int pari,parj,park; int compt,topD1; int ***masque_bloc; transf3d *transfo; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11; int (*gradient)(); int (*func_hessien)(); reg_grad_locale_t gradient_reg; reg_hessien_locale_t hessien_reg; hessien3d *hessienIref,*maskhessienIref=NULL; mat3d pseudo_hessien,hessien,inv_hessien; //double cfmax; double xm,xM,ym,yM,zm,zM; int res_inv=0,continu,pas; double nuk,ck=10,ck1,seuil_nuk; int tutu; #ifndef SAVE_INTERMEDIAIRE char nomfichier[255]; char temp[2]; char *ext; #endif int nb_pas = NB_PAS_LINEMIN_TOPO,itmp,imin; double energie_precision = 0.01; double *opp_param_norm=NULL; double lambda_ref = (1.0-TOPO_PONDERATION_RECALAGE_SYMETRIQUE)/TOPO_PONDERATION_RECALAGE_SYMETRIQUE; if (dist==Energie_IM_locale_3d) energie_precision=0.0001; /* les variations relatives de l'IM sont en g�n�ral bcp plus faibles */ wdth=imref->width;hght=imref->height;dpth=imref->depth; resol=BASE3D.resol; topD=(int)pow(2.0,1.0*resol)-1; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) gradient=gradient_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) gradient=gradient_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) gradient=gradient_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) gradient=gradient_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) gradient=gradient_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) gradient=gradient_base_ICP_sym_locale_3d; if (dist==Energie_atrophie_jacobien_locale_3d) gradient=gradient_atrophie_jacobien_locale_3d; if (dist==Energie_atrophie_log_jacobien_locale_3d) gradient=gradient_atrophie_log_jacobien_locale_3d; if (dist==Energie_quad_locale_symetrique_3d) gradient=gradient_quad_locale_symetrique_3d; if (dist==Energie_quad_locale_symetrique_coupe_3d) gradient=gradient_quad_locale_symetrique_coupe_3d; func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) func_hessien=hessien_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) func_hessien=hessien_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) func_hessien=hessien_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) func_hessien=hessien_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) func_hessien=hessien_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) func_hessien=hessien_base_ICP_sym_locale_3d; if (dist==Energie_atrophie_jacobien_locale_3d) func_hessien=hessien_atrophie_jacobien_locale_3d; if (dist==Energie_atrophie_log_jacobien_locale_3d) func_hessien=hessien_atrophie_log_jacobien_locale_3d; if (dist==Energie_quad_locale_symetrique_3d) func_hessien=hessien_quad_locale_symetrique_3d; if (dist==Energie_quad_locale_symetrique_coupe_3d) func_hessien=hessien_quad_locale_symetrique_coupe_3d; gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) gradient_reg=gradient_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) gradient_reg=gradient_regularisation_log_jacobien_local; hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) hessien_reg=hessien_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) hessien_reg=hessien_regularisation_energie_membrane_local; //allocation memoire des variables //p=alloc_dvector(nb_param); p_i=alloc_dvector(nb_param); param_norm=alloc_dvector(nb_param); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) opp_param_norm=alloc_dvector(nb_param); grad=alloc_dvector(nb_param); //gradIref=cr_field3d(wdth,hght,dpth); // pour economiser de la place memoire gradIref=champ_fin; masque_bloc=alloc_imatrix_3d(topD,topD,topD); hessienIref=cr_hessien3d(wdth,hght,dpth); if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) { maskhessienIref=cr_hessien3d(wdth,hght,dpth); maskgradIref=cr_field3d(wdth,hght,dpth); } transfo=cr_transf3d(wdth,hght,dpth,NULL); transfo->nb_param=nb_param;transfo->param=CALLOC(nb_param,double); transfo->typetrans=BSPLINE3D; transfo->resol=BASE3D.resol;transfo->degre=1; // Valeur codee en dur car ca ne marche que pour les splines de degre 1 p = transfo->param; //Initialisation de masque_bloc for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) masque_bloc[topi][topj][topk]=1; for (i=0;i<nb_param;i++) p_i[i]=p[i]=param[i]; // initialisation des parametres normalises sur [0,1] for (i=0;i<nb_param/3;i++) { param_norm[3*i] =1.0*p[3*i] /wdth; param_norm[3*i+1]=1.0*p[3*i+1]/hght; param_norm[3*i+2]=1.0*p[3*i+2]/dpth; } //Mise a jour de Jm et JM dans les Slpqr for (i=0;i<8;i++) { Slpqr[i].Jm=Jmin; Slpqr[i].JM=Jmax; } //calcul de l'energie de depart Edebut=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); E2=Edebut; // calcul du gradient de l'image a recaler if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_ICP_locale_3d)) imx_gradient_3d_p(imreca,gradIref,0,4); else imx_gradient_3d_p(imreca,gradIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_gradient_3d_p(imreca->mask,maskgradIref,0,4); //--- Pour le recalage symetrique, on calcule le gradient de imref ----- if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_gradient_3d_p(imref,maskgradIref,2,4); // calcul du Hessien de l'image if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_ICP_locale_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_hessien_3d_p(imreca,hessienIref,0,4); else imx_hessien_3d_p(imreca,hessienIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_hessien_3d_p(imreca->mask,maskhessienIref,0,4); //--- Pour le recalage symetrique, on calcule le hessien de imref ----- if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) imx_hessien_3d_p(imref,maskhessienIref,2,4); aff_log("Edebut: %.2f nb_param: %d \n",Edebut,nb_param); nb=nbreduc=0;prreduc=0.1/100.0; stop=1; E=0; //E=Edebut; do { Eprec=E; E=0; E1=E2; compt=1; stop=0; nb_tmp=0; /*for (pari=0;pari<MINI(2,resol);pari++) for (parj=0;parj<MINI(2,resol);parj++) for (park=0;park<MINI(2,resol);park++)*/ /*if (dist==Energie_geman_locale_3d) update_TOPO_ALPHA_ROBUST_global(imref,imreca, nb_param, p);*/ for(pas=0; pas<11; pas++) { // --- On fixe la pr�cision � 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la pr�cision en recalage sym�trique soit �quivalent que celle obtenue en non symetrique precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); for(pari=MINI(2,resol)-1;pari>=0;pari--) for(parj=MINI(2,resol)-1;parj>=0;parj--) for(park=MINI(2,resol)-1;park>=0;park--) { for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) if ((topi%2==pari)&&(topj%2==parj)&&(topk%2==park)) if ((masque_param[topi][topj][topk]!=0)&&(masque_bloc[topi][topj][topk]!=0)) { /*borne_jacobien_bspline1_local_3d( nb_param, p, param_norm, topi, topj, topk, &min1, &max1); regularisation_energie_membrane_local(nb_param, p, topi, topj, topk, &min2, &max2); if (((min1-min2)/min1>0.0001)||((max1-max2)/max1>0.0001)) printf ("Aie un bug : min1 : %f min2 : %f max1 : %f max2 : %f \n",min1,min2,max1,max2); else printf ("OK : min1 : %f min2 : %f max1 : %f max2 : %f \n",min1,min2,max1,max2);*/ topD1=TOP_conv_ind(topi,topj,topk,nb_param); // printf("%d ieme bloc sur %d \r",topD1/3,nb_param/3); //--------------------------------------------------------------- //----- initialisation Slpqr ------------------------- //--------------------------------------------------------------- xm = 1.0*x00[topD1/3]/wdth; xM = 1.0*x11[topD1/3]/wdth; ym = 1.0*y00[topD1/3]/hght; yM = 1.0*y11[topD1/3]/hght; zm = 1.0*z00[topD1/3]/dpth; zM =1.0*z11[topD1/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; for (i=0;i<3;i++) p_ini[i]=p[topD1+i]; if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); continu=0; nuk=0; ck=10; ck1=10; seuil_nuk=0; nb_iter=0; tutu=1; if (Etmp==0) continu=1; do{ Emin=Etmp; if (tutu>0) { // Calcul du gradient gradient(imref,imreca,nb_param,p,param_norm,gradIref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; func_hessien(imref, imreca, nb_param,p,param_norm,gradIref,maskgradIref,hessienIref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=hessien.H[i][j]; if ((nuk==0)&&(seuil_nuk==0)) { nuk=0.01*sqrt(hessien.H[0][0]*hessien.H[0][0]+hessien.H[1][1]*hessien.H[1][1]+hessien.H[2][2]*hessien.H[2][2]); seuil_nuk=100.0*sqrt(gradl[0]*gradl[0]+gradl[1]*gradl[1]+gradl[2]*gradl[2]); /*normG=sqrt(gradl[0]*gradl[0]+gradl[1]*gradl[1]+gradl[2]*gradl[2]); normH=sqrt(hessien.H[0][0]*hessien.H[0][0]+hessien.H[1][1]*hessien.H[1][1]+hessien.H[2][2]*hessien.H[2][2]); nuk=MINI(pow(0.001*normG,2)/normH,0.01*normH); seuil_nuk=MAXI(pow(1000*normG,2)/normH,100*normG);*/ if ((seuil_nuk<100*nuk)||(nuk<0.0001)) { nuk=0.01;seuil_nuk=1000000; //on fixe des valeurs arbitraires } } } if((gradl[0]!=0)||(gradl[1]!=0)||(gradl[2]!=0)) { // Calcul du pseudo hessien Hk=H+nuk*I jusqu'a ce qu'il soit defini positif res_inv=0; while (res_inv==0) { for (i=0;i<3;i++) pseudo_hessien.H[i][i]=hessien.H[i][i]+nuk; res_inv=inversion_mat3d(&pseudo_hessien,&inv_hessien); if(res_inv==0) nuk=nuk*ck; } if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; for (i=0;i<3;i++) for (j=0;j<3;j++) p[topD1+i]=p[topD1+i]-0.1*pas*inv_hessien.H[i][j]*gradl[j]; for (i=0;i<3;i++) if (fabs(p[topD1+i])<0.000001) /* C'est pour en finir avec les bug num�riques ... */ p[topD1+i]=0.0; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); /*if (isinf(p[topD1])||isinf(p[topD1+1])||isinf(p[topD1+2])) {printf("Y a un bug \n"); for (i=0;i<3;i++) for (j=0;j<3;j++) printf("hessien.H[%d][%d]=%f\n",i,j,hessien.H[i][j]); for (i=0;i<3;i++) printf("grad[%d]=%f\n",i,gradl[i]); }*/ if (Etmp>Emin) { for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; nuk=nuk*ck; Etmp=Emin; if (nuk>seuil_nuk) {continu=1;} tutu=0; nb_iter=0; } else{ /*if (TOP_verification_locale(nb_param,p,param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0) { for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=Emin; continu=1; res_inv=-1; } else*/ { nuk=1.0*nuk/ck1; tutu=2; nb_iter++; if (((1.0*fabs((Emin-Etmp)/Emin))<energie_precision)||(nb_iter>0)||(Emin==0)) {continu=1;Emin=Etmp;} } } if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } else { continu=1; } }while (continu==0); // V�rification de la conservation de la topologie pour les nouveaux param /* if ((TOP_verification_locale(nb_param,p,param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)||(res_inv==-1)) { // on fait une recherche lin�aire suivant la descente de gradient for (i=0;i<3;i++) p[topD1+i]=p_ini[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; gradient(imref,imreca,nb_param,p,param_norm,gradIref,gradl,topi,topj,topk,Slpqr); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; //printf("\n On fait de la descente de gradient !!!! %f \n",nuk); if((gradl[0]!=0)||(gradl[1]!=0)||(gradl[2]!=0)) Emin=TOP_linemin_locale_3d(imref,imreca,imres,champ_fin,the_transf,inter,dist,nb_param,p,param_norm,grad,topi,topj,topk,Jmin,Jmax,Slpqr); nb_tmp++; } */ if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) { for(i=0;i<nb_param;i++) opp_param_norm[i]=-1.0*lambda_ref*param_norm[i]; } if ((TOP_verification_locale(nb_param,p,param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)||(res_inv==-1) ||(TOP_verification_locale(nb_param,p,opp_param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)) { for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); Emin=HUGE_VAL;imin=0; continu=1; for (itmp=0;((itmp<nb_pas)&&(continu==1));itmp++) { for (i=0;i<3;i++) p[topD1+i]=p_ini[i]+1.0*itmp/nb_pas*(p_tmp[i]-p_ini[i]); for (i=0;i<3;i++) if (fabs(p[topD1+i])<0.000001) /* C'est pour en finir avec les bug num�riques ... */ p[topD1+i]=0.0; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) { for(i=0;i<3;i++) opp_param_norm[topD1+i]=-1.0*lambda_ref*param_norm[topD1+i]; } if ((TOP_verification_locale(nb_param,p,param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0) ||(TOP_verification_locale(nb_param,p,opp_param_norm,Jmin,Jmax,topi,topj,topk,Slpqr)==0)) continu=0; else if (Etmp<Emin) {Emin=Etmp;imin=itmp;} } for (i=0;i<3;i++) p[topD1+i]=p_ini[i]+1.0*imin/nb_pas*(p_tmp[i]-p_ini[i]); param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) { for(i=0;i<3;i++) opp_param_norm[topD1+i]=-1.0*lambda_ref*param_norm[topD1+i]; } if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } if (Emin==HUGE_VAL) {//printf("c'est un bug issu des pb numerique de topologie ...\n"); if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); for (i=0;i<3;i++) p[topD1+i]=p_ini[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Emin=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } E=E+Emin; //-------Evaluation du deplacement max------------ maxpx=1.0*fabs(p_i[topD1]-p[topD1]); maxpy=1.0*fabs(p_i[topD1+1]-p[topD1+1]); maxpz=1.0*fabs(p_i[topD1+2]-p[topD1+2]); if ((maxpx<precisx)&&(maxpy<precisy)&&(maxpz<precisz)) masque_bloc[topi][topj][topk]=0; else {/* on debloque les blocs voisins */ /*for (i=MAXI(topi-1,0);i<=MINI(topi+1,topD-1);i++) for (j=MAXI(topj-1,0);j<=MINI(topj+1,topD-1);j++) for (k=MAXI(topk-1,0);k<=MINI(topk+1,topD-1);k++) masque_bloc[i][j][k]=1;*/ if (maxpx>precisx) { if (topi>0) masque_bloc[topi-1][topj][topk]=1; if (topi<topD-1) masque_bloc[topi+1][topj][topk]=1; } if (maxpy>precisy) { if (topj>0) masque_bloc[topi][topj-1][topk]=1; if (topj<topD-1) masque_bloc[topi][topj+1][topk]=1; } if (maxpz>precisz) { if (topk>0) masque_bloc[topi][topj][topk-1]=1; if (topk<topD-1) masque_bloc[topi][topj][topk+1]=1; } } stop++; } } } for (i=0;i<nb_param;i++) p_i[i]=p[i]; printf("Minimisation sur %f %% des blocs Eprec : %f E : %f\n",300.0*stop/nb_param,Eprec,E); #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin iteration ..... "); #endif TOP_verification_all(nb_param,p,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif if (nomfichiertrf!=NULL) { #ifndef TOPO_COMPARE_CRITERE compare_critere(imref,imreca,imres,champ_fin,p,param_norm,nb_param,masque_param,nb); #endif } /* base_to_field_3d(nb_param,p,champ_fin,imref,imreca); inter_labeled_3d(imreca->mask,champ_fin,imres); save_mri_ipb_3d_p("test_anim",imres);*/ nb++; } while (nb<50 && Eprec!=E); //calcul de l'energie finale Efin=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); aff_log("nbiter: %d Efin: %.2f reduction: %.2f %% \n",nb,Efin,(Edebut-Efin)/Edebut*100.0); for (i=0;i<nb_param;i++) param[i]=p[i]; #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif #ifndef SAVE_INTERMEDIAIRE if (nomfichiertrf!=NULL) { //si l'extension .trf existe on la supprime strcpy(nomfichier,nomfichiertrf); ext=strstr(nomfichier,".trf"); if (ext!=NULL) *ext='\0'; strcat(nomfichier,"_"); temp[0]=(char)(resol+48); temp[1]=0; strcat(nomfichier,temp); save_transf_3d(transfo,nomfichier); } #endif //liberation memoire des variables //free_dvector(p,nb_param); free_dvector(p_i,nb_param); free_dvector(param_norm,nb_param); free_dvector(grad,nb_param); if ((dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) free_dvector(opp_param_norm,nb_param); //free_field3d(gradIref); free_imatrix_3d(masque_bloc); free_hessien3d(hessienIref); free_transf3d(transfo); if ((dist==Energie_ICP_sym_locale_3d)||(dist==Energie_quad_locale_symetrique_3d)||(dist==Energie_quad_locale_symetrique_coupe_3d)) {free_hessien3d(maskhessienIref); free_field3d(maskgradIref); } return(Efin); } /******************************************************************************* ** TOP_min_marquardt_penal_locale_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param) ** ** Minimisation par la m�thode de Levenberg-Marquardt ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retourne dans param *******************************************************************************/ double TOP_min_marquardt_penal_locale_3d (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin, transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist, reg_func_locale_t regularisation, int nb_param, double *param, int ***masque_param,double Jmin, double Jmax,char *nomfichiertrf) { int wdth,hght,dpth,i,j; field3d *gradIref,*maskgradIref=NULL; double *grad,*p,*p_i,gradl[3],*param_norm,p_ini[3],p_tmp[3]; double Edebut,Efin,E1,E2,E,Eprec,Emin,Etmp; int nb,nbreduc,stop,nb_iter,nb_tmp; double prreduc,maxpx,maxpy,maxpz,precis,precisx,precisy,precisz; int topi,topj,topk,topD,resol; int pari,parj,park; int compt,topD1; int ***masque_bloc; transf3d *transfo; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11; int (*gradient)(); reg_grad_locale_t gradient_reg; int (*func_hessien)(); reg_hessien_locale_t hessien_reg; hessien3d *hessienIref,*maskhessienIref=NULL; mat3d pseudo_hessien,hessien,inv_hessien; //double cfmax; double xm,xM,ym,yM,zm,zM; int res_inv,continu; double nuk,ck=100,ck1=10,seuil_nuk; int tutu; #ifndef SAVE_INTERMEDIAIRE char nomfichier[255]; char temp[2]; char *ext; #endif double energie_precision = 0.01; if (dist==Energie_IM_locale_3d) energie_precision=0.0001; /* les variations relatives de l'IM sont en g�n�ral bcp plus faibles */ wdth=imref->width;hght=imref->height;dpth=imref->depth; resol=BASE3D.resol; topD=(int)pow(2.0,1.0*resol)-1; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) gradient=gradient_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) gradient=gradient_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) gradient=gradient_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) gradient=gradient_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) gradient=gradient_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) gradient=gradient_base_ICP_sym_locale_3d; func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) func_hessien=hessien_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) func_hessien=hessien_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) func_hessien=hessien_base_geman_locale_3d; if (dist==Energie_IM_locale_3d) func_hessien=hessien_base_IM_locale_3d; if (dist==Energie_ICP_locale_3d) func_hessien=hessien_base_ICP_locale_3d; if (dist==Energie_ICP_sym_locale_3d) func_hessien=hessien_base_ICP_sym_locale_3d; gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) gradient_reg=gradient_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) gradient_reg=gradient_regularisation_log_jacobien_local; hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) hessien_reg=hessien_regularisation_energie_membrane_Lp_local; if (regularisation==regularisation_log_jacobien_local) hessien_reg=hessien_regularisation_energie_membrane_local; //allocation memoire des variables p=alloc_dvector(nb_param); p_i=alloc_dvector(nb_param); param_norm=alloc_dvector(nb_param); grad=alloc_dvector(nb_param); //gradIref=cr_field3d(wdth,hght,dpth); // pour economiser de la place memoire gradIref=champ_fin; masque_bloc=alloc_imatrix_3d(topD,topD,topD); hessienIref=cr_hessien3d(wdth,hght,dpth); if (dist==Energie_ICP_sym_locale_3d) {maskhessienIref=cr_hessien3d(wdth,hght,dpth); maskgradIref=cr_field3d(wdth,hght,dpth); } transfo=cr_transf3d(wdth,hght,dpth,NULL); transfo->nb_param=nb_param;transfo->param=CALLOC(nb_param,double); transfo->typetrans=BSPLINE3D; transfo->resol=BASE3D.resol;transfo->degre=1; // Valeur codee en dur car ca ne marche que pour les splines de degre 1 p = transfo->param; //Initialisation de masque_bloc for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) masque_bloc[topi][topj][topk]=1; for (i=0;i<nb_param;i++) p_i[i]=p[i]=param[i]; // initialisation des parametres normalises sur [0,1] for (i=0;i<nb_param/3;i++) { param_norm[3*i] =1.0*p[3*i] /wdth; param_norm[3*i+1]=1.0*p[3*i+1]/hght; param_norm[3*i+2]=1.0*p[3*i+2]/dpth; } //Mise a jour de Jm et JM dans les Slpqr for (i=0;i<8;i++) { Slpqr[i].Jm=Jmin; Slpqr[i].JM=Jmax; } //calcul de l'energie de depart Edebut=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); //Etmp=Energie_globale_sym_3d(imref,imreca,nb_param,p,param_norm,dist,masque_param); E2=Edebut; // calcul du gradient de l'image a recaler imx_gradient_3d_p(imreca,gradIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_gradient_3d_p(imreca->mask,maskgradIref,2,4); // calucl du Hessiend e l'image imx_hessien_3d_p(imreca,hessienIref,2,4); if (dist==Energie_ICP_sym_locale_3d) imx_hessien_3d_p(imreca->mask,maskhessienIref,2,4); aff_log("Edebut: %.2f nb_param: %d \n",Edebut,nb_param); nb=nbreduc=0;prreduc=0.1/100.0; stop=1; // --- On fixe la pr�cision � 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la pr�cision en recalage sym�trique soit �quivalent que celle obtenue en non symetrique precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); E=0; do { Eprec=E; E=0; E1=E2; compt=1; stop=0; nb_tmp=0; /*for (pari=0;pari<MINI(2,resol);pari++) for (parj=0;parj<MINI(2,resol);parj++) for (park=0;park<MINI(2,resol);park++)*/ for(pari=MINI(2,resol)-1;pari>=0;pari--) for(parj=MINI(2,resol)-1;parj>=0;parj--) for(park=MINI(2,resol)-1;park>=0;park--) { for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) if ((topi%2==pari)&&(topj%2==parj)&&(topk%2==park)) if ((masque_param[topi][topj][topk]!=0)&&(masque_bloc[topi][topj][topk]!=0)) { topD1=TOP_conv_ind(topi,topj,topk,nb_param); // printf("%d ieme bloc sur %d \r",topD1/3,nb_param/3); //--------------------------------------------------------------- //----- initialisation Slpqr ------------------------- //--------------------------------------------------------------- xm = 1.0*x00[topD1/3]/wdth; xM = 1.0*x11[topD1/3]/wdth; ym = 1.0*y00[topD1/3]/hght; yM = 1.0*y11[topD1/3]/hght; zm = 1.0*z00[topD1/3]/dpth; zM =1.0*z11[topD1/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; for (i=0;i<3;i++) p_ini[i]=p[topD1+i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); continu=0; nuk=0; ck=10; ck1=10; seuil_nuk=0; nb_iter=0; tutu=1; if (Etmp==0) continu=1; do{ Emin=Etmp; if (tutu>0) { // Calcul du gradient gradient(imref,imreca,nb_param,p,param_norm,gradIref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; func_hessien(imref, imreca, nb_param,p,param_norm,gradIref,maskgradIref,hessienIref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=hessien.H[i][j]; // Estimation de l'espace de recherche de nuk if ((nuk==0)&&(seuil_nuk==0)) { nuk=0.01*sqrt(hessien.H[0][0]*hessien.H[0][0]+hessien.H[1][1]*hessien.H[1][1]+hessien.H[2][2]*hessien.H[2][2]); seuil_nuk=100.0*sqrt(gradl[0]*gradl[0]+gradl[1]*gradl[1]+gradl[2]*gradl[2]); if ((seuil_nuk<100*nuk)||(nuk<0.0001)) { nuk=0.01;seuil_nuk=1000000; //on fixe des valeurs arbitraires } } } if((gradl[0]!=0)||(gradl[1]!=0)||(gradl[2]!=0)) { // Calcul du pseudo hessien Hk=H+nuk*I jusqu'a ce qu'il soit defini positif res_inv=0; while (res_inv==0) { for (i=0;i<3;i++) pseudo_hessien.H[i][i]=hessien.H[i][i]+nuk; res_inv=inversion_mat3d(&pseudo_hessien,&inv_hessien); if(res_inv==0) nuk=nuk*ck; } if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; for (i=0;i<3;i++) for (j=0;j<3;j++) p[topD1+i]=p[topD1+i]-inv_hessien.H[i][j]*gradl[j]; for (i=0;i<3;i++) if (fabs(p[topD1+i])<0.000001) /* C'est pour en finir avec les bug num�riques ... */ p[topD1+i]=0.0; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); /* borne_jacobien_bspline1_local_3d(nb_param,p,param_norm, topi, topj, topk, &minJ, &maxJ); if ((minJ<0)&&(Etmp<HUGE_VAL)) printf("violation de la topologie discrete\n");*/ /*if (Etmp==HUGE_VAL) { px=p[topD1]; py=p[topD1+1]; pz=p[topD1+2]; for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; p[topD1]=px; param_norm[topD1] =p[topD1] /wdth; Etmpx=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr); p[topD1]=p_tmp[0]; param_norm[topD1] =p[topD1] /wdth; p[topD1+1]=py; param_norm[topD1+1] =p[topD1+1] /hght; Etmpy=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr); p[topD1+1]=p_tmp[1]; param_norm[topD1+1] =p[topD1+1] /hght; p[topD1+2]=pz; param_norm[topD1+2] =p[topD1+2] /dpth; Etmpz=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr); p[topD1+2]=p_tmp[2]; param_norm[topD1+2] =p[topD1+2] /dpth; if ((Etmpx<Etmpy)&&(Etmpx<Etmpz)) {Etmp=Etmpx; p[topD1]=px; param_norm[topD1] =p[topD1] /wdth; } if ((Etmpy<Etmpx)&&(Etmpy<Etmpz)) {Etmp=Etmpy; p[topD1+1]=py; param_norm[topD1+1] =p[topD1+1] /hght; } if ((Etmpz<Etmpx)&&(Etmpz<Etmpy)) {Etmp=Etmpz; p[topD1+2]=pz; param_norm[topD1+2] =p[topD1+2] /dpth; } }*/ if (Etmp>Emin) { for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; nuk=nuk*ck; Etmp=Emin; if (nuk>seuil_nuk) {continu=1;} tutu=0; nb_iter=0; } else{ { nuk=1.0*nuk/ck1; tutu=2; nb_iter++; if (((1.0*(Emin-Etmp)/Emin)<energie_precision)||(nb_iter>10)||(Emin==0)) {continu=1;Emin=Etmp;} } } if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } else {continu=1;} }while (continu==0); if (Emin==HUGE_VAL) {for (i=0;i<3;i++) p[topD1+i]=p_ini[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; if (dist==Energie_IM_locale_3d) init_IM_locale_before_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); Emin=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (dist==Energie_IM_locale_3d) init_IM_locale_after_optimization_3d(imref, imreca, nb_param, p, topi, topj, topk); } E=E+Emin; //-------Evaluation du deplacement max------------ maxpx=1.0*fabs(p_i[topD1]-p[topD1]); maxpy=1.0*fabs(p_i[topD1+1]-p[topD1+1]); maxpz=1.0*fabs(p_i[topD1+2]-p[topD1+2]); if ((maxpx<precisx)&&(maxpy<precisy)&&(maxpz<precisz)) masque_bloc[topi][topj][topk]=0; else {/* on debloque les blocs voisins */ /*for (i=MAXI(topi-1,0);i<=MINI(topi+1,topD-1);i++) for (j=MAXI(topj-1,0);j<=MINI(topj+1,topD-1);j++) for (k=MAXI(topk-1,0);k<=MINI(topk+1,topD-1);k++) masque_bloc[i][j][k]=1;*/ if (maxpx>precisx) { if (topi>0) masque_bloc[topi-1][topj][topk]=1; if (topi<topD-1) masque_bloc[topi+1][topj][topk]=1; } if (maxpy>precisy) { if (topj>0) masque_bloc[topi][topj-1][topk]=1; if (topj<topD-1) masque_bloc[topi][topj+1][topk]=1; } if (maxpz>precisz) { if (topk>0) masque_bloc[topi][topj][topk-1]=1; if (topk<topD-1) masque_bloc[topi][topj][topk+1]=1; } } stop++; } } for (i=0;i<nb_param;i++) p_i[i]=p[i]; printf("Minimisation sur %f %% des blocs Eprec : %f E : %f\n",300.0*stop/nb_param,Eprec,E); // printf("Descente de gradient sur %f %% des blocs \n",100.0*nb_tmp/stop); #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin iteration ..... "); #endif TOP_verification_all(nb_param,p,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif if (nomfichiertrf!=NULL) { #ifndef TOPO_COMPARE_CRITERE compare_critere(imref,imreca,imres,champ_fin,p,param_norm,nb_param,masque_param,nb); #endif } /* base_to_field_3d(nb_param,p,champ_fin,imref,imreca); inter_labeled_3d(imreca->mask,champ_fin,imres); save_mri_ipb_3d_p("test_anim",imres);*/ nb++; } while (nb<50 && Eprec!=E); //calcul de l'energie finale Efin=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); aff_log("nbiter: %d Efin: %.2f reduction: %.2f %% \n",nb,Efin,(Edebut-Efin)/Edebut*100.0); for (i=0;i<nb_param;i++) param[i]=p[i]; #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif #ifndef SAVE_INTERMEDIAIRE if (nomfichiertrf!=NULL) { //si l'extension .trf existe on la supprime strcpy(nomfichier,nomfichiertrf); ext=strstr(nomfichier,".trf"); if (ext!=NULL) *ext='\0'; strcat(nomfichier,"_"); temp[0]=(char)(resol+48); temp[1]=0; strcat(nomfichier,temp); save_transf_3d(transfo,nomfichier); } #endif //liberation memoire des variables free_dvector(p,nb_param); free_dvector(p_i,nb_param); free_dvector(param_norm,nb_param); free_dvector(grad,nb_param); //free_field3d(gradIref); free_imatrix_3d(masque_bloc); free_hessien3d(hessienIref); if (dist==Energie_ICP_sym_locale_3d) { free_hessien3d(maskhessienIref); free_field3d(maskgradIref); } return(Efin); } /******************************************************************************* ** TOP_min_marquardt_penal_locale_gradient_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param) ** ** Minimisation par la m�thode de Levenberg-Marquardt ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retourne dans param *******************************************************************************/ double TOP_min_marquardt_penal_locale_gradient_3d (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin, transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist,reg_func_locale_t regularisation, int nb_param, double *param, int ***masque_param,double Jmin, double Jmax,char *nomfichiertrf) { int wdth,hght,dpth,i,j,k; field3d *gradIref,*gradIreca,*gradGxref,*gradGyref,*gradGzref,*maskgradIref=NULL; double *grad,*p,*p_i,gradl[3],*param_norm,p_ini[3],p_tmp[3]; double Edebut,Efin,E1,E2,E,Eprec,Emin,Etmp; int nb,nbreduc,stop,nb_iter,nb_tmp; double prreduc,maxpx,maxpy,maxpz,precis,precisx,precisy,precisz; int topi,topj,topk,topD,resol; int pari,parj,park; int compt,topD1; int ***masque_bloc; transf3d *transfo; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11; int (*gradient)(); reg_grad_locale_t gradient_reg; int (*func_hessien)(); reg_hessien_locale_t hessien_reg; hessien3d *hessienIref,*hessienGxref,*hessienGyref,*hessienGzref,*maskhessienIref=NULL; mat3d pseudo_hessien,hessien,inv_hessien; //double cfmax; double xm,xM,ym,yM,zm,zM; int res_inv,continu; double nuk,ck=100,ck1=10,seuil_nuk; int tutu; grphic3d *gxref,*gyref,*gzref,*gxreca,*gyreca,*gzreca; double alpha=0.5; #ifndef SAVE_INTERMEDIAIRE char nomfichier[255]; char temp[2]; char *ext; #endif wdth=imref->width;hght=imref->height;dpth=imref->depth; resol=BASE3D.resol; topD=(int)pow(2.0,1.0*resol)-1; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) gradient=gradient_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) gradient=gradient_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) gradient=gradient_base_geman_locale_3d; func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) func_hessien=hessien_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) func_hessien=hessien_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) func_hessien=hessien_base_geman_locale_3d; gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) gradient_reg=gradient_regularisation_energie_membrane_Lp_local; hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) hessien_reg=hessien_regularisation_energie_membrane_Lp_local; //allocation memoire des variables p=alloc_dvector(nb_param); p_i=alloc_dvector(nb_param); param_norm=alloc_dvector(nb_param); grad=alloc_dvector(nb_param); //gradIref=cr_field3d(wdth,hght,dpth); // pour economiser de la place memoire gradIref=champ_fin; gradIreca=cr_field3d(wdth,hght,dpth); gradGxref=cr_field3d(wdth,hght,dpth); gradGyref=cr_field3d(wdth,hght,dpth); gradGzref=cr_field3d(wdth,hght,dpth); masque_bloc=alloc_imatrix_3d(topD,topD,topD); hessienIref=cr_hessien3d(wdth,hght,dpth); hessienGxref=cr_hessien3d(wdth,hght,dpth); hessienGyref=cr_hessien3d(wdth,hght,dpth); hessienGzref=cr_hessien3d(wdth,hght,dpth); gxref=cr_grphic3d(imref); gyref=cr_grphic3d(imref); gzref=cr_grphic3d(imref); gxreca=cr_grphic3d(imreca); gyreca=cr_grphic3d(imreca); gzreca=cr_grphic3d(imreca); transfo=cr_transf3d(wdth,hght,dpth,NULL); transfo->nb_param=nb_param;transfo->param=CALLOC(nb_param,double); transfo->typetrans=BSPLINE3D; transfo->resol=BASE3D.resol;transfo->degre=1; // Valeur codee en dur car ca ne marche que pour les splines de degre 1 p = transfo->param; //Initialisation de masque_bloc for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) masque_bloc[topi][topj][topk]=1; for (i=0;i<nb_param;i++) p_i[i]=p[i]=param[i]; // initialisation des parametres normalises sur [0,1] for (i=0;i<nb_param/3;i++) { param_norm[3*i] =1.0*p[3*i] /wdth; param_norm[3*i+1]=1.0*p[3*i+1]/hght; param_norm[3*i+2]=1.0*p[3*i+2]/dpth; } //Mise a jour de Jm et JM dans les Slpqr for (i=0;i<8;i++) { Slpqr[i].Jm=Jmin; Slpqr[i].JM=Jmax; } // calcul du gradient de l'image a recaler imx_gradient_3d_p(imreca,gradIref,2,4); imx_gradient_3d_p(imref,gradIreca,2,4); for (i=0;i<wdth;i++) for (j=0;j<hght;j++) for (k=0;k<dpth;k++) { gxref->mri[i][j][k]=(int)gradIreca->raw[i][j][k].x; gyref->mri[i][j][k]=(int)gradIreca->raw[i][j][k].y; gzref->mri[i][j][k]=(int)gradIreca->raw[i][j][k].z; gxreca->mri[i][j][k]=(int)gradIref->raw[i][j][k].x; gyreca->mri[i][j][k]=(int)gradIref->raw[i][j][k].y; gzreca->mri[i][j][k]=(int)gradIref->raw[i][j][k].z; } imx_gradient_3d_p(gxreca,gradGxref,2,4); imx_gradient_3d_p(gyreca,gradGyref,2,4); imx_gradient_3d_p(gzreca,gradGzref,2,4); imx_hessien_3d_p(gxreca,hessienGxref,2,4); imx_hessien_3d_p(gyreca,hessienGyref,2,4); imx_hessien_3d_p(gzreca,hessienGzref,2,4); // calucl du Hessiend e l'image imx_hessien_3d_p(imreca,hessienIref,2,4); //calcul de l'energie de depart Edebut=(1.0-alpha)*Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); Edebut=Edebut+alpha*Energie_globale_3d(gxref,gxreca,nb_param,p,param_norm,dist,regularisation,masque_param)/3.0; Edebut=Edebut+alpha*Energie_globale_3d(gyref,gyreca,nb_param,p,param_norm,dist,regularisation,masque_param)/3.0; Edebut=Edebut+alpha*Energie_globale_3d(gzref,gzreca,nb_param,p,param_norm,dist,regularisation,masque_param)/3.0; E2=Edebut; aff_log("Edebut: %.2f nb_param: %d \n",Edebut,nb_param); nb=nbreduc=0;prreduc=0.1/100.0; stop=1; // --- On fixe la pr�cision � 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la pr�cision en recalage sym�trique soit �quivalent que celle obtenue en non symetrique precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); E=0; do { Eprec=E; E=0; E1=E2; compt=1; stop=0; nb_tmp=0; /*for (pari=0;pari<MINI(2,resol);pari++) for (parj=0;parj<MINI(2,resol);parj++) for (park=0;park<MINI(2,resol);park++)*/ for(pari=MINI(2,resol)-1;pari>=0;pari--) for(parj=MINI(2,resol)-1;parj>=0;parj--) for(park=MINI(2,resol)-1;park>=0;park--) { for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) if ((topi%2==pari)&&(topj%2==parj)&&(topk%2==park)) if ((masque_param[topi][topj][topk]!=0)&&(masque_bloc[topi][topj][topk]!=0)) { topD1=TOP_conv_ind(topi,topj,topk,nb_param); // printf("%d ieme bloc sur %d \r",topD1/3,nb_param/3); //--------------------------------------------------------------- //----- initialisation Slpqr ------------------------- //--------------------------------------------------------------- xm = 1.0*x00[topD1/3]/wdth; xM = 1.0*x11[topD1/3]/wdth; ym = 1.0*y00[topD1/3]/hght; yM = 1.0*y11[topD1/3]/hght; zm = 1.0*z00[topD1/3]/dpth; zM =1.0*z11[topD1/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; for (i=0;i<3;i++) p_ini[i]=p[topD1+i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=(1.0-alpha)*dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); Etmp=Etmp+alpha*dist(gxref,gxreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; Etmp=Etmp+alpha*dist(gyref,gyreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; Etmp=Etmp+alpha*dist(gzref,gzreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; continu=0; nuk=0; ck=10; ck1=10; seuil_nuk=0; nb_iter=0; tutu=1; if (Etmp==0) continu=1; do{ Emin=Etmp; if (tutu>0) { // Calcul du gradient gradient(imref,imreca,nb_param,p,param_norm,gradIref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=(1.0-alpha)*gradl[0];grad[topD1+1]=(1.0-alpha)*gradl[1];grad[topD1+2]=(1.0-alpha)*gradl[2]; gradient(gxref,gxreca,nb_param,p,param_norm,gradGxref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=grad[topD1]+alpha*gradl[0]/3.0;grad[topD1+1]=grad[topD1+1]+alpha*gradl[1]/3.0;grad[topD1+2]=grad[topD1+2]+alpha*gradl[2]/3.0; gradient(gyref,gyreca,nb_param,p,param_norm,gradGyref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=grad[topD1]+alpha*gradl[0]/3.0;grad[topD1+1]=grad[topD1+1]+alpha*gradl[1]/3.0;grad[topD1+2]=grad[topD1+2]+alpha*gradl[2]/3.0; gradient(gzref,gzreca,nb_param,p,param_norm,gradGzref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=grad[topD1]+alpha*gradl[0]/3.0;grad[topD1+1]=grad[topD1+1]+alpha*gradl[1]/3.0;grad[topD1+2]=grad[topD1+2]+alpha*gradl[2]/3.0; gradl[0]=grad[topD1];gradl[1]=grad[topD1+1];gradl[2]=grad[topD1+2]; func_hessien(imref, imreca, nb_param,p,param_norm,gradIref,maskgradIref,hessienIref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=(1.0-alpha)*hessien.H[i][j]; func_hessien(gxref, gxreca, nb_param,p,param_norm,gradGxref,maskgradIref,hessienGxref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=pseudo_hessien.H[i][j]+alpha*hessien.H[i][j]/3.0; func_hessien(gyref, gyreca, nb_param,p,param_norm,gradGyref,maskgradIref,hessienGyref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=pseudo_hessien.H[i][j]+alpha*hessien.H[i][j]/3.0; func_hessien(gzref, gzreca, nb_param,p,param_norm,gradGzref,maskgradIref,hessienGzref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=pseudo_hessien.H[i][j]+alpha*hessien.H[i][j]/3.0; for (i=0;i<3;i++) for (j=0;j<3;j++) hessien.H[i][j]=pseudo_hessien.H[i][j]; // Estimation de l'espace de recherche de nuk if ((nuk==0)&&(seuil_nuk==0)) { nuk=0.01*sqrt(hessien.H[0][0]*hessien.H[0][0]+hessien.H[1][1]*hessien.H[1][1]+hessien.H[2][2]*hessien.H[2][2]); seuil_nuk=100.0*sqrt(gradl[0]*gradl[0]+gradl[1]*gradl[1]+gradl[2]*gradl[2]); if ((seuil_nuk<100*nuk)||(nuk<0.0001)) { nuk=0.01;seuil_nuk=1000000; //on fixe des valeurs arbitraires } } } if((gradl[0]!=0)||(gradl[1]!=0)||(gradl[2]!=0)) { // Calcul du pseudo hessien Hk=H+nuk*I jusqu'a ce qu'il soit defini positif res_inv=0; while (res_inv==0) { for (i=0;i<3;i++) pseudo_hessien.H[i][i]=hessien.H[i][i]+nuk; res_inv=inversion_mat3d(&pseudo_hessien,&inv_hessien); if(res_inv==0) nuk=nuk*ck; } for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; for (i=0;i<3;i++) for (j=0;j<3;j++) p[topD1+i]=p[topD1+i]-inv_hessien.H[i][j]*gradl[j]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=(1.0-alpha)*dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); Etmp=Etmp+alpha*dist(gxref,gxreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; Etmp=Etmp+alpha*dist(gyref,gyreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; Etmp=Etmp+alpha*dist(gzref,gzreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; if (isnan(Etmp)) Etmp=HUGE_VAL; /* borne_jacobien_bspline1_local_3d(nb_param,p,param_norm, topi, topj, topk, &minJ, &maxJ); if ((minJ<0)&&(Etmp<HUGE_VAL)) printf("violation de la topologie discrete\n");*/ /*if (Etmp==HUGE_VAL) { px=p[topD1]; py=p[topD1+1]; pz=p[topD1+2]; for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; p[topD1]=px; param_norm[topD1] =p[topD1] /wdth; Etmpx=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr); p[topD1]=p_tmp[0]; param_norm[topD1] =p[topD1] /wdth; p[topD1+1]=py; param_norm[topD1+1] =p[topD1+1] /hght; Etmpy=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr); p[topD1+1]=p_tmp[1]; param_norm[topD1+1] =p[topD1+1] /hght; p[topD1+2]=pz; param_norm[topD1+2] =p[topD1+2] /dpth; Etmpz=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr); p[topD1+2]=p_tmp[2]; param_norm[topD1+2] =p[topD1+2] /dpth; if ((Etmpx<Etmpy)&&(Etmpx<Etmpz)) {Etmp=Etmpx; p[topD1]=px; param_norm[topD1] =p[topD1] /wdth; } if ((Etmpy<Etmpx)&&(Etmpy<Etmpz)) {Etmp=Etmpy; p[topD1+1]=py; param_norm[topD1+1] =p[topD1+1] /hght; } if ((Etmpz<Etmpx)&&(Etmpz<Etmpy)) {Etmp=Etmpz; p[topD1+2]=pz; param_norm[topD1+2] =p[topD1+2] /dpth; } }*/ if (Etmp>Emin) { for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; nuk=nuk*ck; Etmp=Emin; if (nuk>seuil_nuk) {continu=1;} tutu=0; nb_iter=0; } else{ { nuk=1.0*nuk/ck1; tutu=2; nb_iter++; if (((1.0*(Emin-Etmp)/Emin)<0.01)||(nb_iter>10)) {continu=1;Emin=Etmp;} } } } else {continu=1;} }while (continu==0); if (Emin==HUGE_VAL) {for (i=0;i<3;i++) p[topD1+i]=p_ini[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Emin=(1.0-alpha)*dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); Emin=Emin+alpha*dist(gxref,gxreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; Emin=Emin+alpha*dist(gyref,gyreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; Emin=Emin+alpha*dist(gzref,gzreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation)/3.0; } E=E+Emin; //-------Evaluation du deplacement max------------ maxpx=1.0*fabs(p_i[topD1]-p[topD1]); maxpy=1.0*fabs(p_i[topD1+1]-p[topD1+1]); maxpz=1.0*fabs(p_i[topD1+2]-p[topD1+2]); if ((maxpx<precisx)&&(maxpy<precisy)&&(maxpz<precisz)) masque_bloc[topi][topj][topk]=0; else {/* on debloque les blocs voisins */ /*for (i=MAXI(topi-1,0);i<=MINI(topi+1,topD-1);i++) for (j=MAXI(topj-1,0);j<=MINI(topj+1,topD-1);j++) for (k=MAXI(topk-1,0);k<=MINI(topk+1,topD-1);k++) masque_bloc[i][j][k]=1;*/ if (maxpx>precisx) { if (topi>0) masque_bloc[topi-1][topj][topk]=1; if (topi<topD-1) masque_bloc[topi+1][topj][topk]=1; } if (maxpy>precisy) { if (topj>0) masque_bloc[topi][topj-1][topk]=1; if (topj<topD-1) masque_bloc[topi][topj+1][topk]=1; } if (maxpz>precisz) { if (topk>0) masque_bloc[topi][topj][topk-1]=1; if (topk<topD-1) masque_bloc[topi][topj][topk+1]=1; } } stop++; } } for (i=0;i<nb_param;i++) p_i[i]=p[i]; printf("Minimisation sur %f %% des blocs Eprec : %f E : %f\n",300.0*stop/nb_param,Eprec,E); // printf("Descente de gradient sur %f %% des blocs \n",100.0*nb_tmp/stop); #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin iteration ..... "); #endif TOP_verification_all(nb_param,p,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif if (nomfichiertrf!=NULL) { #ifndef TOPO_COMPARE_CRITERE compare_critere(imref,imreca,imres,champ_fin,p,param_norm,nb_param,masque_param,nb); #endif } /* base_to_field_3d(nb_param,p,champ_fin,imref,imreca); inter_labeled_3d(imreca->mask,champ_fin,imres); save_mri_ipb_3d_p("test_anim",imres);*/ nb++; } while (nb<50 && Eprec!=E); //calcul de l'energie finale Efin=(1.0-alpha)*Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); Efin=Efin+alpha*Energie_globale_3d(gxref,gxreca,nb_param,p,param_norm,dist,regularisation,masque_param)/3.0; Efin=Efin+alpha*Energie_globale_3d(gyref,gyreca,nb_param,p,param_norm,dist,regularisation,masque_param)/3.0; Efin=Efin+alpha*Energie_globale_3d(gzref,gzreca,nb_param,p,param_norm,dist,regularisation,masque_param)/3.0; aff_log("nbiter: %d Efin: %.2f reduction: %.2f %% \n",nb,Efin,(Edebut-Efin)/Edebut*100.0); for (i=0;i<nb_param;i++) param[i]=p[i]; #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif #ifndef SAVE_INTERMEDIAIRE if (nomfichiertrf!=NULL) { //si l'extension .trf existe on la supprime strcpy(nomfichier,nomfichiertrf); ext=strstr(nomfichier,".trf"); if (ext!=NULL) *ext='\0'; strcat(nomfichier,"_"); temp[0]=(char)(resol+48); temp[1]=0; strcat(nomfichier,temp); save_transf_3d(transfo,nomfichier); } #endif //liberation memoire des variables free_dvector(p,nb_param); free_dvector(p_i,nb_param); free_dvector(param_norm,nb_param); free_dvector(grad,nb_param); //free_field3d(gradIref); free_field3d(gradIreca); free_field3d(gradGxref);free_field3d(gradGyref);free_field3d(gradGzref); free_imatrix_3d(masque_bloc); free_hessien3d(hessienIref); free_hessien3d(hessienGxref);free_hessien3d(hessienGyref);free_hessien3d(hessienGzref); free_grphic3d(gxref);free_grphic3d(gyref);free_grphic3d(gzref); free_grphic3d(gxreca);free_grphic3d(gyreca);free_grphic3d(gzreca); return(Efin); } /******************************************************************************* ** TOP_min_marquardt_adapt_penal_locale_3d(imref,imreca,imres,champ_ini,champ_fin,the_transf,inter ** ,dist,nb_param,min_param,max_param,prec_param,param) ** ** Minimisation par la m�thode de Levenberg-Marquardt ** ** utilisation: ** imref,imreca,imres: images ** champ_ini : champ initial ** NULL = pas de champ initial ** champ_fin : champ final resultat de la transfo ** the_transf : pointeur sur la fonction de transformation ** int the_transf(nb_param,param,champ) ** inter : pointeur sur la fonction d'interpolation ** int inter(imdeb,champ,imres) ** dist : pointeur sur la fonction de distance ** double dist(im1,im2) ** nb_param: nombre de parametre a minimiser ** min_param: bornes inferieures des parametres ** max_param: bornes superieures des parametres ** prec_param: precision demandee pour chaque parametre ** param: resultats donnant la valeur des parametres au ** point definissant le minimum ** la fonction retourne un double contenant la valeur du minimum ** Les parametres correspondant a ce minimum sont retourne dans param *******************************************************************************/ double TOP_min_marquardt_adapt_penal_locale_3d (grphic3d *imref, grphic3d *imreca, grphic3d *imres, field3d *champ_fin, transf_func_t the_transf, InterpolationFct inter, dist_func_locale_t dist,reg_func_locale_t regularisation, int nb_param, double *param, int ***masque_param,double Jmin, double Jmax,char *nomfichiertrf) { int wdth,hght,dpth,i,j; field3d *gradIref,*maskgradIref=NULL; double *grad,*p,*p_i,gradl[3],*param_norm,p_ini[3],p_tmp[3]; double Edebut,Efin,E1,E2,E,Eprec,Emin,Etmp; int nb,nbreduc,stop,nb_iter,nb_tmp; double prreduc,precis,precisx,precisy,precisz; int topi,topj,topk,topD,resol; int compt,topD1; int ***masque_bloc; double ***norme_gradient; transf3d *transfo; TSlpqr Slpqr[8]; int *x00,*x11,*y00,*y11,*z00,*z11; int (*gradient)(); reg_grad_locale_t gradient_reg; int (*func_hessien)(); reg_hessien_locale_t hessien_reg; hessien3d *hessienIref, *maskhessienIref=NULL; mat3d pseudo_hessien,hessien,inv_hessien; //double cfmax; double xm,xM,ym,yM,zm,zM; int res_inv,continu; double nuk,ck=10; int tutu/*,nbg=0*/; #ifndef SAVE_INTERMEDIAIRE char nomfichier[255]; char temp[2]; char *ext; #endif double max_gradient,seuil_gradient,min_gradient; int imax=0,jmax=0,kmax=0; wdth=imref->width;hght=imref->height;dpth=imref->depth; resol=BASE3D.resol; topD=(int)pow(2.0,1.0*resol)-1; x00=BASE3D.x0;x11=BASE3D.x1;y00=BASE3D.y0;y11=BASE3D.y1;z00=BASE3D.z0;z11=BASE3D.z1; gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) gradient=gradient_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) gradient=gradient_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) gradient=gradient_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) gradient=gradient_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) gradient=gradient_base_geman_locale_3d; func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_L1L2_locale_3d) func_hessien=hessien_base_L1L2_locale_3d; if (dist==Energie_L1L2_sym_locale_3d) func_hessien=hessien_base_L1L2_sym_locale_3d; if (dist==Energie_quad_topo_locale_3d) func_hessien=hessien_base_quad_locale_3d; if (dist==Energie_quad_sym_topo_locale_3d) func_hessien=hessien_base_quad_sym_locale_3d; if (dist==Energie_geman_locale_3d) func_hessien=hessien_base_geman_locale_3d; gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) gradient_reg=gradient_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) gradient_reg=gradient_regularisation_energie_membrane_Lp_local; hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_local) hessien_reg=hessien_regularisation_energie_membrane_local; if (regularisation==regularisation_energie_membrane_Lp_local) hessien_reg=hessien_regularisation_energie_membrane_Lp_local; //allocation memoire des variables p=alloc_dvector(nb_param); p_i=alloc_dvector(nb_param); param_norm=alloc_dvector(nb_param); grad=alloc_dvector(nb_param); //gradIref=cr_field3d(wdth,hght,dpth); // pour economiser de la place memoire gradIref=champ_fin; masque_bloc=alloc_imatrix_3d(topD,topD,topD); norme_gradient=alloc_dmatrix_3d(topD,topD,topD); hessienIref=cr_hessien3d(wdth,hght,dpth); transfo=cr_transf3d(wdth,hght,dpth,NULL); transfo->nb_param=nb_param;transfo->param=CALLOC(nb_param,double); transfo->typetrans=BSPLINE3D; transfo->resol=BASE3D.resol;transfo->degre=1; // Valeur codee en dur car ca ne marche que pour les splines de degre 1 p = transfo->param; //Initialisation de masque_bloc for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) masque_bloc[topi][topj][topk]=1; for (i=0;i<nb_param;i++) p_i[i]=p[i]=param[i]; // initialisation des parametres normalises sur [0,1] for (i=0;i<nb_param/3;i++) { param_norm[3*i] =1.0*p[3*i] /wdth; param_norm[3*i+1]=1.0*p[3*i+1]/hght; param_norm[3*i+2]=1.0*p[3*i+2]/dpth; } //Mise a jour de Jm et JM dans les Slpqr for (i=0;i<8;i++) { Slpqr[i].Jm=Jmin; Slpqr[i].JM=Jmax; } //calcul de l'energie de depart Edebut=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); E2=Edebut; // calcul du gradient de l'image a recaler imx_gradient_3d_p(imreca,gradIref,2,4); // calucl du Hessiend e l'image imx_hessien_3d_p(imreca,hessienIref,2,4); aff_log("Edebut: %.2f nb_param: %d \n",Edebut,nb_param); nb=nbreduc=0;prreduc=0.1/100.0; stop=1; // --- On fixe la pr�cision � 10% de la taille du support de spline precis=MAXI(TOPO_PONDERATION_RECALAGE_SYMETRIQUE,1.0); // pour que la pr�cision en recalage sym�trique soit �quivalent que celle obtenue en non symetrique precisx=CRITERE_ARRET_PARAM*precis*(x11[0]-x00[0]); precisy=CRITERE_ARRET_PARAM*precis*(y11[0]-y00[0]); precisz=CRITERE_ARRET_PARAM*precis*(z11[0]-z00[0]); /* calcul des normes de gradient */ for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) { topD1=TOP_conv_ind(topi,topj,topk,nb_param); xm = 1.0*x00[topD1/3]/wdth; xM = 1.0*x11[topD1/3]/wdth; ym = 1.0*y00[topD1/3]/hght; yM = 1.0*y11[topD1/3]/hght; zm = 1.0*z00[topD1/3]/dpth; zM =1.0*z11[topD1/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; gradient(imref,imreca,nb_param,p,param_norm,gradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; norme_gradient[topi][topj][topk]=sqrt(gradl[0]*gradl[0]+gradl[1]*gradl[1]+gradl[2]*gradl[2]); } max_gradient=0; /* recherche du gradient max */ for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) { if(norme_gradient[topi][topj][topk]>max_gradient) {max_gradient=norme_gradient[topi][topj][topk]; imax=topi;jmax=topj;kmax=topk; } } min_gradient=HUGE_VAL; /* recherche du gradient max */ for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) { if(norme_gradient[topi][topj][topk]<min_gradient) {min_gradient=norme_gradient[topi][topj][topk]; } } seuil_gradient=min_gradient+0.1*(max_gradient-min_gradient); /* seuillage du gradient */ for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) { if(norme_gradient[topi][topj][topk]<seuil_gradient) norme_gradient[topi][topj][topk]=0; } E=0; do { Eprec=E; E=0; E1=E2; compt=1; stop=0; nb_tmp=0; topi=imax;topj=jmax;topk=kmax; topD1=TOP_conv_ind(topi,topj,topk,nb_param); // printf("%d ieme bloc sur %d \r",topD1/3,nb_param/3); //--------------------------------------------------------------- //----- initialisation Slpqr ------------------------- //--------------------------------------------------------------- xm = 1.0*x00[topD1/3]/wdth; xM = 1.0*x11[topD1/3]/wdth; ym = 1.0*y00[topD1/3]/hght; yM = 1.0*y11[topD1/3]/hght; zm = 1.0*z00[topD1/3]/dpth; zM =1.0*z11[topD1/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; for (i=0;i<3;i++) p_ini[i]=p[topD1+i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); continu=0; nuk=10000; nb_iter=0; tutu=1; if (Etmp==0) continu=1; do{ Emin=Etmp; if (tutu>0) { // Calcul du gradient gradient(imref,imreca,nb_param,p,param_norm,gradIref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; func_hessien(imref, imreca, nb_param,p,param_norm,gradIref,maskgradIref,hessienIref,maskhessienIref,& hessien,topi,topj,topk,Slpqr,hessien_reg); for (i=0;i<3;i++) for (j=0;j<3;j++) pseudo_hessien.H[i][j]=hessien.H[i][j]; } // Calcul du pseudo hessien Hk=H+nuk*I jusqu'a ce qu'il soit defini positif res_inv=0; while (res_inv==0) { for (i=0;i<3;i++) pseudo_hessien.H[i][i]=hessien.H[i][i]+nuk; res_inv=inversion_mat3d(&pseudo_hessien,&inv_hessien); if(res_inv==0) nuk=nuk*ck; } for (i=0;i<3;i++) p_tmp[i]=p[topD1+i]; for (i=0;i<3;i++) for (j=0;j<3;j++) p[topD1+i]=p[topD1+i]-inv_hessien.H[i][j]*gradl[j]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Etmp=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); if (Etmp>Emin) { for (i=0;i<3;i++) p[topD1+i]=p_tmp[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; nuk=nuk*ck; Etmp=Emin; if (nuk>100000000) {continu=1;} tutu=0; nb_iter=0; } else{ { nuk=1.0*nuk/ck; tutu=2; nb_iter++; if (((1.0*(Emin-Etmp)/Emin)<0.01)||(nb_iter>10)) {continu=1;Emin=Etmp;} } } }while (continu==0); if (Emin==HUGE_VAL) {for (i=0;i<3;i++) p[topD1+i]=p_ini[i]; param_norm[topD1] =p[topD1] /wdth; param_norm[topD1+1]=p[topD1+1]/hght; param_norm[topD1+2]=p[topD1+2]/dpth; Emin=dist(imref,imreca,nb_param,p,param_norm,topi,topj,topk,Slpqr,regularisation); } E=E+Emin; /* mise a jour des normes de gradient */ for (topi=MAXI(imax-1,0); topi<MINI(imax+1,topD); topi++) for (topj=MAXI(jmax-1,0); topj<MINI(jmax+1,topD); topj++) for (topk=MAXI(kmax-1,0); topk<MINI(kmax+1,topD); topk++) { topD1=TOP_conv_ind(topi,topj,topk,nb_param); xm = 1.0*x00[topD1/3]/wdth; xM = 1.0*x11[topD1/3]/wdth; ym = 1.0*y00[topD1/3]/hght; yM = 1.0*y11[topD1/3]/hght; zm = 1.0*z00[topD1/3]/dpth; zM =1.0*z11[topD1/3]/dpth; Slpqr[0].b.xm = xm; Slpqr[0].b.xM = (xm+xM)/2; Slpqr[1].b.xm = xm; Slpqr[1].b.xM = (xm+xM)/2; Slpqr[2].b.xm = xm; Slpqr[2].b.xM = (xm+xM)/2; Slpqr[3].b.xm = xm; Slpqr[3].b.xM = (xm+xM)/2; Slpqr[4].b.xM = xM; Slpqr[4].b.xm = (xm+xM)/2; Slpqr[5].b.xM = xM; Slpqr[5].b.xm = (xm+xM)/2; Slpqr[6].b.xM = xM; Slpqr[6].b.xm = (xm+xM)/2; Slpqr[7].b.xM = xM; Slpqr[7].b.xm = (xm+xM)/2; Slpqr[0].b.ym = ym; Slpqr[0].b.yM = (ym+yM)/2; Slpqr[1].b.ym = ym; Slpqr[1].b.yM = (ym+yM)/2; Slpqr[4].b.ym = ym; Slpqr[4].b.yM = (ym+yM)/2; Slpqr[5].b.ym = ym; Slpqr[5].b.yM = (ym+yM)/2; Slpqr[2].b.yM = yM; Slpqr[2].b.ym = (ym+yM)/2; Slpqr[3].b.yM = yM; Slpqr[3].b.ym = (ym+yM)/2; Slpqr[6].b.yM = yM; Slpqr[6].b.ym = (ym+yM)/2; Slpqr[7].b.yM = yM; Slpqr[7].b.ym = (ym+yM)/2; Slpqr[0].b.zm = zm; Slpqr[0].b.zM = (zm+zM)/2; Slpqr[2].b.zm = zm; Slpqr[2].b.zM = (zm+zM)/2; Slpqr[4].b.zm = zm; Slpqr[4].b.zM = (zm+zM)/2; Slpqr[6].b.zm = zm; Slpqr[6].b.zM = (zm+zM)/2; Slpqr[1].b.zM = zM; Slpqr[1].b.zm = (zm+zM)/2; Slpqr[3].b.zM = zM; Slpqr[3].b.zm = (zm+zM)/2; Slpqr[5].b.zM = zM; Slpqr[5].b.zm = (zm+zM)/2; Slpqr[7].b.zM = zM; Slpqr[7].b.zm = (zm+zM)/2; gradient(imref,imreca,nb_param,p,param_norm,gradIref,maskgradIref,gradl,topi,topj,topk,Slpqr,gradient_reg); grad[topD1]=gradl[0];grad[topD1+1]=gradl[1];grad[topD1+2]=gradl[2]; norme_gradient[topi][topj][topk]=sqrt(gradl[0]*gradl[0]+gradl[1]*gradl[1]+gradl[2]*gradl[2]); if (norme_gradient[topi][topj][topk]<seuil_gradient) norme_gradient[topi][topj][topk]=0; if ((topi==imax)&&(topj==jmax)&&(topk==kmax)&&(norme_gradient[topi][topj][topk]==max_gradient)) {norme_gradient[topi][topj][topk]=0; /*nbg++;max_gradient=0;*/} } /*if (max_gradient>0) nbg=0; if (nbg<2) {*/ max_gradient=0; /* recherche du gradient max */ for (topi=0; topi<topD; topi++) for (topj=0; topj<topD; topj++) for (topk=0; topk<topD; topk++) { if(norme_gradient[topi][topj][topk]>max_gradient) {max_gradient=norme_gradient[topi][topj][topk]; imax=topi;jmax=topj;kmax=topk; } } //} } while ((max_gradient>0)/*&&(Eprec!=E)*/); //calcul de l'energie finale Efin=Energie_globale_3d(imref,imreca,nb_param,p,param_norm,dist,regularisation,masque_param); aff_log("nbiter: %d Efin: %.2f reduction: %.2f %% \n",nb,Efin,(Edebut-Efin)/Edebut*100.0); for (i=0;i<nb_param;i++) param[i]=p[i]; #ifndef TOPO_DEBUG { #ifndef TOPO_VERBOSE aff_log("Verif. fin resolution..... "); #endif TOP_verification_all(nb_param,param,masque_param,Jmin,Jmax); #ifndef TOPO_VERBOSE aff_log("finie \n"); #endif } #endif #ifndef SAVE_INTERMEDIAIRE if (nomfichiertrf!=NULL) { //si l'extension .trf existe on la supprime strcpy(nomfichier,nomfichiertrf); ext=strstr(nomfichier,".trf"); if (ext!=NULL) *ext='\0'; strcat(nomfichier,"_"); temp[0]=(char)(resol+48); temp[1]=0; strcat(nomfichier,temp); save_transf_3d(transfo,nomfichier); } #endif //liberation memoire des variables free_dvector(p,nb_param); free_dvector(p_i,nb_param); free_dvector(param_norm,nb_param); free_dvector(grad,nb_param); //free_field3d(gradIref); free_imatrix_3d(masque_bloc); free_dmatrix_3d(norme_gradient); free_hessien3d(hessienIref); return(Efin); }
c_print_results.c
/*****************************************************************/ /****** C _ P R I N T _ R E S U L T S ******/ /*****************************************************************/ #include <stdlib.h> #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif void c_print_results( char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int passed_verification, char *npbversion, char *compiletime, char *cc, char *clink, char *c_lib, char *c_inc, char *cflags, char *clinkflags ) { int num_threads, max_threads; max_threads = 1; num_threads = 1; /* figure out number of threads used */ #ifdef _OPENMP max_threads = omp_get_max_threads(); #pragma omp parallel shared(num_threads) { #pragma omp master num_threads = omp_get_num_threads(); } #endif printf( "\n\n %s Benchmark Completed\n", name ); printf( " Class = %c\n", class ); if( n3 == 0 ) { long nn = n1; if ( n2 != 0 ) nn *= n2; printf( " Size = %12ld\n", nn ); /* as in IS */ } else printf( " Size = %4dx%4dx%4d\n", n1,n2,n3 ); printf( " Iterations = %12d\n", niter ); printf( " Time in seconds = %12.2f\n", t ); printf( " Total threads = %12d\n", num_threads); printf( " Avail threads = %12d\n", max_threads); if (num_threads != max_threads) printf( " Warning: Threads used differ from threads available\n"); printf( " Mop/s total = %12.2f\n", mops ); printf( " Mop/s/thread = %12.2f\n", mops/(double)num_threads ); printf( " Operation type = %24s\n", optype); if( passed_verification < 0 ) printf( " Verification = NOT PERFORMED\n" ); else if( passed_verification ) printf( " Verification = SUCCESSFUL\n" ); else printf( " Verification = UNSUCCESSFUL\n" ); printf( " Version = %12s\n", npbversion ); printf( " Compile date = %12s\n", compiletime ); printf( "\n Compile options:\n" ); printf( " CC = %s\n", cc ); printf( " CLINK = %s\n", clink ); printf( " C_LIB = %s\n", c_lib ); printf( " C_INC = %s\n", c_inc ); printf( " CFLAGS = %s\n", cflags ); printf( " CLINKFLAGS = %s\n", clinkflags ); printf( "\n\n" ); printf( " Please send all errors/feedbacks to:\n\n" ); printf( " NPB Development Team\n" ); printf( " npb@nas.nasa.gov\n\n\n" ); /* printf( " Please send the results of this run to:\n\n" ); printf( " NPB Development Team\n" ); printf( " Internet: npb@nas.nasa.gov\n \n" ); printf( " If email is not available, send this to:\n\n" ); printf( " MS T27A-1\n" ); printf( " NASA Ames Research Center\n" ); printf( " Moffett Field, CA 94035-1000\n\n" ); printf( " Fax: 650-604-3957\n\n" ); */ }
multind.c
/* Copyright 2013-2015 The Regents of the University of California. * Copyright 2016-2017. Martin Uecker. * Copyright 2017. Intel Corporation. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2012-2017 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2013 Frank Ong <frankong@berkeley.edu> * 2017 Michael J. Anderson <michael.j.anderson@intel.com> * * Generic operations on multi-dimensional arrays. Most functions * come in two flavours: * * 1. A basic version which takes the number of dimensions, an array * of long integers specifing the size of each dimension, the pointers * to the data, and the size of each element and other required parameters. * The data is assumed to be stored in column-major format. * * 2. An extended version which takes an array of long integers which * specifies the strides for each argument. * * All functions should work on CPU and GPU and md_copy can be used * to copy between CPU and GPU. * */ #define _GNU_SOURCE #include <string.h> #include <assert.h> #include <stdbool.h> #include <alloca.h> #include <strings.h> #include "misc/misc.h" #include "misc/types.h" #include "misc/debug.h" #include "num/optimize.h" #ifdef USE_CUDA #include "num/gpuops.h" #endif #include "multind.h" /** * Generic functions which loops over all dimensions of a set of * multi-dimensional arrays and calls a given function for each position. */ void md_nary(unsigned int C, unsigned int D, const long dim[D], const long* str[C], void* ptr[C], void* data, md_nary_fun_t fun) { if (0 == D) { fun(data, ptr); return; } for (long i = 0; i < dim[D - 1]; i++) { void* moving_ptr[C]; for (unsigned int j = 0; j < C; j++) moving_ptr[j] = ptr[j] + i * str[j][D - 1]; md_nary(C, D - 1, dim, str, moving_ptr, data, fun); } } /** * Generic functions which loops over all dimensions of a set of * multi-dimensional arrays and calls a given function for each position. * This functions tries to parallelize over the dimensions indicated * with flags. */ void md_parallel_nary(unsigned int C, unsigned int D, const long dim[D], unsigned long flags, const long* str[C], void* ptr[C], void* data, md_nary_fun_t fun) { if (0 == flags) { md_nary(C, D, dim, str, ptr, data, fun); return; } long dimc[D]; md_select_dims(D, ~flags, dimc, dim); // Collect all parallel dimensions int nparallel = 0; int parallel_b[D]; long parallel_dim[D]; long total_iterations = 1L; while (0 != flags) { int b = ffsl(flags & -flags) - 1; assert(MD_IS_SET(flags, b)); flags = MD_CLEAR(flags, b); debug_printf(DP_DEBUG4, "Parallelize: %d\n", dim[b]); parallel_b[nparallel] = b; parallel_dim[nparallel] = dim[b]; total_iterations *= parallel_dim[nparallel]; nparallel++; } #pragma omp parallel for for (long i = 0; i < total_iterations; i++) { // Recover place in parallel iteration space long iter_i[D]; long ii = i; for (int p = nparallel - 1; p >= 0; p--) { iter_i[p] = ii % parallel_dim[p]; ii /= parallel_dim[p]; } void* moving_ptr[C]; for (unsigned int j = 0; j < C; j++) { moving_ptr[j] = ptr[j]; for(int p = 0; p < nparallel; p++) moving_ptr[j] += iter_i[p] * str[j][parallel_b[p]]; } md_nary(C, D, dimc, str, moving_ptr, data, fun); } } static void md_parallel_loop_r(unsigned int D, unsigned int N, const long dim[static N], unsigned int flags, const long pos[static N], void* data, md_loop_fun_t fun) { if (0 == D) { fun(data, pos); return; } D--; // we need to make a copy because firstprivate needs to see // an array instead of a pointer long pos_copy[N]; for (unsigned int i = 0; i < N; i++) pos_copy[i] = pos[i]; #pragma omp parallel for firstprivate(pos_copy) if ((1 < dim[D]) && (flags & (1 << D))) for (int i = 0; i < dim[D]; i++) { pos_copy[D] = i; md_parallel_loop_r(D, N, dim, flags, pos_copy, data, fun); } } /** * Generic function which loops over all dimensions and calls a given * function passing the current indices as argument. * * Runs fun(data, position) for all position in dim * */ void md_parallel_loop(unsigned int D, const long dim[static D], unsigned long flags, void* data, md_loop_fun_t fun) { long pos[D]; md_parallel_loop_r(D, D, dim, flags, pos, data, fun); } static void md_loop_r(unsigned int D, const long dim[D], long pos[D], void* data, md_loop_fun_t fun) { if (0 == D) { fun(data, pos); return; } D--; for (pos[D] = 0; pos[D] < dim[D]; pos[D]++) md_loop_r(D, dim, pos, data, fun); } /** * Generic function which loops over all dimensions and calls a given * function passing the current indices as argument. * * Runs fun( data, position ) for all position in dim * */ void md_loop(unsigned int D, const long dim[D], void* data, md_loop_fun_t fun) { long pos[D]; md_loop_r(D, dim, pos, data, fun); } /** * Computes the next position. Returns true until last index. */ bool md_next(unsigned int D, const long dims[D], unsigned long flags, long pos[D]) { if (0 == D--) return false; if (md_next(D, dims, flags, pos)) return true; if (MD_IS_SET(flags, D)) { assert((0 <= pos[D]) && (pos[D] < dims[D])); if (++pos[D] < dims[D]) return true; pos[D] = 0; } return false; } /** * Returns offset for position in a multidimensional array * * return pos[0]*strides[0] + ... + pos[D-1]*strides[D-1] * * @param D number of dimensions * @param dim dimensions array */ long md_calc_offset(unsigned int D, const long strides[D], const long position[D]) { long pos = 0; for (unsigned int i = 0; i < D; i++) pos += strides[i] * position[i]; return pos; } static long md_calc_size_r(unsigned int D, const long dim[D], size_t size) { if (0 == D) return size; return md_calc_size_r(D - 1, dim, size * dim[D - 1]); } /** * Returns the number of elements * * return dim[0]*dim[1]*...*dim[D-1] * * @param D number of dimensions * @param dim dimensions array */ long md_calc_size(unsigned int D, const long dim[D]) { return md_calc_size_r(D, dim, 1); } /** * Computes the number of smallest dimensions which are stored * contineously, i.e. can be accessed as a block of memory. * */ unsigned int md_calc_blockdim(unsigned int D, const long dim[D], const long str[D], size_t size) { long dist = size; unsigned int i = 0; for (i = 0; i < D; i++) { if (!((str[i] == dist) || (dim[i] == 1))) break; dist *= dim[i]; } return i; } /** * Copy dimensions specified by flags and set remaining dimensions to 1 * * odims = [ 1 idims[1] idims[2] 1 1 idims[5] ] * * @param D number of dimensions * @param flags bitmask specifying which dimensions to copy * @param odims output dimensions * @param idims input dimensions */ void md_select_dims(unsigned int D, unsigned long flags, long odims[D], const long idims[D]) { md_copy_dims(D, odims, idims); for (unsigned int i = 0; i < D; i++) if (!MD_IS_SET(flags, i)) odims[i] = 1; } /** * Copy dimensions * * odims[i] = idims[i] */ void md_copy_dims(unsigned int D, long odims[D], const long idims[D]) { memcpy(odims, idims, D * sizeof(long)); } /** * Copy strides * * ostrs[i] = istrs[i] */ void md_copy_strides(unsigned int D, long ostrs[D], const long istrs[D]) { memcpy(ostrs, istrs, D * sizeof(long)); } /** * Set all dimensions to value * * dims[i] = val */ void md_set_dims(unsigned int D, long dims[D], long val) { for (unsigned int i = 0; i < D; i++) dims[i] = val; } /** * returns whether or not @param pos is a valid index of an array of dimension @param dims */ bool md_is_index(unsigned int D, const long pos[D], const long dims[D]) { if (D == 0) return true; return ((pos[0] >= 0) && (pos[0] < dims[0]) && md_is_index(D - 1, pos + 1, dims + 1)); } /** * return whether some other dimensions are >1 */ bool md_check_dimensions(unsigned int N, const long dims[N], unsigned int flags) { long d[N]; md_select_dims(N, ~flags, d, dims); return (1 != md_calc_size(N, d)); } /* * compute non-trivial (> 1) dims */ unsigned long md_nontriv_dims(unsigned int D, const long dims[D]) { unsigned long flags = 0; for (unsigned int i = 0; i < D; i++) if (dims[i] > 1) flags = MD_SET(flags, i); return flags; } /** * Set all dimensions to one * * dims[i] = 1 */ void md_singleton_dims(unsigned int D, long dims[D]) { for (unsigned int i = 0; i < D; i++) dims[i] = 1; } /** * Set all strides to one * * dims[i] = 1 */ void md_singleton_strides(unsigned int D, long strs[D]) { for (unsigned int i = 0; i < D; i++) strs[i] = 0; } /** * Check dimensions for compatibility. Dimensions must be equal or * where indicated by a set bit in flags one must be equal to one * in atleast one of the arguments. */ bool md_check_compat(unsigned int D, unsigned long flags, const long dim1[D], const long dim2[D]) { if (0 == D) return true; D--; if ((dim1[D] == dim2[D]) || (MD_IS_SET(flags, D) && ((1 == dim1[D]) || (1 == dim2[D])))) return md_check_compat(D, flags, dim1, dim2); return false; } void md_merge_dims(unsigned int N, long out_dims[N], const long dims1[N], const long dims2[N]) { assert(md_check_compat(N, ~0, dims1, dims2)); for (unsigned int i = 0; i < N; i++) out_dims[i] = (1 == dims1[i]) ? dims2[i] : dims1[i]; } /** * dim1 must be bounded by dim2 where a bit is set */ bool md_check_bounds(unsigned int D, unsigned long flags, const long dim1[D], const long dim2[D]) { if (0 == D--) return true; if (!MD_IS_SET(flags, D) || (dim1[D] <= dim2[D])) return md_check_bounds(D, flags, dim1, dim2); return false; } /** * Set the output's flagged dimensions to the minimum of the two input dimensions * * odims = [ MIN(idims1[0],idims2[0] ... MIN(idims1[D-1],idims2[D-1]) ] * * @param D number of dimensions * @param flags bitmask specifying which dimensions to minimize * @param odims output dimensions * @param idims1 input 1 dimensions * @param idims2 input 2 dimensions */ void md_min_dims(unsigned int D, unsigned long flags, long odims[D], const long idims1[D], const long idims2[D]) { for (unsigned int i = 0; i < D; i++) if (MD_IS_SET(flags, i)) odims[i] = MIN(idims1[i], idims2[i]); } /** * Set the output's flagged dimensions to the maximum of the two input dimensions * * odims = [ MAX(idims1[0],idims2[0] ... MAX(idims1[D-1],idims2[D-1]) ] * * @param D number of dimensions * @param flags bitmask specifying which dimensions to maximize * @param odims output dimensions * @param idims1 input 1 dimensions * @param idims2 input 2 dimensions */ void md_max_dims(unsigned int D, unsigned long flags, long odims[D], const long idims1[D], const long idims2[D]) { for (unsigned int i = 0; i < D; i++) if (MD_IS_SET(flags, i)) odims[i] = MAX(idims1[i], idims2[i]); } struct data_s { size_t size; #ifdef USE_CUDA bool use_gpu; #endif }; static void nary_clear(struct nary_opt_data_s* opt_data, void* ptr[]) { struct data_s* data = opt_data->data_ptr; size_t size = data->size * opt_data->size; #ifdef USE_CUDA if (data->use_gpu) { cuda_clear(size, ptr[0]); return; } #endif memset(ptr[0], 0, size); } /** * Zero out array (with strides) * * ptr[i] = 0 */ void md_clear2(unsigned int D, const long dim[D], const long str[D], void* ptr, size_t size) { const long (*nstr[1])[D] = { (const long (*)[D])str }; #ifdef USE_CUDA struct data_s data = { size, cuda_ondevice(ptr) }; #else struct data_s data = { size }; #endif unsigned long flags = 0; for (unsigned int i = 0; i < D; i++) if (0 == str[i]) flags |= MD_BIT(i); long dim2[D]; md_select_dims(D, ~flags, dim2, dim); optimized_nop(1, MD_BIT(0), D, dim2, nstr, (void*[1]){ ptr }, (size_t[1]){ size }, nary_clear, &data); } /** * Calculate strides in column-major format * (smallest index is sequential) * * @param D number of dimensions * @param array of calculates strides * @param dim array of dimensions * @param size of a single element */ long* md_calc_strides(unsigned int D, long str[D], const long dim[D], size_t size) { long old = size; for (unsigned int i = 0; i < D; i++) { str[i] = (1 == dim[i]) ? 0 : old; old *= dim[i]; } return str; } /** * Zero out array (without strides) * * ptr[i] = 0 * * @param D number of dimensions * @param dim dimensions array * @param ptr pointer to data to clear * @param size sizeof() */ void md_clear(unsigned int D, const long dim[D], void* ptr, size_t size) { md_clear2(D, dim, MD_STRIDES(D, dim, size), ptr, size); } struct strided_copy_s { long sizes[2]; long ostr; long istr; }; #ifdef USE_CUDA static void nary_strided_copy(void* _data, void* ptr[]) { struct strided_copy_s* data = _data; // printf("CUDA 2D copy %ld %ld %ld %ld %ld %ld\n", data->sizes[0], data->sizes[1], data->ostr, data->istr, (long)ptr[0], (long)ptr[1]); cuda_memcpy_strided(data->sizes, data->ostr, ptr[0], data->istr, ptr[1]); } #endif static void nary_copy(struct nary_opt_data_s* opt_data, void* ptr[]) { struct data_s* data = opt_data->data_ptr; size_t size = data->size * opt_data->size; #ifdef USE_CUDA if (data->use_gpu) { cuda_memcpy(size, ptr[0], ptr[1]); return; } #endif memcpy(ptr[0], ptr[1], size); } /** * Copy array (with strides) * * optr[i] = iptr[i] */ void md_copy2(unsigned int D, const long dim[D], const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size) { #if 0 // this is for a fun comparison between our copy engine and FFTW extern void fft2(unsigned int D, const long dim[D], unsigned int flags, const long ostr[D], void* optr, const long istr[D], const void* iptr); if (sizeof(complex float) == size) fft2(D, dim, 0, ostr, optr, istr, iptr); #endif #ifndef USE_CUDA struct data_s data = { size }; #else struct data_s data = { size, cuda_ondevice(optr) || cuda_ondevice(iptr) }; #if 1 long tostr[D]; long tistr[D]; long tdims[D]; md_copy_strides(D, tostr, ostr); md_copy_strides(D, tistr, istr); md_copy_dims(D, tdims, dim); long (*nstr2[2])[D] = { &tostr, &tistr }; int ND = optimize_dims(2, D, tdims, nstr2); size_t sizes[2] = { size, size }; int skip = min_blockdim(2, ND, tdims, nstr2, sizes); if (data.use_gpu && (ND - skip == 1)) { // FIXME: the test was > 0 which would optimize transpose // but failes in the second cuda_memcpy_strided call // probably because of alignment restrictions const long* nstr[2] = { *nstr2[0] + skip, *nstr2[1] + skip }; void* nptr[2] = { optr, (void*)iptr }; long sizes[2] = { md_calc_size(skip, tdims) * size, tdims[skip] }; struct strided_copy_s data = { { sizes[0], sizes[1] } , (*nstr2[0])[skip], (*nstr2[1])[skip] }; skip++; md_nary(2, ND - skip, tdims + skip , nstr, nptr, &data, &nary_strided_copy); return; } #endif #endif const long (*nstr[2])[D] = { (const long (*)[D])ostr, (const long (*)[D])istr }; optimized_nop(2, MD_BIT(0), D, dim, nstr, (void*[2]){ optr, (void*)iptr }, (size_t[2]){ size, size }, nary_copy, &data); } /** * Copy array (without strides) * * optr[i] = iptr[i] */ void md_copy(unsigned int D, const long dim[D], void* optr, const void* iptr, size_t size) { long str[D]; md_calc_strides(D, str, dim, size); md_copy2(D, dim, str, optr, str, iptr, size); } #ifdef USE_CUDA // copied from flpmath.c static void* gpu_constant(const void* vp, size_t size) { return md_gpu_move(1, (long[1]){ 1 }, vp, size); } #endif /** * Fill array with value pointed by pointer (with strides) * * ptr[i] = iptr[0] */ void md_fill2(unsigned int D, const long dim[D], const long str[D], void* ptr, const void* iptr, size_t size) { #ifdef USE_CUDA if (cuda_ondevice(ptr) && (!cuda_ondevice(iptr))) { void* giptr = gpu_constant(iptr, size); md_fill2(D, dim, str, ptr, giptr, size); md_free(giptr); return; } #endif long istr[D]; md_singleton_strides(D, istr); md_copy2(D, dim, str, ptr, istr, iptr, size); } /** * Fill array with value pointed by pointer (without strides) * * ptr[i] = iptr[0] */ void md_fill(unsigned int D, const long dim[D], void* ptr, const void* iptr, size_t size) { md_fill2(D, dim, MD_STRIDES(D, dim, size), ptr, iptr, size); } struct swap_s { unsigned int M; size_t size; }; static void nary_swap(struct nary_opt_data_s* opt_data, void* ptr[]) { const struct swap_s* data = opt_data->data_ptr; size_t size = data->size * opt_data->size; unsigned int M = data->M; char* tmp = (size < 32) ? alloca(size) : xmalloc(size); #ifdef USE_CUDA assert(!cuda_ondevice(ptr[0])); assert(!cuda_ondevice(ptr[1])); #endif memcpy(tmp, ptr[0], size); for (unsigned int i = 0; i < M - 1; i++) memcpy(ptr[i], ptr[i + 1], size); memcpy(ptr[M - 1], tmp, size); if (size >= 32) xfree(tmp); } /** * Swap values between a number of arrays (with strides) */ void md_circular_swap2(unsigned int M, unsigned int D, const long dims[D], const long* strs[M], void* ptr[M], size_t size) { size_t sizes[M]; for (unsigned int i = 0; i < M; i++) sizes[i] = size; struct swap_s data = { M, size }; const long (*nstrs[M])[D]; for (unsigned int i = 0; i < M; i++) nstrs[i] = (const long (*)[D])strs[i]; optimized_nop(M, (1 << M) - 1, D, dims, nstrs, ptr, sizes, nary_swap, &data); } /** * Swap values between a number of arrays */ void md_circular_swap(unsigned M, unsigned int D, const long dims[D], void* ptr[M], size_t size) { long strs[M][D]; md_calc_strides(D, strs[0], dims, size); const long* strp[M]; strp[0] = strs[0]; for (unsigned int i = 1; i < M; i++) { md_copy_strides(D, strs[i], strs[0]); strp[i] = strs[i]; } md_circular_swap2(M, D, dims, strp, ptr, size); } /** * Swap values between two arrays (with strides) * * iptr[i] = optr[i] and optr[i] = iptr[i] */ void md_swap2(unsigned int D, const long dim[D], const long ostr[D], void* optr, const long istr[D], void* iptr, size_t size) { md_circular_swap2(2, D, dim, (const long*[2]){ ostr, istr }, (void*[2]){ optr, iptr }, size); } /** * Swap values between two arrays (without strides) * * iptr[i] = optr[i] and optr[i] = iptr[i] */ void md_swap(unsigned int D, const long dim[D], void* optr, void* iptr, size_t size) { long str[D]; md_calc_strides(D, str, dim, size); md_swap2(D, dim, str, optr, str, iptr, size); } /** * Move a block from an array to another array (with strides) * */ void md_move_block2(unsigned int D, const long dim[D], const long opos[D], const long odim[D], const long ostr[D], void* optr, const long ipos[D], const long idim[D], const long istr[D], const void* iptr, size_t size) { for (unsigned int i = 0; i < D; i++) { assert(dim[i] <= odim[i]); assert(dim[i] <= idim[i]); assert((0 <= opos[i]) && (opos[i] <= odim[i] - dim[i])); assert((0 <= ipos[i]) && (ipos[i] <= idim[i] - dim[i])); } long ioff = md_calc_offset(D, istr, ipos); long ooff = md_calc_offset(D, ostr, opos); md_copy2(D, dim, ostr, optr + ooff, istr, iptr + ioff, size); } /** * Move a block from an array to another array (without strides) * */ void md_move_block(unsigned int D, const long dim[D], const long opos[D], const long odim[D], void* optr, const long ipos[D], const long idim[D], const void* iptr, size_t size) { md_move_block2(D, dim, opos, odim, MD_STRIDES(D, odim, size), optr, ipos, idim, MD_STRIDES(D, idim, size), iptr, size); } /** * Copy a block from an array to another array (with strides) * * Block dimensions are min(idim , odim) * * if idim[d] > odim[d], then optr[i] = iptr[pos + i] for 0 <= i < odim[d] * * if idim[d] < odim[d], then optr[pos + i] = iptr[i] for 0 <= i < idim[d] * */ void md_copy_block2(unsigned int D, const long pos[D], const long odim[D], const long ostr[D], void* optr, const long idim[D], const long istr[D], const void* iptr, size_t size) { long dim[D]; long ipos[D]; long opos[D]; for (unsigned int i = 0; i < D; i++) { assert((idim[i] != odim[i]) || (0 == pos[i])); dim[i] = MIN(odim[i], idim[i]); ipos[i] = 0; opos[i] = 0; if (idim[i] != dim[i]) ipos[i] = pos[i]; if (odim[i] != dim[i]) opos[i] = pos[i]; } md_move_block2(D, dim, opos, odim, ostr, optr, ipos, idim, istr, iptr, size); } /** * Copy a block from an array to another array (without strides) * * Block dimensions are min(idim , odim) * * if idim[d] > odim[d], then optr[i] = iptr[pos + i] for 0 <= i < odim[d] * * if idim[d] < odim[d], then optr[pos + i] = iptr[i] for 0 <= i < idim[d] * */ void md_copy_block(unsigned int D, const long pos[D], const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size) { md_copy_block2(D, pos, odim, MD_STRIDES(D, odim, size), optr, idim, MD_STRIDES(D, idim, size), iptr, size); } /** * Resize an array by zero-padding or by truncation at the end. * * optr = [iptr 0 0 0 0] * */ void md_resize(unsigned int D, const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size) { long pos[D]; memset(pos, 0, D * sizeof(long)); md_clear(D, odim, optr, size); md_copy_block(D, pos, odim, optr, idim, iptr, size); } /** * Resize an array by zero-padding or by truncation at both ends symmetrically. * * optr = [0 0 iptr 0 0] * */ void md_resize_center(unsigned int D, const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size) { // the definition of the center position corresponds // to the one used in the FFT. long pos[D]; for (unsigned int i = 0; i < D; i++) pos[i] = labs((odim[i] / 2) - (idim[i] / 2)); md_clear(D, odim, optr, size); md_copy_block(D, pos, odim, optr, idim, iptr, size); } /** * Extract slice from array specified by flags (with strides) * * optr = iptr(pos[0], :, pos[2], :, :) * */ void md_slice2(unsigned int D, unsigned long flags, const long pos[D], const long dim[D], const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size) { long odim[D]; md_select_dims(D, ~flags, odim, dim); md_copy_block2(D, pos, odim, ostr, optr, dim, istr, iptr, size); } /** * Extract slice from array specified by flags (with strides) * * optr = iptr(pos[0], :, pos[2], :, :) * */ void md_slice(unsigned int D, unsigned long flags, const long pos[D], const long dim[D], void* optr, const void* iptr, size_t size) { long odim[D]; md_select_dims(D, ~flags, odim, dim); md_slice2(D, flags, pos, dim, MD_STRIDES(D, odim, size), optr, MD_STRIDES(D, dim, size), iptr, size); } /** * Permute array (with strides) * * optr[order[i]] = iptr[i] * */ void md_permute2(unsigned int D, const unsigned int order[D], const long odims[D], const long ostr[D], void* optr, const long idims[D], const long istr[D], const void* iptr, size_t size) { unsigned int flags = 0; long ostr2[D]; for (unsigned int i = 0; i < D; i++) { assert(order[i] < D); assert(odims[i] == idims[order[i]]); flags = MD_SET(flags, order[i]); ostr2[order[i]] = ostr[i]; } assert(MD_BIT(D) == flags + 1); md_copy2(D, idims, ostr2, optr, istr, iptr, size); } /** * Permute array (without strides) * * optr[order[i]] = iptr[i] * */ void md_permute(unsigned int D, const unsigned int order[D], const long odims[D], void* optr, const long idims[D], const void* iptr, size_t size) { md_permute2(D, order, odims, MD_STRIDES(D, odims, size), optr, idims, MD_STRIDES(D, idims, size), iptr, size); } /** * Permute dimensions * * */ void md_permute_dims(unsigned int D, const unsigned int order[D], long odims[D], const long idims[D]) { for (unsigned int i = 0; i < D; i++) odims[i] = idims[order[i]]; } static void md_transpose_order(unsigned int D, unsigned int order[D], unsigned int dim1, unsigned int dim2) { assert(dim1 < D); assert(dim2 < D); for (unsigned int i = 0; i < D; i++) order[i] = i; order[dim1] = dim2; order[dim2] = dim1; } /** * Transpose dimensions * * */ void md_transpose_dims(unsigned int D, unsigned int dim1, unsigned int dim2, long odims[D], const long idims[D]) { unsigned int order[D]; md_transpose_order(D, order, dim1, dim2); md_permute_dims(D, order, odims, idims); } /** * Tranpose array (with strides) * * optr[dim2] = iptr[dim1] * * optr[dim1] = iptr[dim2] * */ void md_transpose2(unsigned int D, unsigned int dim1, unsigned int dim2, const long odims[D], const long ostr[D], void* optr, const long idims[D], const long istr[D], const void* iptr, size_t size) { for (unsigned int i = 0; i < D; i++) if ((i != dim1) && (i != dim2)) assert(odims[i] == idims[i]); assert(odims[dim1] == idims[dim2]); assert(odims[dim2] == idims[dim1]); unsigned int order[D]; md_transpose_order(D, order, dim1, dim2); md_permute2(D, order, odims, ostr, optr, idims, istr, iptr, size); } /** * Tranpose array (without strides) * * optr[dim2] = iptr[dim1] * * optr[dim1] = iptr[dim2] * */ void md_transpose(unsigned int D, unsigned int dim1, unsigned int dim2, const long odims[D], void* optr, const long idims[D], const void* iptr, size_t size) { md_transpose2(D, dim1, dim2, odims, MD_STRIDES(D, odims, size), optr, idims, MD_STRIDES(D, idims, size), iptr, size); } static void md_flip_inpl2(unsigned int D, const long dims[D], unsigned long flags, const long str[D], void* ptr, size_t size); /** * Swap input and output while flipping selected dimensions * at the same time. */ void md_swap_flip2(unsigned int D, const long dims[D], unsigned long flags, const long ostr[D], void* optr, const long istr[D], void* iptr, size_t size) { #if 1 int i; for (i = D - 1; i >= 0; i--) if ((1 != dims[i]) && MD_IS_SET(flags, i)) break; if (-1 == i) { md_swap2(D, dims, ostr, optr, istr, iptr, size); return; } assert(1 < dims[i]); assert(ostr[i] != 0); assert(istr[i] != 0); long dims2[D]; md_copy_dims(D, dims2, dims); dims2[i] = dims[i] / 2; long off = (dims[i] + 1) / 2; assert(dims2[i] + off == dims[i]); md_swap_flip2(D, dims2, flags, ostr, optr, istr, iptr + off * istr[i], size); md_swap_flip2(D, dims2, flags, ostr, optr + off * ostr[i], istr, iptr, size); // odd, swap center plane // (we should split in three similar sized chunks instead) dims2[i] = 1; if (1 == dims[i] % 2) md_swap_flip2(D, dims2, flags, ostr, optr + (off - 1) * ostr[i], istr, iptr + (off - 1) * istr[i], size); #else // simpler, but more swaps md_swap2(D, dims, ostr, optr, istr, iptr, size); md_flip_inpl2(D, dims, flags, ostr, optr, size); md_flip_inpl2(D, dims, flags, istr, iptr, size); #endif } /** * Swap input and output while flipping selected dimensions * at the same time. */ void md_swap_flip(unsigned int D, const long dims[D], unsigned long flags, void* optr, void* iptr, size_t size) { long strs[D]; md_calc_strides(D, strs, dims, size); md_swap_flip2(D, dims, flags, strs, optr, strs, iptr, size); } static void md_flip_inpl2(unsigned int D, const long dims[D], unsigned long flags, const long str[D], void* ptr, size_t size) { int i; for (i = D - 1; i >= 0; i--) if ((1 != dims[i]) && MD_IS_SET(flags, i)) break; if (-1 == i) return; assert(1 < dims[i]); assert(str[i] != 0); long dims2[D]; md_copy_dims(D, dims2, dims); dims2[i] = dims[i] / 2; long off = str[i] * (0 + (dims[i] + 1) / 2); md_swap_flip2(D, dims2, flags, str, ptr, str, ptr + off, size); } /** * Flip array (with strides) * * optr[dims[D] - 1 - i] = iptr[i] * */ void md_flip2(unsigned int D, const long dims[D], unsigned long flags, const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size) { if (optr == iptr) { assert(ostr == istr); md_flip_inpl2(D, dims, flags, ostr, optr, size); return; } long off = 0; long ostr2[D]; for (unsigned int i = 0; i < D; i++) { ostr2[i] = ostr[i]; if (MD_IS_SET(flags, i)) { ostr2[i] = -ostr[i]; off += (dims[i] - 1) * ostr[i]; } } md_copy2(D, dims, ostr2, optr + off, istr, iptr, size); } /** * Flip array (without strides) * * optr[dims[D] - 1 - i] = iptr[i] * */ void md_flip(unsigned int D, const long dims[D], unsigned long flags, void* optr, const void* iptr, size_t size) { long str[D]; md_calc_strides(D, str, dims, size); md_flip2(D, dims, flags, str, optr, str, iptr, size); } struct compare_s { bool eq; size_t size; }; static void nary_cmp(struct nary_opt_data_s* opt_data, void* ptrs[]) { struct compare_s* data = opt_data->data_ptr; size_t size = data->size * opt_data->size; bool eq = (0 == memcmp(ptrs[0], ptrs[1], size)); #pragma omp critical data->eq &= eq; } bool md_compare2(unsigned int D, const long dims[D], const long str1[D], const void* src1, const long str2[D], const void* src2, size_t size) { struct compare_s data = { true, size }; const long (*nstr[2])[D] = { (const long (*)[D])str1, (const long (*)[D])str2 }; optimized_nop(2, 0u, D, dims, nstr, (void*[2]){ (void*)src1, (void*)src2 }, (size_t[2]){ size, size }, nary_cmp, &data); return data.eq; } bool md_compare(unsigned int D, const long dims[D], const void* src1, const void* src2, size_t size) { long str[D]; md_calc_strides(D, str, dims, size); return md_compare2(D, dims, str, src1, str, src2, size); } struct septrafo_s { long N; long str; void* data; md_trafo_fun_t fun; }; static void nary_septrafo(void* _data, void* ptr[]) { struct septrafo_s* data = (struct septrafo_s*)_data; data->fun(data->data, data->N, data->str, ptr[0]); } static void md_septrafo_r(unsigned int D, unsigned int R, long dimensions[D], unsigned long flags, const long strides[D], void* ptr, md_trafo_fun_t fun, void* _data) { if (0 == R--) return; md_septrafo_r(D, R, dimensions, flags, strides, ptr, fun, _data); if (MD_IS_SET(flags, R)) { struct septrafo_s data = { dimensions[R], strides[R], _data, fun }; void* nptr[1] = { ptr }; const long* nstrides[1] = { strides }; dimensions[R] = 1; // we made a copy in md_septrafo2 //md_nary_parallel(1, D, dimensions, nstrides, nptr, &data, nary_septrafo); md_nary(1, D, dimensions, nstrides, nptr, &data, nary_septrafo); dimensions[R] = data.N; } } /** * Apply a separable transformation along selected dimensions. * */ void md_septrafo2(unsigned int D, const long dimensions[D], unsigned long flags, const long strides[D], void* ptr, md_trafo_fun_t fun, void* _data) { long dimcopy[D]; md_copy_dims(D, dimcopy, dimensions); md_septrafo_r(D, D, dimcopy, flags, strides, ptr, fun, _data); } /** * Apply a separable transformation along selected dimensions. * */ void md_septrafo(unsigned int D, const long dims[D], unsigned long flags, void* ptr, size_t size, md_trafo_fun_t fun, void* _data) { md_septrafo2(D, dims, flags, MD_STRIDES(D, dims, size), ptr, fun, _data); } /** * Copy diagonals from array specified by flags (with strides) * * dst(i, i, :, i, :) = src(i, i, :, i, :) * */ void md_copy_diag2(unsigned int D, const long dims[D], unsigned long flags, const long str1[D], void* dst, const long str2[D], const void* src, size_t size) { long stride1 = 0; long stride2 = 0; long count = -1; for (unsigned int i = 0; i < D; i++) { if (MD_IS_SET(flags, i)) { if (count < 0) count = dims[i]; assert(dims[i] == count); stride1 += str1[i]; stride2 += str2[i]; } } long xdims[D]; md_select_dims(D, ~flags, xdims, dims); for (long i = 0; i < count; i++) md_copy2(D, xdims, str1, dst + i * stride1, str2, src + i * stride2, size); } /** * Copy diagonals from array specified by flags (without strides) * * dst(i ,i ,: ,i , :) = src(i ,i ,: ,i ,:) * */ void md_copy_diag(unsigned int D, const long dims[D], unsigned long flags, void* dst, const void* src, size_t size) { long str[D]; md_calc_strides(D, str, dims, size); md_copy_diag2(D, dims, flags, str, dst, str, src, size); } /** * Fill diagonals specified by flags with value (without strides) * * dst(i, i, :, i, :) = src[0] * */ void md_fill_diag(unsigned int D, const long dims[D], unsigned long flags, void* dst, const void* src, size_t size) { long str2[D]; md_singleton_strides(D, str2); md_copy_diag2(D, dims, flags, MD_STRIDES(D, dims, size), dst, str2, src, size); } static void md_circ_shift_inpl2(unsigned int D, const long dims[D], const long center[D], const long strs[D], void* dst, size_t size) { #if 0 long dims1[D]; long dims2[D]; md_copy_dims(D, dims1, dims); md_copy_dims(D, dims2, dims); unsigned int i; for (i = 0; i < D; i++) { if (0 != center[i]) { dims1[i] = center[i]; dims2[i] = dims[i] - center[i]; break; } } if (i == D) return; long off = strs[i] * center[i]; // cool but slow, instead we want to have a chain of swaps md_flip2(D, dims, MD_BIT(i), strs, dst, strs, dst, size); md_flip2(D, dims1, MD_BIT(i), strs, dst, strs, dst, size); md_flip2(D, dims2, MD_BIT(i), strs, dst + off, strs, dst + off, size); // also not efficient, we want to merge the chain of swaps long center2[D]; md_copy_dims(D, center2, center); center2[i] = 0; md_circ_shift_inpl2(D, dims, center2, strs, dst, size); #else // use tmp for now unsigned int i; for (i = 0; i < D; i++) if (0 != center[i]) break; if (i == D) return; long tmp_strs[D]; md_calc_strides(D, tmp_strs, dims, size); void* tmp = md_alloc_sameplace(D, dims, size, dst); md_copy2(D, dims, tmp_strs, tmp, strs, dst, size); md_circ_shift2(D, dims, center, strs, dst, tmp_strs, tmp, size); md_free(tmp); #endif } /** * Circularly shift array (with strides) * * dst[mod(i + center)] = src[i] * */ void md_circ_shift2(unsigned int D, const long dimensions[D], const long center[D], const long str1[D], void* dst, const long str2[D], const void* src, size_t size) { long pos[D]; for (unsigned int i = 0; i < D; i++) { // FIXME: it would be better to calc modulo pos[i] = center[i]; while (pos[i] < 0) pos[i] += dimensions[i]; } unsigned int i = 0; // FIXME :maybe we shoud search the other way? while ((i < D) && (0 == pos[i])) i++; if (D == i) { md_copy2(D, dimensions, str1, dst, str2, src, size); return; } if (dst == src) { assert(str1 == str2); md_circ_shift_inpl2(D, dimensions, pos, str1, dst, size); return; } long shift = pos[i]; assert(shift != 0); long dim1[D]; long dim2[D]; md_copy_dims(D, dim1, dimensions); md_copy_dims(D, dim2, dimensions); dim1[i] = shift; dim2[i] = dimensions[i] - shift; assert((dim1[i] >= 0) && (dim2[i] >= 0)); pos[i] = 0; //printf("%d: %ld %ld %d\n", i, dim1[i], dim2[i], sizeof(dimensions)); md_circ_shift2(D, dim1, pos, str1, dst, str2, src + dim2[i] * str2[i], size); md_circ_shift2(D, dim2, pos, str1, dst + dim1[i] * str1[i], str2, src, size); } /** * Circularly shift array (without strides) * * dst[mod(i + center)] = src[i] * */ void md_circ_shift(unsigned int D, const long dimensions[D], const long center[D], void* dst, const void* src, size_t size) { long strides[D]; md_calc_strides(D, strides, dimensions, size); md_circ_shift2(D, dimensions, center, strides, dst, strides, src, size); } /** * Circularly extend array (with strides) * */ void md_circ_ext2(unsigned int D, const long dims1[D], const long strs1[D], void* dst, const long dims2[D], const long strs2[D], const void* src, size_t size) { long ext[D]; for (unsigned int i = 0; i < D; i++) { ext[i] = dims1[i] - dims2[i]; assert(ext[i] >= 0); assert(ext[i] <= dims2[i]); } unsigned int i = 0; // FIXME :maybe we shoud search the other way? while ((i < D) && (0 == ext[i])) i++; if (D == i) { md_copy2(D, dims1, strs1, dst, strs2, src, size); return; } long dims1_crop[D]; long dims2_crop[D]; long ext_dims[D]; md_copy_dims(D, dims1_crop, dims1); md_copy_dims(D, dims2_crop, dims2); md_copy_dims(D, ext_dims, dims1); dims1_crop[i] = dims2[i]; dims2_crop[i] = ext[i]; ext_dims[i] = ext[i]; ext[i] = 0; //printf("%d: %ld %ld %d\n", i, dim1[i], dim2[i], sizeof(dimensions)); md_circ_ext2(D, dims1_crop, strs1, dst, dims2, strs2, src, size); md_circ_ext2(D, ext_dims, strs1, dst + dims2[i] * strs1[i], dims2_crop, strs2, src, size); } /** * Circularly extend array (without strides) * */ void md_circ_ext(unsigned int D, const long dims1[D], void* dst, const long dims2[D], const void* src, size_t size) { md_circ_ext2(D, dims1, MD_STRIDES(D, dims1, size), dst, dims2, MD_STRIDES(D, dims2, size), src, size); } /** * Periodically extend array (with strides) * */ void md_periodic2(unsigned int D, const long dims1[D], const long strs1[D], void* dst, const long dims2[D], const long strs2[D], const void* src, size_t size) { long dims1B[2 * D]; long strs1B[2 * D]; long strs2B[2 * D]; for (unsigned int i = 0; i < D; i++) { assert(0 == dims1[i] % dims2[i]); // blocks dims1B[2 * i + 0] = dims2[i]; strs1B[2 * i + 0] = strs1[i]; strs2B[2 * i + 0] = strs2[i]; // periodic copies dims1B[2 * i + 0] = dims1[i] / dims2[i]; strs1B[2 * i + 0] = strs1[i] * dims2[i]; strs2B[2 * i + 0] = 0; } md_copy2(D, dims1B, strs1B, dst, strs2B, src, size); } /** * Periodically extend array (without strides) * */ void md_periodic(unsigned int D, const long dims1[D], void* dst, const long dims2[D], const void* src, size_t size) { md_periodic2(D, dims1, MD_STRIDES(D, dims1, size), dst, dims2, MD_STRIDES(D, dims2, size), src, size); } /** * Allocate CPU memory * * return pointer to CPU memory */ void* md_alloc(unsigned int D, const long dimensions[D], size_t size) { return xmalloc(md_calc_size(D, dimensions) * size); } /** * Allocate CPU memory and clear * * return pointer to CPU memory */ void* md_calloc(unsigned int D, const long dimensions[D], size_t size) { void* ptr = md_alloc(D, dimensions, size); md_clear(D, dimensions, ptr, size); return ptr; } #ifdef USE_CUDA /** * Allocate GPU memory * * return pointer to GPU memory */ void* md_alloc_gpu(unsigned int D, const long dimensions[D], size_t size) { return cuda_malloc(md_calc_size(D, dimensions) * size); } /** * Allocate GPU memory and copy from CPU pointer * * return pointer to GPU memory */ void* md_gpu_move(unsigned int D, const long dims[D], const void* ptr, size_t size) { if (NULL == ptr) return NULL; void* gpu_ptr = md_alloc_gpu(D, dims, size); md_copy(D, dims, gpu_ptr, ptr, size); return gpu_ptr; } #endif /** * Allocate memory on the same device (CPU/GPU) place as ptr * * return pointer to CPU memory if ptr is in CPU or to GPU memory if ptr is in GPU */ void* md_alloc_sameplace(unsigned int D, const long dimensions[D], size_t size, const void* ptr) { #ifdef USE_CUDA return (cuda_ondevice(ptr) ? md_alloc_gpu : md_alloc)(D, dimensions, size); #else assert(0 != ptr); return md_alloc(D, dimensions, size); #endif } /** * Free CPU/GPU memory * */ void md_free(const void* ptr) { #ifdef USE_CUDA if (cuda_ondevice(ptr)) cuda_free((void*)ptr); else #endif xfree(ptr); }
parser.c
/***************************************************************************** * * Elmer, A Finite Element Software for Multiphysical Problems * * Copyright 1st April 1995 - , CSC - IT Center for Science Ltd., Finland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This 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 this library (in file ../LGPL-2.1); if not, write * to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ /******************************************************************************* * * MATC language/expression parser. * ******************************************************************************* * * Author: Juha Ruokolainen * * Address: CSC - IT Center for Science Ltd. * Keilaranta 14, P.O. BOX 405 * 02101 Espoo, Finland * Tel. +358 0 457 2723 * Telefax: +358 0 457 2302 * EMail: Juha.Ruokolainen@csc.fi * * Date: 30 May 1996 * * Modified by: * * Date of modification: * ******************************************************************************/ /*********************************************************************** | | PARSER.C - Last Edited 8. 8. 1988 | ***********************************************************************/ /*====================================================================== |Syntax of the manual pages: | |FUNCTION NAME(...) params ... | $ usage of the function and type of the parameters ? explane the effects of the function = return value and the type of value if not of type int @ globals effected directly by this routine ! current known bugs or limitations & functions called by this function ~ these functions may interest you as an alternative function or | because they control this function somehow ^=====================================================================*/ /* * $Id: parser.c,v 1.5 2006/11/22 10:57:14 jpr Exp $ * * $Log: parser.c,v $ * Revision 1.5 2006/11/22 10:57:14 jpr * *** empty log message *** * * Revision 1.4 2006/02/02 06:54:44 jpr * small formatting changes. * * Revision 1.2 2005/05/27 12:26:21 vierinen * changed header install location * * Revision 1.1.1.1 2005/04/14 13:29:14 vierinen * initial matc automake package * * Revision 1.2 1998/08/01 12:34:54 jpr * * Added Id, started Log. * * */ #include "elmer/matc.h" static SYMTYPE symbol, bendsym; static char *str, csymbol[4096], buf[4096]; #pragma omp threadprivate (symbol, bendsym, str, csymbol, buf) int char_in_list(int ch, char *list) { char *p; for(p = list; *p != '\0'; p++) if (*p == ch) return TRUE; return FALSE; } void scan() { char *p, ch; int i; symbol = nullsym; if ( *str == '\0' ) return; while( isspace(*str) ) str++; if (*str == '\0') return; p = str; if (isdigit(*str) || (*str == '.' && isdigit(*(str+1)))) { str++; while(isdigit(*str)) str++; if (*str == '.') { str++; if (isdigit(*str)) { while(isdigit(*str)) str++; } else if ( *str != '\0' && *str != 'e' && *str != 'E' && *str != 'd' && *str != 'D' ) { error("Badly formed number.\n"); } } if ( *str == 'd' || *str == 'D' ) *str = 'e'; if (*str == 'e' || *str=='E' ) { str++; if (isdigit(*str)) { while(isdigit(*str)) str++; } else if (char_in_list(*str,"+-")) { str++; if (isdigit(*str)) { while(isdigit(*str)) str++; } else { error("Badly formed number.\n"); } } else { error("Badly formed number.\n"); } } symbol = number; } else if (isalpha(*str) || char_in_list(*str, symchars)) { while(isalnum(*str) || char_in_list(*str, symchars)) str++; ch = *str; *str = '\0'; for(i = 0; reswords[i] != NULL; i++) if (strcmp(p, reswords[i]) == 0) { symbol = rsymbols[i]; break; } if (reswords[i] == NULL) symbol = name; *str = ch; } else if (*str == '"') { str++; while(*str != '"' && *str != '\0') { if (*str++ == '\\') str++; } if (*str == '\0') { error("String not terminated.\n"); } str++; symbol = string; } else if (char_in_list(*str, csymbols)) { for(i = 0; *str != csymbols[i]; i++); symbol = ssymbols[i]; str++; if (*str == '=') switch(symbol) { case assignsym: symbol = eq; str++; break; case lt: symbol = le; str++; break; case gt: symbol = ge; str++; break; case indclose: case rightpar: break; default: error("Syntax error.\n"); } if (*str == '>') if (symbol == lt) { symbol = neq; str++; } } else { error("Syntax error.\n"); } ch = *str; *str = '\0'; strcpy( csymbol, p ); *str = ch; return; } TREE *newtree() { return (TREE *)ALLOCMEM(sizeof(TREE)); } TREE *args(minp, maxp) int minp, maxp; { TREE *treeptr, *root; int numgot = 0; root = treeptr = equation(); numgot++; while(symbol == argsep) { scan(); NEXT(treeptr) = equation(); treeptr = NEXT(treeptr); numgot++; if (numgot > maxp) error("Too many parameters.\n"); } if (numgot < minp) error("Too few parameters.\n"); return root; } TREE *nameorvar() { TREE *root, *treeptr, *prevtree, *tp; SYMTYPE sym = nullsym; int i, slen; char *tstr; root = treeptr = prevtree = newtree(); if (symbol == minus && !isspace(*str) && (str-2<buf || isspace(*(str-2)) || char_in_list(*(str-2),"{};=[(\\<>&|+-*/^,"))) { sym = minus; scan(); } if (symbol != name && symbol != number && symbol != string && symbol != leftpar) { error("Expecting identifier, constant or leftpar.\n"); } while(symbol == name || symbol == number || symbol == string || symbol == leftpar) { switch(symbol) { case name: SDATA(treeptr) = STRCOPY(csymbol); ETYPE(treeptr) = ETYPE_NAME; if (*str == '(' || *str == '[') { scan(); scan(); ARGS(treeptr) = args(0, 10000); if (symbol != rightpar && symbol != indclose) { error("Expecting closing parenthesis.\n"); } } break; case string: tstr = csymbol + 1; tstr[strlen(tstr)-1] = '\0'; slen = strlen(tstr); for(i = 0; i < strlen(tstr); i++) if (tstr[i] == '\\') switch(tstr[++i]) { case 'n': break; default: slen--; break; } SDATA(treeptr) = (char *)ALLOCMEM(slen+1); for(i = 0; *tstr != '\0'; i++, tstr++) if (*tstr == '\\') switch(*++tstr) { case 'n': SDATA(treeptr)[i++] = '\r'; SDATA(treeptr)[i] = '\n'; break; case 't': SDATA(treeptr)[i] = '\t'; break; case 'v': SDATA(treeptr)[i] = '\v'; break; case 'b': SDATA(treeptr)[i] = '\b'; break; case 'r': SDATA(treeptr)[i] = '\r'; break; case 'f': SDATA(treeptr)[i] = '\f'; break; case 'e': SDATA(treeptr)[i] = 27; break; default: SDATA(treeptr)[i] = *tstr; break; } else SDATA(treeptr)[i] = *tstr; ETYPE(treeptr) = ETYPE_STRING; break; case number: DDATA(treeptr) = atof(csymbol); ETYPE(treeptr) = ETYPE_NUMBER; break; case leftpar: scan(); LEFT(treeptr) = equation(); if (symbol != rightpar) { error("Right paranthesis missing.\n"); } ETYPE(treeptr) = ETYPE_EQUAT; break; } if (*str == '[') { scan(); scan(); SUBS(treeptr) = args(1,2); if (symbol != rightpar && symbol != indclose) { error("Expecting closing parenthesis.\n"); } } if (sym == minus) { tp = newtree(); VDATA(tp) = opr_minus; ETYPE(tp) = ETYPE_OPER; LEFT(tp) = treeptr; if (root == treeptr) root = treeptr = tp; else LINK(prevtree) = treeptr = tp; } sym = symbol; scan(); if (symbol == minus && !isspace(*str) && (str-2<buf || isspace(*(str-2)) || char_in_list(*(str-2),"{};=([\\<>&|+-*/^,"))) { sym = minus; if (*str == '-' && !isspace(*(str + 1))) { break; } else if (*str == '-') error("Syntax error.\n"); scan(); if (symbol != name && symbol != number && symbol != string && symbol != leftpar) { error("Expecting identifier, constant or leftpar.\n"); } } if (symbol == name || symbol == number || symbol == string || symbol == leftpar) { prevtree = treeptr; LINK(treeptr) = newtree(); treeptr = LINK(treeptr); } } return root; } TREE *par_apply(root) TREE *root; { TREE *newroot; newroot = newtree(); switch(symbol) { case apply: VDATA(newroot) = opr_apply; break; case not: VDATA(newroot) = opr_not; break; } ETYPE(newroot) = ETYPE_OPER; scan(); if (symbol == apply || symbol == not) LEFT(newroot) = par_apply(newroot); else LEFT(newroot) = nameorvar(); return newroot; } TREE *par_trans(root) TREE *root; { TREE *newroot; while(symbol == transpose) { newroot = newtree(); LEFT(newroot) = root; VDATA(newroot) = opr_trans; ETYPE(newroot) = ETYPE_OPER; root = newroot; scan(); } return newroot; } TREE *par_pow(root) TREE *root; { TREE *newroot; while(symbol == power) { newroot = newtree(); LEFT(newroot) = root; VDATA(newroot) = opr_pow; ETYPE(newroot) = ETYPE_OPER; root = newroot; scan(); RIGHT(newroot) = nameorvar(); switch(symbol) { case transpose: RIGHT(newroot) = par_trans(RIGHT(newroot)); break; case apply: case not: RIGHT(newroot) = par_apply(RIGHT(newroot)); break; } } return newroot; } TREE *par_timesdivide(root) TREE *root; { TREE *newroot; while(symbol == times || symbol == ptimes || symbol == divide) { newroot = newtree(); LEFT(newroot) = root; switch(symbol) { case times: VDATA(newroot) = opr_mul; break; case ptimes: VDATA(newroot) = opr_pmul; break; case divide: VDATA(newroot) = opr_div; break; } ETYPE(newroot) = ETYPE_OPER; root = newroot; scan(); RIGHT(newroot) = nameorvar(); switch(symbol) { case power: RIGHT(newroot) = par_pow(RIGHT(newroot)); break; case transpose: RIGHT(newroot) = par_trans(RIGHT(newroot)); break; case apply: case not: RIGHT(newroot) = par_apply(RIGHT(newroot)); break; } } return newroot; } TREE *par_plusminus(root) TREE *root; { TREE *newroot; while(symbol == plus || symbol == minus) { newroot = newtree(); LEFT(newroot) = root; switch(symbol) { case plus: VDATA(newroot) = opr_add; break; case minus: VDATA(newroot) = opr_subs; break; } ETYPE(newroot) = ETYPE_OPER; root = newroot; scan(); RIGHT(newroot) = nameorvar(); switch(symbol) { case times: case ptimes: case divide: RIGHT(newroot) = par_timesdivide(RIGHT(newroot)); break; case power: RIGHT(newroot) = par_pow(RIGHT(newroot)); break; case transpose: RIGHT(newroot) = par_trans(RIGHT(newroot)); break; case apply: case not: RIGHT(newroot) = par_apply(RIGHT(newroot)); break; } } return newroot; } TREE *par_compare(root) TREE *root; { TREE *newroot; while(symbol == eq || symbol == neq || symbol == lt || symbol == gt || symbol == le || symbol == ge) { newroot = newtree(); LEFT(newroot) = root; switch(symbol) { case eq: VDATA(newroot) = opr_eq; break; case lt: VDATA(newroot) = opr_lt; break; case gt: VDATA(newroot) = opr_gt; break; case neq: VDATA(newroot) = opr_neq; break; case le: VDATA(newroot) = opr_le; break; case ge: VDATA(newroot) = opr_ge; break; } ETYPE(newroot) = ETYPE_OPER; root = newroot; scan(); RIGHT(newroot) = nameorvar(); switch(symbol) { case plus: case minus: RIGHT(newroot) = par_plusminus(RIGHT(newroot)); break; case times: case ptimes: case divide: RIGHT(newroot) = par_timesdivide(RIGHT(newroot)); break; case power: RIGHT(newroot) = par_pow(RIGHT(newroot)); break; case transpose: RIGHT(newroot) = par_trans(RIGHT(newroot)); break; case apply: case not: RIGHT(newroot) = par_apply(RIGHT(newroot)); break; } } return newroot; } TREE *par_vector(root) TREE *root; { TREE *newroot; while(symbol == vector) { newroot = newtree(); LEFT(newroot) = root; VDATA(newroot) = opr_vector; ETYPE(newroot) = ETYPE_OPER; root = newroot; scan(); RIGHT(newroot) = nameorvar(); switch(symbol) { case eq: case neq: case lt: case gt: case le: case ge: RIGHT(newroot) = par_compare(RIGHT(newroot)); break; case plus: case minus: RIGHT(newroot) = par_plusminus(RIGHT(newroot)); break; case times: case ptimes: case divide: RIGHT(newroot) = par_timesdivide(RIGHT(newroot)); break; case power: RIGHT(newroot) = par_pow(RIGHT(newroot)); break; case transpose: RIGHT(newroot) = par_trans(RIGHT(newroot)); break; case apply: case not: RIGHT(newroot) = par_apply(RIGHT(newroot)); break; } } return newroot; } TREE *par_logical(root) TREE *root; { TREE *newroot; while(symbol == and || symbol == or) { newroot = newtree(); LEFT(newroot) = root; switch(symbol) { case and: VDATA(newroot) = opr_and; break; case or: VDATA(newroot) = opr_or; break; } ETYPE(newroot) = ETYPE_OPER; root = newroot; scan(); RIGHT(newroot) = nameorvar(); switch(symbol) { case vector: RIGHT(newroot) = par_vector(RIGHT(newroot)); break; case eq: case neq: case lt: case gt: case le: case ge: RIGHT(newroot) = par_compare(RIGHT(newroot)); break; case plus: case minus: RIGHT(newroot) = par_plusminus(RIGHT(newroot)); break; case times: case ptimes: case divide: RIGHT(newroot) = par_timesdivide(RIGHT(newroot)); break; case power: RIGHT(newroot) = par_pow(RIGHT(newroot)); break; case transpose: RIGHT(newroot) = par_trans(RIGHT(newroot)); break; case apply: case not: RIGHT(newroot) = par_apply(RIGHT(newroot)); break; } } return newroot; } TREE *par_reduction(root) TREE *root; { TREE *newroot; while(symbol == reduction) { newroot = newtree(); VDATA(newroot) = opr_reduction; ETYPE(newroot) = ETYPE_OPER; scan(); RIGHT(newroot) = nameorvar(); LEFT(newroot) = root; root = newroot; switch(symbol) { case and: case or: RIGHT(newroot) = par_logical(RIGHT(newroot)); break; case vector: RIGHT(newroot) = par_vector(RIGHT(newroot)); break; case eq: case neq: case lt: case gt: case le: case ge: RIGHT(newroot) = par_compare(RIGHT(newroot)); break; case plus: case minus: RIGHT(newroot) = par_plusminus(RIGHT(newroot)); break; case times: case ptimes: case divide: RIGHT(newroot) = par_timesdivide(RIGHT(newroot)); break; case power: RIGHT(newroot) = par_pow(RIGHT(newroot)); break; case transpose: RIGHT(newroot) = par_trans(RIGHT(newroot)); break; case apply: case not: RIGHT(newroot) = par_apply(RIGHT(newroot)); break; } } return newroot; } TREE *par_resize(root) TREE *root; { TREE *newroot; while(symbol == resize) { newroot = newtree(); VDATA(newroot) = opr_resize; ETYPE(newroot) = ETYPE_OPER; scan(); LEFT(newroot) = nameorvar(); RIGHT(newroot) = root; root = newroot; switch(symbol) { case reduction: LEFT(newroot) = par_reduction(LEFT(newroot)); break; case and: case or: LEFT(newroot) = par_logical(LEFT(newroot)); break; case vector: LEFT(newroot) = par_vector(LEFT(newroot)); break; case eq: case neq: case lt: case gt: case le: case ge: LEFT(newroot) = par_compare(LEFT(newroot)); break; case plus: case minus: LEFT(newroot) = par_plusminus(LEFT(newroot)); break; case times: case ptimes: case divide: LEFT(newroot) = par_timesdivide(LEFT(newroot)); break; case power: LEFT(newroot) = par_pow(LEFT(newroot)); break; case transpose: LEFT(newroot) = par_trans(LEFT(newroot)); break; case apply: case not: LEFT(newroot) = par_apply(LEFT(newroot)); break; } } return newroot; } TREE *equation() { TREE *treeptr; switch(symbol) { case apply: case not: break; default: treeptr = nameorvar(); break; } while(TRUE) { switch(symbol) { case resize: treeptr = par_resize(treeptr); break; case reduction: treeptr = par_reduction(treeptr); break; case and: case or: treeptr = par_logical(treeptr); break; case vector: treeptr = par_vector(treeptr); break; case eq: case neq: case lt: case gt: case le: case ge: treeptr = par_compare(treeptr); break; case plus: case minus: treeptr = par_plusminus(treeptr); break; case times: case ptimes: case divide: treeptr = par_timesdivide(treeptr); break; case power: treeptr = par_pow(treeptr); break; case transpose: treeptr = par_trans(treeptr); break; case apply: case not: treeptr = par_apply(treeptr); break; default: return treeptr; } } } CLAUSE *commentparse() { char *p = str; CLAUSE *root = NULL; while( *str!='\n' && *str!='\0' ) str++; scan(); return root; } CLAUSE *scallparse() { char *p = str; CLAUSE *root = NULL; while( *str!='\n' && *str != ';' && *str!='\0' ) str++; if ( *str ) *str++ = '\0'; if ( *p ) { root = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); root->data = systemcall; root->this = newtree(); SDATA(root->this) = STRCOPY( p ); ETYPE(root->this) = ETYPE_STRING; } scan(); return root; } CLAUSE *statement() { char *csymbcopy, *p; CLAUSE *root = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); if (symbol == name) { p = str; csymbcopy = STRCOPY(csymbol); do { scan(); } while( symbol != assignsym && symbol != nullsym && symbol != statemend ); strcpy(csymbol, csymbcopy); FREEMEM(csymbcopy); str = p; if (symbol == assignsym) { symbol = name; root -> this = nameorvar(); scan(); } else symbol = name; } LINK(root) = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); LINK(root) -> this = equation(); root->data = assignsym; return root; } CLAUSE *blockparse() { CLAUSE *root, *ptr; root = (CLAUSE *)NULL; if (symbol != beginsym) error("if|while|function: missing block open symbol.\n"); scan(); if (symbol == nullsym) { dogets(str, PMODE_BLOCK); scan(); } if (symbol != endsym) { root = ptr = parse(); while(LINK(ptr) != NULL) { ptr = LINK(ptr); } } while(symbol != endsym && symbol != elsesym) { if (symbol == nullsym) { dogets(str, PMODE_BLOCK); scan(); } if (symbol != endsym && symbol != elsesym) { LINK(ptr) = parse(); while(LINK(ptr) != NULL) { ptr = LINK(ptr); } } } bendsym = symbol; scan(); return root; } CLAUSE *funcparse() { CLAUSE *root, *ptr; SYMTYPE sym; TREE *lptr, *rptr,*help; int ch,n; char *p = str; root = ptr = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); ptr->data = funcsym; scan(); ptr->this = nameorvar(); help = SUBS(root->this) = newtree(); SDATA( help ) = STRCOPY( p ); p = str; while ( symbol == nullsym || symbol == comment ) { dogets( str, PMODE_CONT ); scan(); if ( symbol == comment ) { NEXT(help) = newtree(); help = NEXT(help); while( *str != '\n' && *str != '\0' ) str++; ch = *str; if ( *str ) *++str = '\0'; *str = ch; SDATA(help) = STRCOPY( p ); p = str; } } while(symbol == import || symbol == export) { if (symbol == import) lptr = LEFT(root->this); else lptr = RIGHT(root->this); sym = symbol; scan(); rptr = args(1,1000); if (lptr == NULL) { if (sym == import) LEFT(root->this) = rptr; else RIGHT(root->this) = rptr; } else { while(NEXT(lptr)) lptr=NEXT(lptr); NEXT(lptr) = rptr; } if (symbol == nullsym) { dogets(str, PMODE_CONT); scan(); } } if (symbol == beginsym) { LINK(ptr) = blockparse(); if (bendsym != endsym) error("function: missing end.\n"); } else LINK(ptr) = parse(); return root; } CLAUSE *ifparse() { CLAUSE *root, *ptr, *parse(); int block = FALSE; scan(); if (symbol != leftpar) { error("Missing leftpar.\n"); } root = ptr = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); ptr->data = ifsym; scan(); ptr -> this = equation(); if (symbol != rightpar) { error("Missing rightpar.\n"); } scan(); if (symbol == thensym) scan(); if (symbol == nullsym) { dogets(str, PMODE_CONT); scan(); } if (symbol == beginsym) { block = TRUE; LINK(ptr) = blockparse(); } else LINK(ptr) = parse(); while(LINK(ptr) != NULL) { ptr = LINK(ptr); } root->jmp = LINK(ptr) = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); ptr = LINK(ptr); ptr->data = endsym; if (symbol == elsesym || bendsym == elsesym) { root -> jmp = LINK(ptr) = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); ptr = LINK(ptr); ptr->data = elsesym; if (symbol == elsesym) scan(); if (symbol == nullsym) { dogets(str, PMODE_CONT); scan(); } if (symbol == beginsym) { LINK(ptr) = blockparse(); if (block && bendsym != endsym) error("else: missing end.\n"); } else LINK(ptr) = parse(); while(LINK(ptr) != NULL) { ptr = LINK(ptr); } root->jmp->jmp = LINK(ptr) = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); LINK(ptr)->data = endsym; } return root; } CLAUSE *whileparse() { CLAUSE *root, *ptr; scan(); if (symbol != leftpar) { error("Missing leftpar.\n"); } root = ptr = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); ptr->data = whilesym; scan(); ptr->this = equation(); if (symbol != rightpar) { error("Missing rightpar.\n"); } scan(); if (symbol == nullsym) { dogets(str, PMODE_CONT); scan(); } if (symbol == beginsym) { LINK(ptr) = blockparse(); if (bendsym != endsym) error("while: missing end.\n"); } else LINK(ptr) = parse(); while(LINK(ptr) != NULL) { ptr = LINK(ptr); } root -> jmp = LINK(ptr) = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); LINK(ptr)->data = endsym; return root; } CLAUSE *forparse() { CLAUSE *root, *ptr; scan(); if (symbol != leftpar) { error("for: missing leftpar.\n"); } root = ptr = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); ptr->data = forsym; scan(); ptr -> this = nameorvar(); if (symbol != assignsym) { error("for: missing equalsign\n"); } scan(); LINK(ptr->this) = equation(); if (symbol != rightpar) { error("Missing rightpar.\n"); } scan(); if (symbol == nullsym) { dogets(str, PMODE_CONT); scan(); } if (symbol == beginsym) { LINK(ptr) = blockparse(); if (bendsym != endsym) error("for: missing end.\n"); } else LINK(ptr) = parse(); while(LINK(ptr) != NULL) { ptr = LINK(ptr); } root -> jmp = LINK(ptr) = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); LINK(ptr)->data = endsym; return root; } CLAUSE *parse() { CLAUSE *ptr = (CLAUSE *)NULL; switch(symbol) { case funcsym: ptr = funcparse(); break; case beginsym: ptr = blockparse(); if (bendsym != endsym) error("begin: missing end.\n"); break; case ifsym: ptr = ifparse(); break; case whilesym: ptr = whileparse(); break; case forsym: ptr = forparse(); break; case systemcall: ptr = scallparse(); break; case comment: ptr = commentparse(); break; default: ptr = statement(); break; } while( symbol == statemend ) scan(); if (ptr == (CLAUSE *)NULL) ptr = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); return ptr; } void free_treeentry(root) TREEENTRY *root; { if (root == NULL) return; free_tree(root->args); free_tree(root->subs); if ( root->entrytype == ETYPE_STRING || root->entrytype == ETYPE_NAME ) FREEMEM(root->entrydata.s_data); else if ( root->entrytype == ETYPE_CONST ) var_delete_temp(root->entrydata.c_data); } void free_tree(root) TREE *root; { if (root == NULL) return; free_tree(NEXT(root)); free_tree(LINK(root)); free_tree(LEFT(root)); free_tree(RIGHT(root)); free_treeentry(&root->tentry); FREEMEM((char *)root); } void free_clause(root) CLAUSE *root; { if (root == NULL) return; free_clause(LINK(root)); free_tree(root->this); FREEMEM((char *)root); } VARIABLE *doit(line) char *line; { CLAUSE *ptr, *root; VARIABLE *res; str = buf; strcpy( str, line ); root = ptr = (CLAUSE *)ALLOCMEM(sizeof(CLAUSE)); scan(); while(symbol != nullsym) { LINK(ptr) = parse(); while(LINK(ptr) != NULL) { ptr = LINK(ptr); } } /* root = optimclause(root); */ /* printclause(root, math_out, 0); */ res = evalclause(root); free_clause(root); return res; }
core_cunmlq.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_zunmlq.c, normal z -> c, Fri Sep 28 17:38:25 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" #include <omp.h> /***************************************************************************//** * * @ingroup core_unmlq * * Overwrites the general complex m-by-n tile C with * * side = PlasmaLeft side = PlasmaRight * trans = PlasmaNoTrans Q * C C * Q * trans = Plasma_ConjTrans Q^H * C C * Q^H * * where Q is a unitary matrix defined as the product of k * elementary reflectors * \f[ * Q = H(k) . . . H(2) H(1) * \f] * as returned by plasma_core_cgelqt. Q is of order m if side = PlasmaLeft * and of order n if side = PlasmaRight. * ******************************************************************************* * * @param[in] side * - PlasmaLeft : apply Q or Q^H from the Left; * - PlasmaRight : apply Q or Q^H from the Right. * * @param[in] trans * - PlasmaNoTrans : No transpose, apply Q; * - Plasma_ConjTrans : Transpose, apply Q^H. * * @param[in] m * The number of rows of the tile C. m >= 0. * * @param[in] n * The number of columns of the tile C. n >= 0. * * @param[in] k * The number of elementary reflectors whose product defines * the matrix Q. * If side = PlasmaLeft, m >= k >= 0; * if side = PlasmaRight, n >= k >= 0. * * @param[in] ib * The inner-blocking size. ib >= 0. * * @param[in] A * Dimension: (lda,m) if SIDE = PlasmaLeft, * (lda,n) if SIDE = PlasmaRight, * The i-th row must contain the vector which defines the * elementary reflector H(i), for i = 1,2,...,k, as returned by * plasma_core_cgelqt in the first k rows of its array argument A. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,k). * * @param[in] T * The ib-by-k triangular factor T of the block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] ldt * The leading dimension of the array T. ldt >= ib. * * @param[in,out] C * On entry, the m-by-n tile C. * On exit, C is overwritten by Q*C or Q^H*C or C*Q^H or C*Q. * * @param[in] ldc * The leading dimension of the array C. ldc >= max(1,m). * * @param work * Auxiliary workspace array of length * ldwork-by-m if side == PlasmaLeft * ldwork-by-ib if side == PlasmaRight * * @param[in] ldwork * The leading dimension of the array work. * ldwork >= max(1,ib) if side == PlasmaLeft * ldwork >= max(1,n) if side == PlasmaRight * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************/ __attribute__((weak)) int plasma_core_cunmlq(plasma_enum_t side, plasma_enum_t trans, int m, int n, int k, int ib, const plasma_complex32_t *A, int lda, const plasma_complex32_t *T, int ldt, plasma_complex32_t *C, int ldc, plasma_complex32_t *work, int ldwork) { // Check input arguments. if ((side != PlasmaLeft) && (side != PlasmaRight)) { plasma_coreblas_error("illegal value of side"); return -1; } int nq; // order of Q int nw; // dimension of work if (side == PlasmaLeft) { nq = m; nw = n; } else { nq = n; nw = m; } if (trans != PlasmaNoTrans && trans != Plasma_ConjTrans) { plasma_coreblas_error("illegal value of trans"); return -2; } if (m < 0) { plasma_coreblas_error("illegal value of m"); return -3; } if (n < 0) { plasma_coreblas_error("illegal value of n"); return -4; } if (k < 0 || k > nq) { plasma_coreblas_error("illegal value of k"); return -5; } if (ib < 0) { plasma_coreblas_error("illegal value of ib"); return -6; } if (A == NULL) { plasma_coreblas_error("NULL A"); return -7; } if ((lda < imax(1, k)) && (k > 0)) { plasma_coreblas_error("illegal value of lda"); return -8; } if (T == NULL) { plasma_coreblas_error("NULL T"); return -9; } if (ldt < imax(1, ib)) { plasma_coreblas_error("illegal value of ldt"); return -10; } if (C == NULL) { plasma_coreblas_error("NULL C"); return -11; } if ((ldc < imax(1, m)) && (m > 0)) { plasma_coreblas_error("illegal value of ldc"); return -12; } if (work == NULL) { plasma_coreblas_error("NULL work"); return -13; } if ((ldwork < imax(1, nw)) && (nw > 0)) { plasma_coreblas_error("illegal value of ldwork"); return -14; } // quick return if (m == 0 || n == 0 || k == 0) return PlasmaSuccess; int i1, i3; if ((side == PlasmaLeft && trans == PlasmaNoTrans) || (side == PlasmaRight && trans != PlasmaNoTrans)) { i1 = 0; i3 = ib; } else { i1 = ((k-1)/ib)*ib; i3 = -ib; } if (trans == PlasmaNoTrans) trans = Plasma_ConjTrans; else trans = PlasmaNoTrans; for (int i = i1; i > -1 && i < k; i += i3) { int kb = imin(ib, k-i); int ic = 0; int jc = 0; int ni = n; int mi = m; if (side == PlasmaLeft) { // H or H^H is applied to C(i:m,1:n). mi = m - i; ic = i; } else { // H or H^H is applied to C(1:m,i:n). ni = n - i; jc = i; } // Apply H or H^H. LAPACKE_clarfb_work(LAPACK_COL_MAJOR, lapack_const(side), lapack_const(trans), lapack_const(PlasmaForward), lapack_const(PlasmaRowwise), mi, ni, kb, &A[lda*i+i], lda, &T[ldt*i], ldt, &C[ldc*jc+ic], ldc, work, ldwork); } return PlasmaSuccess; } /******************************************************************************/ void plasma_core_omp_cunmlq(plasma_enum_t side, plasma_enum_t trans, int m, int n, int k, int ib, const plasma_complex32_t *A, int lda, const plasma_complex32_t *T, int ldt, plasma_complex32_t *C, int ldc, plasma_workspace_t work, plasma_sequence_t *sequence, plasma_request_t *request) { int ak; if (side == PlasmaLeft) ak = m; else ak = n; #pragma omp task depend(in:A[0:lda*ak]) \ depend(in:T[0:ib*k]) \ depend(inout:C[0:ldc*n]) { if (sequence->status == PlasmaSuccess) { // Prepare workspaces. int tid = omp_get_thread_num(); plasma_complex32_t *W = (plasma_complex32_t*)work.spaces[tid]; int ldwork = side == PlasmaLeft ? n : m; // TODO: float check // Call the kernel. int info = plasma_core_cunmlq(side, trans, m, n, k, ib, A, lda, T, ldt, C, ldc, W, ldwork); if (info != PlasmaSuccess) { plasma_error("core_cunmlq() failed"); plasma_request_fail(sequence, request, PlasmaErrorInternal); } } } }
displacement_lagrangemultiplier_mixed_frictional_contact_criteria.h
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: StructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H) #define KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H /* System includes */ /* External includes */ /* Project includes */ #include "utilities/table_stream_utility.h" #include "utilities/color_utilities.h" #include "solving_strategies/convergencecriterias/convergence_criteria.h" #include "custom_utilities/active_set_utilities.h" namespace Kratos { ///@addtogroup ContactStructuralMechanicsApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@name Kratos Classes ///@{ /** * @class DisplacementLagrangeMultiplierMixedFrictionalContactCriteria * @ingroup ContactStructuralMechanicsApplication * @brief Convergence criteria for contact problems * @details This class implements a convergence control based on nodal displacement and * lagrange multiplier values. The error is evaluated separately for each of them, and * relative and absolute tolerances for both must be specified. * @author Vicente Mataix Ferrandiz */ template< class TSparseSpace, class TDenseSpace > class DisplacementLagrangeMultiplierMixedFrictionalContactCriteria : public ConvergenceCriteria< TSparseSpace, TDenseSpace > { public: ///@name Type Definitions ///@{ /// Pointer definition of DisplacementLagrangeMultiplierMixedFrictionalContactCriteria KRATOS_CLASS_POINTER_DEFINITION( DisplacementLagrangeMultiplierMixedFrictionalContactCriteria ); /// Local Flags KRATOS_DEFINE_LOCAL_FLAG( ENSURE_CONTACT ); KRATOS_DEFINE_LOCAL_FLAG( PRINTING_OUTPUT ); KRATOS_DEFINE_LOCAL_FLAG( TABLE_IS_INITIALIZED ); KRATOS_DEFINE_LOCAL_FLAG( PURE_SLIP ); KRATOS_DEFINE_LOCAL_FLAG( INITIAL_RESIDUAL_IS_SET ); /// The base class definition (and it subclasses) typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; /// The sparse space used typedef TSparseSpace SparseSpaceType; /// The r_table stream definition TODO: Replace by logger typedef TableStreamUtility::Pointer TablePrinterPointerType; /// The index type definition typedef std::size_t IndexType; /// The key type definition typedef std::size_t KeyType; ///@} ///@name Life Cycle ///@{ /** * @brief Default constructor. * @param DispRatioTolerance Relative tolerance for displacement residual error * @param DispAbsTolerance Absolute tolerance for displacement residual error * @param LMRatioTolerance Relative tolerance for lagrange multiplier residual error * @param LMAbsTolerance Absolute tolerance for lagrange multiplier residual error * @param NormalTangentRatio Ratio between the normal and tangent that will accepted as converged * @param EnsureContact To check if the contact is lost * @param pTable The pointer to the output r_table * @param PrintingOutput If the output is going to be printed in a txt file */ explicit DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( const TDataType DispRatioTolerance, const TDataType DispAbsTolerance, const TDataType LMNormalRatioTolerance, const TDataType LMNormalAbsTolerance, const TDataType LMTangentRatioTolerance, const TDataType LMTangentAbsTolerance, const TDataType NormalTangentRatio, const bool EnsureContact = false, const bool PureSlip = false, const bool PrintingOutput = false ) : BaseType() { // Set local flags mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT, EnsureContact); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT, PrintingOutput); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, false); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP, PureSlip); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false); // The displacement residual mDispRatioTolerance = DispRatioTolerance; mDispAbsTolerance = DispAbsTolerance; // The normal contact residual mLMNormalRatioTolerance = LMNormalRatioTolerance; mLMNormalAbsTolerance = LMNormalAbsTolerance; // The tangent contact residual mLMTangentRatioTolerance = LMTangentRatioTolerance; mLMTangentAbsTolerance = LMTangentAbsTolerance; // We get the ratio between the normal and tangent that will accepted as converged mNormalTangentRatio = NormalTangentRatio; } /** * @brief Default constructor (parameters) * @param ThisParameters The configuration parameters */ explicit DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( Parameters ThisParameters = Parameters(R"({})")) : BaseType() { // The default parameters Parameters default_parameters = Parameters(R"( { "ensure_contact" : false, "pure_slip" : false, "print_convergence_criterion" : false, "residual_relative_tolerance" : 1.0e-4, "residual_absolute_tolerance" : 1.0e-9, "contact_displacement_relative_tolerance" : 1.0e-4, "contact_displacement_absolute_tolerance" : 1.0e-9, "frictional_contact_displacement_relative_tolerance" : 1.0e-4, "frictional_contact_displacement_absolute_tolerance" : 1.0e-9, "ratio_normal_tangent_threshold" : 1.0e-4 })" ); ThisParameters.ValidateAndAssignDefaults(default_parameters); // The displacement residual mDispRatioTolerance = ThisParameters["residual_relative_tolerance"].GetDouble(); mDispAbsTolerance = ThisParameters["residual_absolute_tolerance"].GetDouble(); // The normal contact solution mLMNormalRatioTolerance = ThisParameters["contact_displacement_relative_tolerance"].GetDouble(); mLMNormalAbsTolerance = ThisParameters["contact_displacement_absolute_tolerance"].GetDouble(); // The tangent contact solution mLMTangentRatioTolerance = ThisParameters["frictional_contact_displacement_relative_tolerance"].GetDouble(); mLMTangentAbsTolerance = ThisParameters["frictional_contact_displacement_absolute_tolerance"].GetDouble(); // We get the ratio between the normal and tangent that will accepted as converged mNormalTangentRatio = ThisParameters["ratio_normal_tangent_threshold"].GetDouble(); // Set local flags mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT, ThisParameters["ensure_contact"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT, ThisParameters["print_convergence_criterion"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, false); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP, ThisParameters["pure_slip"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false); } //* Copy constructor. DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( DisplacementLagrangeMultiplierMixedFrictionalContactCriteria const& rOther ) :BaseType(rOther) ,mOptions(rOther.mOptions) ,mDispRatioTolerance(rOther.mDispRatioTolerance) ,mDispAbsTolerance(rOther.mDispAbsTolerance) ,mDispInitialResidualNorm(rOther.mDispInitialResidualNorm) ,mDispCurrentResidualNorm(rOther.mDispCurrentResidualNorm) ,mLMNormalRatioTolerance(rOther.mLMNormalRatioTolerance) ,mLMNormalAbsTolerance(rOther.mLMNormalAbsTolerance) ,mLMTangentRatioTolerance(rOther.mLMNormalRatioTolerance) ,mLMTangentAbsTolerance(rOther.mLMNormalAbsTolerance) ,mNormalTangentRatio(rOther.mNormalTangentRatio) { } /// Destructor. ~DisplacementLagrangeMultiplierMixedFrictionalContactCriteria() override = default; ///@} ///@name Operators ///@{ /** * @brief Compute relative and absolute error. * @param rModelPart Reference to the ModelPart containing the contact problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) * @return true if convergence is achieved, false otherwise */ bool PostCriteria( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { if (SparseSpaceType::Size(rb) != 0) { //if we are solving for something // Getting process info ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); // Compute the active set if (!r_process_info[ACTIVE_SET_COMPUTED]) { const array_1d<std::size_t, 2> is_converged = ActiveSetUtilities::ComputeALMFrictionalActiveSet(rModelPart, mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP), this->GetEchoLevel()); // We save to the process info if the active set has converged r_process_info[ACTIVE_SET_CONVERGED] = is_converged[0] == 0 ? true : false; r_process_info[SLIP_SET_CONVERGED] = is_converged[1] == 0 ? true : false; r_process_info[ACTIVE_SET_COMPUTED] = true; } // Initialize TDataType disp_residual_solution_norm = 0.0, normal_lm_solution_norm = 0.0, normal_lm_increase_norm = 0.0, tangent_lm_stick_solution_norm = 0.0, tangent_lm_slip_solution_norm = 0.0, tangent_lm_stick_increase_norm = 0.0, tangent_lm_slip_increase_norm = 0.0; IndexType disp_dof_num(0),lm_dof_num(0),lm_stick_dof_num(0),lm_slip_dof_num(0); // The nodes array auto& r_nodes_array = rModelPart.Nodes(); // First iterator const auto it_dof_begin = rDofSet.begin(); // Auxiliar values std::size_t dof_id = 0; TDataType residual_dof_value = 0.0, dof_value = 0.0, dof_incr = 0.0; // Loop over Dofs #pragma omp parallel for reduction(+:disp_residual_solution_norm,normal_lm_solution_norm,normal_lm_increase_norm,disp_dof_num,lm_dof_num, lm_stick_dof_num, lm_slip_dof_num, dof_id,residual_dof_value,dof_value,dof_incr) for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) { auto it_dof = it_dof_begin + i; if (it_dof->IsFree()) { dof_id = it_dof->EquationId(); const auto curr_var = it_dof->GetVariable(); if (curr_var == VECTOR_LAGRANGE_MULTIPLIER_X) { // The normal of the node (TODO: how to solve this without accesing all the time to the database?) const auto it_node = r_nodes_array.find(it_dof->Id()); const double normal_x = it_node->FastGetSolutionStepValue(NORMAL_X); dof_value = it_dof->GetSolutionStepValue(0); dof_incr = rDx[dof_id]; const TDataType normal_dof_value = dof_value * normal_x; const TDataType normal_dof_incr = dof_incr * normal_x; normal_lm_solution_norm += std::pow(normal_dof_value, 2); normal_lm_increase_norm += std::pow(normal_dof_incr, 2); if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_slip_dof_num; } else { tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_stick_dof_num; } lm_dof_num++; } else if (curr_var == VECTOR_LAGRANGE_MULTIPLIER_Y) { // The normal of the node (TODO: how to solve this without accesing all the time to the database?) const auto it_node = r_nodes_array.find(it_dof->Id()); const double normal_y = it_node->FastGetSolutionStepValue(NORMAL_Y); dof_value = it_dof->GetSolutionStepValue(0); dof_incr = rDx[dof_id]; const TDataType normal_dof_value = dof_value * normal_y; const TDataType normal_dof_incr = dof_incr * normal_y; normal_lm_solution_norm += std::pow(normal_dof_value, 2); normal_lm_increase_norm += std::pow(normal_dof_incr, 2); if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_slip_dof_num; } else { tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_stick_dof_num; } lm_dof_num++; } else if (curr_var == VECTOR_LAGRANGE_MULTIPLIER_Z) { // The normal of the node (TODO: how to solve this without accesing all the time to the database?) const auto it_node = r_nodes_array.find(it_dof->Id()); const double normal_z = it_node->FastGetSolutionStepValue(NORMAL_Z); dof_value = it_dof->GetSolutionStepValue(0); dof_incr = rDx[dof_id]; const TDataType normal_dof_value = dof_value * normal_z; const TDataType normal_dof_incr = dof_incr * normal_z; normal_lm_solution_norm += std::pow(normal_dof_value, 2); normal_lm_increase_norm += std::pow(normal_dof_incr, 2); if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_slip_dof_num; } else { tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2); tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2); ++lm_stick_dof_num; } lm_dof_num++; } else { residual_dof_value = rb[dof_id]; disp_residual_solution_norm += residual_dof_value * residual_dof_value; disp_dof_num++; } } } if(normal_lm_increase_norm == 0.0) normal_lm_increase_norm = 1.0; if(tangent_lm_stick_increase_norm == 0.0) tangent_lm_stick_increase_norm = 1.0; if(tangent_lm_slip_increase_norm == 0.0) tangent_lm_slip_increase_norm = 1.0; KRATOS_ERROR_IF(mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT) && normal_lm_solution_norm == 0.0) << "ERROR::CONTACT LOST::ARE YOU SURE YOU ARE SUPPOSED TO HAVE CONTACT?" << std::endl; mDispCurrentResidualNorm = disp_residual_solution_norm; const TDataType normal_lm_ratio = std::sqrt(normal_lm_increase_norm/normal_lm_solution_norm); const TDataType tangent_lm_slip_ratio = std::sqrt(tangent_lm_slip_increase_norm/tangent_lm_slip_solution_norm); const TDataType tangent_lm_stick_ratio = std::sqrt(tangent_lm_stick_increase_norm/tangent_lm_stick_solution_norm); const TDataType normal_lm_abs = std::sqrt(normal_lm_increase_norm)/ static_cast<TDataType>(lm_dof_num); const TDataType tangent_lm_stick_abs = lm_stick_dof_num > 0 ? std::sqrt(tangent_lm_stick_increase_norm)/ static_cast<TDataType>(lm_stick_dof_num) : 0.0; const TDataType tangent_lm_slip_abs = lm_slip_dof_num > 0 ? std::sqrt(tangent_lm_slip_increase_norm)/ static_cast<TDataType>(lm_slip_dof_num) : 0.0; const TDataType normal_tangent_stick_ratio = tangent_lm_stick_abs/normal_lm_abs; const TDataType normal_tangent_slip_ratio = tangent_lm_slip_abs/normal_lm_abs; TDataType residual_disp_ratio; // We initialize the solution if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET)) { mDispInitialResidualNorm = (disp_residual_solution_norm == 0.0) ? 1.0 : disp_residual_solution_norm; residual_disp_ratio = 1.0; mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, true); } // We calculate the ratio of the displacements residual_disp_ratio = mDispCurrentResidualNorm/mDispInitialResidualNorm; // We calculate the absolute norms TDataType residual_disp_abs = mDispCurrentResidualNorm/disp_dof_num; // We print the results // TODO: Replace for the new log if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { std::cout.precision(4); TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_stick_ratio << mLMTangentRatioTolerance << tangent_lm_stick_abs << mLMTangentAbsTolerance << tangent_lm_slip_ratio << mLMTangentRatioTolerance << tangent_lm_slip_abs << mLMTangentAbsTolerance; } else { r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_slip_ratio << mLMTangentRatioTolerance << tangent_lm_slip_abs << mLMTangentAbsTolerance; } } else { std::cout.precision(4); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) { KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("MIXED CONVERGENCE CHECK") << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tDISPLACEMENT: RATIO = ") << residual_disp_ratio << BOLDFONT(" EXP.RATIO = ") << mDispRatioTolerance << BOLDFONT(" ABS = ") << residual_disp_abs << BOLDFONT(" EXP.ABS = ") << mDispAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tNORMAL LAGRANGE MUL: RATIO = ") << normal_lm_ratio << BOLDFONT(" EXP.RATIO = ") << mLMNormalRatioTolerance << BOLDFONT(" ABS = ") << normal_lm_abs << BOLDFONT(" EXP.ABS = ") << mLMNormalAbsTolerance << std::endl; KRATOS_INFO_IF("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) << BOLDFONT(" STICK LAGRANGE MUL:\tRATIO = ") << tangent_lm_stick_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentRatioTolerance << BOLDFONT(" ABS = ") << tangent_lm_stick_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT(" SLIP LAGRANGE MUL:\tRATIO = ") << tangent_lm_slip_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentRatioTolerance << BOLDFONT(" ABS = ") << tangent_lm_slip_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentAbsTolerance << std::endl; } else { KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "MIXED CONVERGENCE CHECK" << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tDISPLACEMENT: RATIO = " << residual_disp_ratio << " EXP.RATIO = " << mDispRatioTolerance << " ABS = " << residual_disp_abs << " EXP.ABS = " << mDispAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tNORMAL LAGRANGE MUL: RATIO = " << normal_lm_ratio << " EXP.RATIO = " << mLMNormalRatioTolerance << " ABS = " << normal_lm_abs << " EXP.ABS = " << mLMNormalAbsTolerance << std::endl; KRATOS_INFO_IF("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) << " STICK LAGRANGE MUL:\tRATIO = " << tangent_lm_stick_ratio << " EXP.RATIO = " << mLMTangentRatioTolerance << " ABS = " << tangent_lm_stick_abs << " EXP.ABS = " << mLMTangentAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << " SLIP LAGRANGE MUL:\tRATIO = " << tangent_lm_slip_ratio << " EXP.RATIO = " << mLMTangentRatioTolerance << " ABS = " << tangent_lm_slip_abs << " EXP.ABS = " << mLMTangentAbsTolerance << std::endl; } } } // NOTE: Here we don't include the tangent counter part r_process_info[CONVERGENCE_RATIO] = (residual_disp_ratio > normal_lm_ratio) ? residual_disp_ratio : normal_lm_ratio; r_process_info[RESIDUAL_NORM] = (normal_lm_abs > mLMNormalAbsTolerance) ? normal_lm_abs : mLMNormalAbsTolerance; // We check if converged const bool disp_converged = (residual_disp_ratio <= mDispRatioTolerance || residual_disp_abs <= mDispAbsTolerance); const bool lm_converged = (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT) && normal_lm_solution_norm == 0.0) ? true : (normal_lm_ratio <= mLMNormalRatioTolerance || normal_lm_abs <= mLMNormalAbsTolerance) && (tangent_lm_stick_ratio <= mLMTangentRatioTolerance || tangent_lm_stick_abs <= mLMTangentAbsTolerance || normal_tangent_stick_ratio <= mNormalTangentRatio) && (tangent_lm_slip_ratio <= mLMTangentRatioTolerance || tangent_lm_slip_abs <= mLMTangentAbsTolerance || normal_tangent_slip_ratio <= mNormalTangentRatio); if ( disp_converged && lm_converged ) { if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) r_table << BOLDFONT(FGRN(" Achieved")); else r_table << "Achieved"; } else { if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FGRN("achieved")) << std::endl; else KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tConvergence is achieved" << std::endl; } } return true; } else { if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) r_table << BOLDFONT(FRED(" Not achieved")); else r_table << "Not achieved"; } else { if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FRED(" not achieved")) << std::endl; else KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tConvergence is not achieved" << std::endl; } } return false; } } else // In this case all the displacements are imposed! return true; } /** * @brief This function initialize the convergence criteria * @param rModelPart Reference to the ModelPart containing the contact problem. (unused) */ void Initialize( ModelPart& rModelPart) override { BaseType::mConvergenceCriteriaIsInitialized = true; ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); if (r_process_info.Has(TABLE_UTILITY) && mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); r_table.AddColumn("DP RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); r_table.AddColumn("N.LM RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) { r_table.AddColumn("STI. RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); } r_table.AddColumn("SLIP RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); r_table.AddColumn("CONVERGENCE", 15); mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, true); } } /** * @brief This function initializes the solution step * @param rModelPart Reference to the ModelPart containing the contact problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) */ void InitializeSolutionStep( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false); } /** * @brief This function finalizes the non-linear iteration * @param rModelPart Reference to the ModelPart containing the problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual + reactions) */ void FinalizeNonLinearIteration( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { // Calling base criteria BaseType::FinalizeNonLinearIteration(rModelPart, rDofSet, rA, rDx, rb); // The current process info ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); r_process_info.SetValue(ACTIVE_SET_COMPUTED, false); } ///@} ///@name Operations ///@{ ///@} ///@name Acces ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Friends ///@{ protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ Flags mOptions; /// Local flags TDataType mDispRatioTolerance; /// The ratio threshold for the norm of the displacement residual TDataType mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement residual TDataType mDispInitialResidualNorm; /// The reference norm of the displacement residual TDataType mDispCurrentResidualNorm; /// The current norm of the displacement residual TDataType mLMNormalRatioTolerance; /// The ratio threshold for the norm of the LM (normal) TDataType mLMNormalAbsTolerance; /// The absolute value threshold for the norm of the LM (normal) TDataType mLMTangentRatioTolerance; /// The ratio threshold for the norm of the LM (tangent) TDataType mLMTangentAbsTolerance; /// The absolute value threshold for the norm of the LM (tangent) TDataType mNormalTangentRatio; /// The ratio to accept a non converged tangent component in case ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Unaccessible methods ///@{ ///@} }; // Kratos DisplacementLagrangeMultiplierMixedFrictionalContactCriteria ///@name Local flags creation ///@{ /// Local Flags template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::ENSURE_CONTACT(Kratos::Flags::Create(0)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_ENSURE_CONTACT(Kratos::Flags::Create(0, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PRINTING_OUTPUT(Kratos::Flags::Create(1)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_PRINTING_OUTPUT(Kratos::Flags::Create(1, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::TABLE_IS_INITIALIZED(Kratos::Flags::Create(2)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_TABLE_IS_INITIALIZED(Kratos::Flags::Create(2, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PURE_SLIP(Kratos::Flags::Create(3)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_PURE_SLIP(Kratos::Flags::Create(3, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(4)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(4, false)); } #endif /* KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H */
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 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] = 16; tile_size[1] = 16; tile_size[2] = 32; tile_size[3] = 128; 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 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+2,4)); ubp=min(floord(4*Nt+Nz-9,16),floord(8*t1+Nz+2,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-3,4)),ceild(16*t2-Nz-19,32));t3<=min(min(min(floord(4*Nt+Ny-9,32),floord(8*t1+Ny+7,32)),floord(16*t2+Ny+3,32)),floord(16*t1-16*t2+Nz+Ny+5,32));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(16*t2-Nz-115,128)),ceild(32*t3-Ny-115,128));t4<=min(min(min(min(floord(4*Nt+Nx-9,128),floord(8*t1+Nx+7,128)),floord(16*t2+Nx+3,128)),floord(32*t3+Nx+19,128)),floord(16*t1-16*t2+Nz+Nx+5,128));t4++) { for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(32*t3-Ny+5,4)),ceild(128*t4-Nx+5,4)),2*t1),4*t1-4*t2+1);t5<=min(min(min(min(min(floord(16*t1-16*t2+Nz+10,4),Nt-1),2*t1+3),4*t2+2),8*t3+6),32*t4+30);t5++) { for (t6=max(max(16*t2,4*t5+4),-16*t1+16*t2+8*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(32*t3,4*t5+4);t7<=min(32*t3+31,4*t5+Ny-5);t7++) { lbv=max(128*t4,4*t5+4); ubv=min(128*t4+127,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(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; }