Path: blob/main/contrib/llvm-project/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
35271 views
//===- OpenMPIRBuilder.cpp - Builder for LLVM-IR for OpenMP directives ----===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7/// \file8///9/// This file implements the OpenMPIRBuilder class, which is used as a10/// convenient way to create LLVM instructions for OpenMP directives.11///12//===----------------------------------------------------------------------===//1314#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"15#include "llvm/ADT/SmallSet.h"16#include "llvm/ADT/StringExtras.h"17#include "llvm/ADT/StringRef.h"18#include "llvm/Analysis/AssumptionCache.h"19#include "llvm/Analysis/CodeMetrics.h"20#include "llvm/Analysis/LoopInfo.h"21#include "llvm/Analysis/OptimizationRemarkEmitter.h"22#include "llvm/Analysis/ScalarEvolution.h"23#include "llvm/Analysis/TargetLibraryInfo.h"24#include "llvm/Bitcode/BitcodeReader.h"25#include "llvm/Frontend/Offloading/Utility.h"26#include "llvm/Frontend/OpenMP/OMPGridValues.h"27#include "llvm/IR/Attributes.h"28#include "llvm/IR/BasicBlock.h"29#include "llvm/IR/CFG.h"30#include "llvm/IR/CallingConv.h"31#include "llvm/IR/Constant.h"32#include "llvm/IR/Constants.h"33#include "llvm/IR/DebugInfoMetadata.h"34#include "llvm/IR/DerivedTypes.h"35#include "llvm/IR/Function.h"36#include "llvm/IR/GlobalVariable.h"37#include "llvm/IR/IRBuilder.h"38#include "llvm/IR/LLVMContext.h"39#include "llvm/IR/MDBuilder.h"40#include "llvm/IR/Metadata.h"41#include "llvm/IR/PassManager.h"42#include "llvm/IR/PassInstrumentation.h"43#include "llvm/IR/ReplaceConstant.h"44#include "llvm/IR/Value.h"45#include "llvm/MC/TargetRegistry.h"46#include "llvm/Support/CommandLine.h"47#include "llvm/Support/ErrorHandling.h"48#include "llvm/Support/FileSystem.h"49#include "llvm/Target/TargetMachine.h"50#include "llvm/Target/TargetOptions.h"51#include "llvm/Transforms/Utils/BasicBlockUtils.h"52#include "llvm/Transforms/Utils/Cloning.h"53#include "llvm/Transforms/Utils/CodeExtractor.h"54#include "llvm/Transforms/Utils/LoopPeel.h"55#include "llvm/Transforms/Utils/UnrollLoop.h"5657#include <cstdint>58#include <optional>59#include <stack>6061#define DEBUG_TYPE "openmp-ir-builder"6263using namespace llvm;64using namespace omp;6566static cl::opt<bool>67OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden,68cl::desc("Use optimistic attributes describing "69"'as-if' properties of runtime calls."),70cl::init(false));7172static cl::opt<double> UnrollThresholdFactor(73"openmp-ir-builder-unroll-threshold-factor", cl::Hidden,74cl::desc("Factor for the unroll threshold to account for code "75"simplifications still taking place"),76cl::init(1.5));7778#ifndef NDEBUG79/// Return whether IP1 and IP2 are ambiguous, i.e. that inserting instructions80/// at position IP1 may change the meaning of IP2 or vice-versa. This is because81/// an InsertPoint stores the instruction before something is inserted. For82/// instance, if both point to the same instruction, two IRBuilders alternating83/// creating instruction will cause the instructions to be interleaved.84static bool isConflictIP(IRBuilder<>::InsertPoint IP1,85IRBuilder<>::InsertPoint IP2) {86if (!IP1.isSet() || !IP2.isSet())87return false;88return IP1.getBlock() == IP2.getBlock() && IP1.getPoint() == IP2.getPoint();89}9091static bool isValidWorkshareLoopScheduleType(OMPScheduleType SchedType) {92// Valid ordered/unordered and base algorithm combinations.93switch (SchedType & ~OMPScheduleType::MonotonicityMask) {94case OMPScheduleType::UnorderedStaticChunked:95case OMPScheduleType::UnorderedStatic:96case OMPScheduleType::UnorderedDynamicChunked:97case OMPScheduleType::UnorderedGuidedChunked:98case OMPScheduleType::UnorderedRuntime:99case OMPScheduleType::UnorderedAuto:100case OMPScheduleType::UnorderedTrapezoidal:101case OMPScheduleType::UnorderedGreedy:102case OMPScheduleType::UnorderedBalanced:103case OMPScheduleType::UnorderedGuidedIterativeChunked:104case OMPScheduleType::UnorderedGuidedAnalyticalChunked:105case OMPScheduleType::UnorderedSteal:106case OMPScheduleType::UnorderedStaticBalancedChunked:107case OMPScheduleType::UnorderedGuidedSimd:108case OMPScheduleType::UnorderedRuntimeSimd:109case OMPScheduleType::OrderedStaticChunked:110case OMPScheduleType::OrderedStatic:111case OMPScheduleType::OrderedDynamicChunked:112case OMPScheduleType::OrderedGuidedChunked:113case OMPScheduleType::OrderedRuntime:114case OMPScheduleType::OrderedAuto:115case OMPScheduleType::OrderdTrapezoidal:116case OMPScheduleType::NomergeUnorderedStaticChunked:117case OMPScheduleType::NomergeUnorderedStatic:118case OMPScheduleType::NomergeUnorderedDynamicChunked:119case OMPScheduleType::NomergeUnorderedGuidedChunked:120case OMPScheduleType::NomergeUnorderedRuntime:121case OMPScheduleType::NomergeUnorderedAuto:122case OMPScheduleType::NomergeUnorderedTrapezoidal:123case OMPScheduleType::NomergeUnorderedGreedy:124case OMPScheduleType::NomergeUnorderedBalanced:125case OMPScheduleType::NomergeUnorderedGuidedIterativeChunked:126case OMPScheduleType::NomergeUnorderedGuidedAnalyticalChunked:127case OMPScheduleType::NomergeUnorderedSteal:128case OMPScheduleType::NomergeOrderedStaticChunked:129case OMPScheduleType::NomergeOrderedStatic:130case OMPScheduleType::NomergeOrderedDynamicChunked:131case OMPScheduleType::NomergeOrderedGuidedChunked:132case OMPScheduleType::NomergeOrderedRuntime:133case OMPScheduleType::NomergeOrderedAuto:134case OMPScheduleType::NomergeOrderedTrapezoidal:135break;136default:137return false;138}139140// Must not set both monotonicity modifiers at the same time.141OMPScheduleType MonotonicityFlags =142SchedType & OMPScheduleType::MonotonicityMask;143if (MonotonicityFlags == OMPScheduleType::MonotonicityMask)144return false;145146return true;147}148#endif149150static const omp::GV &getGridValue(const Triple &T, Function *Kernel) {151if (T.isAMDGPU()) {152StringRef Features =153Kernel->getFnAttribute("target-features").getValueAsString();154if (Features.count("+wavefrontsize64"))155return omp::getAMDGPUGridValues<64>();156return omp::getAMDGPUGridValues<32>();157}158if (T.isNVPTX())159return omp::NVPTXGridValues;160llvm_unreachable("No grid value available for this architecture!");161}162163/// Determine which scheduling algorithm to use, determined from schedule clause164/// arguments.165static OMPScheduleType166getOpenMPBaseScheduleType(llvm::omp::ScheduleKind ClauseKind, bool HasChunks,167bool HasSimdModifier) {168// Currently, the default schedule it static.169switch (ClauseKind) {170case OMP_SCHEDULE_Default:171case OMP_SCHEDULE_Static:172return HasChunks ? OMPScheduleType::BaseStaticChunked173: OMPScheduleType::BaseStatic;174case OMP_SCHEDULE_Dynamic:175return OMPScheduleType::BaseDynamicChunked;176case OMP_SCHEDULE_Guided:177return HasSimdModifier ? OMPScheduleType::BaseGuidedSimd178: OMPScheduleType::BaseGuidedChunked;179case OMP_SCHEDULE_Auto:180return llvm::omp::OMPScheduleType::BaseAuto;181case OMP_SCHEDULE_Runtime:182return HasSimdModifier ? OMPScheduleType::BaseRuntimeSimd183: OMPScheduleType::BaseRuntime;184}185llvm_unreachable("unhandled schedule clause argument");186}187188/// Adds ordering modifier flags to schedule type.189static OMPScheduleType190getOpenMPOrderingScheduleType(OMPScheduleType BaseScheduleType,191bool HasOrderedClause) {192assert((BaseScheduleType & OMPScheduleType::ModifierMask) ==193OMPScheduleType::None &&194"Must not have ordering nor monotonicity flags already set");195196OMPScheduleType OrderingModifier = HasOrderedClause197? OMPScheduleType::ModifierOrdered198: OMPScheduleType::ModifierUnordered;199OMPScheduleType OrderingScheduleType = BaseScheduleType | OrderingModifier;200201// Unsupported combinations202if (OrderingScheduleType ==203(OMPScheduleType::BaseGuidedSimd | OMPScheduleType::ModifierOrdered))204return OMPScheduleType::OrderedGuidedChunked;205else if (OrderingScheduleType == (OMPScheduleType::BaseRuntimeSimd |206OMPScheduleType::ModifierOrdered))207return OMPScheduleType::OrderedRuntime;208209return OrderingScheduleType;210}211212/// Adds monotonicity modifier flags to schedule type.213static OMPScheduleType214getOpenMPMonotonicityScheduleType(OMPScheduleType ScheduleType,215bool HasSimdModifier, bool HasMonotonic,216bool HasNonmonotonic, bool HasOrderedClause) {217assert((ScheduleType & OMPScheduleType::MonotonicityMask) ==218OMPScheduleType::None &&219"Must not have monotonicity flags already set");220assert((!HasMonotonic || !HasNonmonotonic) &&221"Monotonic and Nonmonotonic are contradicting each other");222223if (HasMonotonic) {224return ScheduleType | OMPScheduleType::ModifierMonotonic;225} else if (HasNonmonotonic) {226return ScheduleType | OMPScheduleType::ModifierNonmonotonic;227} else {228// OpenMP 5.1, 2.11.4 Worksharing-Loop Construct, Description.229// If the static schedule kind is specified or if the ordered clause is230// specified, and if the nonmonotonic modifier is not specified, the231// effect is as if the monotonic modifier is specified. Otherwise, unless232// the monotonic modifier is specified, the effect is as if the233// nonmonotonic modifier is specified.234OMPScheduleType BaseScheduleType =235ScheduleType & ~OMPScheduleType::ModifierMask;236if ((BaseScheduleType == OMPScheduleType::BaseStatic) ||237(BaseScheduleType == OMPScheduleType::BaseStaticChunked) ||238HasOrderedClause) {239// The monotonic is used by default in openmp runtime library, so no need240// to set it.241return ScheduleType;242} else {243return ScheduleType | OMPScheduleType::ModifierNonmonotonic;244}245}246}247248/// Determine the schedule type using schedule and ordering clause arguments.249static OMPScheduleType250computeOpenMPScheduleType(ScheduleKind ClauseKind, bool HasChunks,251bool HasSimdModifier, bool HasMonotonicModifier,252bool HasNonmonotonicModifier, bool HasOrderedClause) {253OMPScheduleType BaseSchedule =254getOpenMPBaseScheduleType(ClauseKind, HasChunks, HasSimdModifier);255OMPScheduleType OrderedSchedule =256getOpenMPOrderingScheduleType(BaseSchedule, HasOrderedClause);257OMPScheduleType Result = getOpenMPMonotonicityScheduleType(258OrderedSchedule, HasSimdModifier, HasMonotonicModifier,259HasNonmonotonicModifier, HasOrderedClause);260261assert(isValidWorkshareLoopScheduleType(Result));262return Result;263}264265/// Make \p Source branch to \p Target.266///267/// Handles two situations:268/// * \p Source already has an unconditional branch.269/// * \p Source is a degenerate block (no terminator because the BB is270/// the current head of the IR construction).271static void redirectTo(BasicBlock *Source, BasicBlock *Target, DebugLoc DL) {272if (Instruction *Term = Source->getTerminator()) {273auto *Br = cast<BranchInst>(Term);274assert(!Br->isConditional() &&275"BB's terminator must be an unconditional branch (or degenerate)");276BasicBlock *Succ = Br->getSuccessor(0);277Succ->removePredecessor(Source, /*KeepOneInputPHIs=*/true);278Br->setSuccessor(0, Target);279return;280}281282auto *NewBr = BranchInst::Create(Target, Source);283NewBr->setDebugLoc(DL);284}285286void llvm::spliceBB(IRBuilderBase::InsertPoint IP, BasicBlock *New,287bool CreateBranch) {288assert(New->getFirstInsertionPt() == New->begin() &&289"Target BB must not have PHI nodes");290291// Move instructions to new block.292BasicBlock *Old = IP.getBlock();293New->splice(New->begin(), Old, IP.getPoint(), Old->end());294295if (CreateBranch)296BranchInst::Create(New, Old);297}298299void llvm::spliceBB(IRBuilder<> &Builder, BasicBlock *New, bool CreateBranch) {300DebugLoc DebugLoc = Builder.getCurrentDebugLocation();301BasicBlock *Old = Builder.GetInsertBlock();302303spliceBB(Builder.saveIP(), New, CreateBranch);304if (CreateBranch)305Builder.SetInsertPoint(Old->getTerminator());306else307Builder.SetInsertPoint(Old);308309// SetInsertPoint also updates the Builder's debug location, but we want to310// keep the one the Builder was configured to use.311Builder.SetCurrentDebugLocation(DebugLoc);312}313314BasicBlock *llvm::splitBB(IRBuilderBase::InsertPoint IP, bool CreateBranch,315llvm::Twine Name) {316BasicBlock *Old = IP.getBlock();317BasicBlock *New = BasicBlock::Create(318Old->getContext(), Name.isTriviallyEmpty() ? Old->getName() : Name,319Old->getParent(), Old->getNextNode());320spliceBB(IP, New, CreateBranch);321New->replaceSuccessorsPhiUsesWith(Old, New);322return New;323}324325BasicBlock *llvm::splitBB(IRBuilderBase &Builder, bool CreateBranch,326llvm::Twine Name) {327DebugLoc DebugLoc = Builder.getCurrentDebugLocation();328BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, Name);329if (CreateBranch)330Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());331else332Builder.SetInsertPoint(Builder.GetInsertBlock());333// SetInsertPoint also updates the Builder's debug location, but we want to334// keep the one the Builder was configured to use.335Builder.SetCurrentDebugLocation(DebugLoc);336return New;337}338339BasicBlock *llvm::splitBB(IRBuilder<> &Builder, bool CreateBranch,340llvm::Twine Name) {341DebugLoc DebugLoc = Builder.getCurrentDebugLocation();342BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, Name);343if (CreateBranch)344Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());345else346Builder.SetInsertPoint(Builder.GetInsertBlock());347// SetInsertPoint also updates the Builder's debug location, but we want to348// keep the one the Builder was configured to use.349Builder.SetCurrentDebugLocation(DebugLoc);350return New;351}352353BasicBlock *llvm::splitBBWithSuffix(IRBuilderBase &Builder, bool CreateBranch,354llvm::Twine Suffix) {355BasicBlock *Old = Builder.GetInsertBlock();356return splitBB(Builder, CreateBranch, Old->getName() + Suffix);357}358359// This function creates a fake integer value and a fake use for the integer360// value. It returns the fake value created. This is useful in modeling the361// extra arguments to the outlined functions.362Value *createFakeIntVal(IRBuilderBase &Builder,363OpenMPIRBuilder::InsertPointTy OuterAllocaIP,364llvm::SmallVectorImpl<Instruction *> &ToBeDeleted,365OpenMPIRBuilder::InsertPointTy InnerAllocaIP,366const Twine &Name = "", bool AsPtr = true) {367Builder.restoreIP(OuterAllocaIP);368Instruction *FakeVal;369AllocaInst *FakeValAddr =370Builder.CreateAlloca(Builder.getInt32Ty(), nullptr, Name + ".addr");371ToBeDeleted.push_back(FakeValAddr);372373if (AsPtr) {374FakeVal = FakeValAddr;375} else {376FakeVal =377Builder.CreateLoad(Builder.getInt32Ty(), FakeValAddr, Name + ".val");378ToBeDeleted.push_back(FakeVal);379}380381// Generate a fake use of this value382Builder.restoreIP(InnerAllocaIP);383Instruction *UseFakeVal;384if (AsPtr) {385UseFakeVal =386Builder.CreateLoad(Builder.getInt32Ty(), FakeVal, Name + ".use");387} else {388UseFakeVal =389cast<BinaryOperator>(Builder.CreateAdd(FakeVal, Builder.getInt32(10)));390}391ToBeDeleted.push_back(UseFakeVal);392return FakeVal;393}394395//===----------------------------------------------------------------------===//396// OpenMPIRBuilderConfig397//===----------------------------------------------------------------------===//398399namespace {400LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();401/// Values for bit flags for marking which requires clauses have been used.402enum OpenMPOffloadingRequiresDirFlags {403/// flag undefined.404OMP_REQ_UNDEFINED = 0x000,405/// no requires directive present.406OMP_REQ_NONE = 0x001,407/// reverse_offload clause.408OMP_REQ_REVERSE_OFFLOAD = 0x002,409/// unified_address clause.410OMP_REQ_UNIFIED_ADDRESS = 0x004,411/// unified_shared_memory clause.412OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,413/// dynamic_allocators clause.414OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,415LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)416};417418} // anonymous namespace419420OpenMPIRBuilderConfig::OpenMPIRBuilderConfig()421: RequiresFlags(OMP_REQ_UNDEFINED) {}422423OpenMPIRBuilderConfig::OpenMPIRBuilderConfig(424bool IsTargetDevice, bool IsGPU, bool OpenMPOffloadMandatory,425bool HasRequiresReverseOffload, bool HasRequiresUnifiedAddress,426bool HasRequiresUnifiedSharedMemory, bool HasRequiresDynamicAllocators)427: IsTargetDevice(IsTargetDevice), IsGPU(IsGPU),428OpenMPOffloadMandatory(OpenMPOffloadMandatory),429RequiresFlags(OMP_REQ_UNDEFINED) {430if (HasRequiresReverseOffload)431RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;432if (HasRequiresUnifiedAddress)433RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;434if (HasRequiresUnifiedSharedMemory)435RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;436if (HasRequiresDynamicAllocators)437RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;438}439440bool OpenMPIRBuilderConfig::hasRequiresReverseOffload() const {441return RequiresFlags & OMP_REQ_REVERSE_OFFLOAD;442}443444bool OpenMPIRBuilderConfig::hasRequiresUnifiedAddress() const {445return RequiresFlags & OMP_REQ_UNIFIED_ADDRESS;446}447448bool OpenMPIRBuilderConfig::hasRequiresUnifiedSharedMemory() const {449return RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY;450}451452bool OpenMPIRBuilderConfig::hasRequiresDynamicAllocators() const {453return RequiresFlags & OMP_REQ_DYNAMIC_ALLOCATORS;454}455456int64_t OpenMPIRBuilderConfig::getRequiresFlags() const {457return hasRequiresFlags() ? RequiresFlags458: static_cast<int64_t>(OMP_REQ_NONE);459}460461void OpenMPIRBuilderConfig::setHasRequiresReverseOffload(bool Value) {462if (Value)463RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;464else465RequiresFlags &= ~OMP_REQ_REVERSE_OFFLOAD;466}467468void OpenMPIRBuilderConfig::setHasRequiresUnifiedAddress(bool Value) {469if (Value)470RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;471else472RequiresFlags &= ~OMP_REQ_UNIFIED_ADDRESS;473}474475void OpenMPIRBuilderConfig::setHasRequiresUnifiedSharedMemory(bool Value) {476if (Value)477RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;478else479RequiresFlags &= ~OMP_REQ_UNIFIED_SHARED_MEMORY;480}481482void OpenMPIRBuilderConfig::setHasRequiresDynamicAllocators(bool Value) {483if (Value)484RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;485else486RequiresFlags &= ~OMP_REQ_DYNAMIC_ALLOCATORS;487}488489//===----------------------------------------------------------------------===//490// OpenMPIRBuilder491//===----------------------------------------------------------------------===//492493void OpenMPIRBuilder::getKernelArgsVector(TargetKernelArgs &KernelArgs,494IRBuilderBase &Builder,495SmallVector<Value *> &ArgsVector) {496Value *Version = Builder.getInt32(OMP_KERNEL_ARG_VERSION);497Value *PointerNum = Builder.getInt32(KernelArgs.NumTargetItems);498auto Int32Ty = Type::getInt32Ty(Builder.getContext());499Value *ZeroArray = Constant::getNullValue(ArrayType::get(Int32Ty, 3));500Value *Flags = Builder.getInt64(KernelArgs.HasNoWait);501502Value *NumTeams3D =503Builder.CreateInsertValue(ZeroArray, KernelArgs.NumTeams, {0});504Value *NumThreads3D =505Builder.CreateInsertValue(ZeroArray, KernelArgs.NumThreads, {0});506507ArgsVector = {Version,508PointerNum,509KernelArgs.RTArgs.BasePointersArray,510KernelArgs.RTArgs.PointersArray,511KernelArgs.RTArgs.SizesArray,512KernelArgs.RTArgs.MapTypesArray,513KernelArgs.RTArgs.MapNamesArray,514KernelArgs.RTArgs.MappersArray,515KernelArgs.NumIterations,516Flags,517NumTeams3D,518NumThreads3D,519KernelArgs.DynCGGroupMem};520}521522void OpenMPIRBuilder::addAttributes(omp::RuntimeFunction FnID, Function &Fn) {523LLVMContext &Ctx = Fn.getContext();524525// Get the function's current attributes.526auto Attrs = Fn.getAttributes();527auto FnAttrs = Attrs.getFnAttrs();528auto RetAttrs = Attrs.getRetAttrs();529SmallVector<AttributeSet, 4> ArgAttrs;530for (size_t ArgNo = 0; ArgNo < Fn.arg_size(); ++ArgNo)531ArgAttrs.emplace_back(Attrs.getParamAttrs(ArgNo));532533// Add AS to FnAS while taking special care with integer extensions.534auto addAttrSet = [&](AttributeSet &FnAS, const AttributeSet &AS,535bool Param = true) -> void {536bool HasSignExt = AS.hasAttribute(Attribute::SExt);537bool HasZeroExt = AS.hasAttribute(Attribute::ZExt);538if (HasSignExt || HasZeroExt) {539assert(AS.getNumAttributes() == 1 &&540"Currently not handling extension attr combined with others.");541if (Param) {542if (auto AK = TargetLibraryInfo::getExtAttrForI32Param(T, HasSignExt))543FnAS = FnAS.addAttribute(Ctx, AK);544} else if (auto AK =545TargetLibraryInfo::getExtAttrForI32Return(T, HasSignExt))546FnAS = FnAS.addAttribute(Ctx, AK);547} else {548FnAS = FnAS.addAttributes(Ctx, AS);549}550};551552#define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;553#include "llvm/Frontend/OpenMP/OMPKinds.def"554555// Add attributes to the function declaration.556switch (FnID) {557#define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets) \558case Enum: \559FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet); \560addAttrSet(RetAttrs, RetAttrSet, /*Param*/ false); \561for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo) \562addAttrSet(ArgAttrs[ArgNo], ArgAttrSets[ArgNo]); \563Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs)); \564break;565#include "llvm/Frontend/OpenMP/OMPKinds.def"566default:567// Attributes are optional.568break;569}570}571572FunctionCallee573OpenMPIRBuilder::getOrCreateRuntimeFunction(Module &M, RuntimeFunction FnID) {574FunctionType *FnTy = nullptr;575Function *Fn = nullptr;576577// Try to find the declation in the module first.578switch (FnID) {579#define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...) \580case Enum: \581FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__}, \582IsVarArg); \583Fn = M.getFunction(Str); \584break;585#include "llvm/Frontend/OpenMP/OMPKinds.def"586}587588if (!Fn) {589// Create a new declaration if we need one.590switch (FnID) {591#define OMP_RTL(Enum, Str, ...) \592case Enum: \593Fn = Function::Create(FnTy, GlobalValue::ExternalLinkage, Str, M); \594break;595#include "llvm/Frontend/OpenMP/OMPKinds.def"596}597598// Add information if the runtime function takes a callback function599if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {600if (!Fn->hasMetadata(LLVMContext::MD_callback)) {601LLVMContext &Ctx = Fn->getContext();602MDBuilder MDB(Ctx);603// Annotate the callback behavior of the runtime function:604// - The callback callee is argument number 2 (microtask).605// - The first two arguments of the callback callee are unknown (-1).606// - All variadic arguments to the runtime function are passed to the607// callback callee.608Fn->addMetadata(609LLVMContext::MD_callback,610*MDNode::get(Ctx, {MDB.createCallbackEncoding(6112, {-1, -1}, /* VarArgsArePassed */ true)}));612}613}614615LLVM_DEBUG(dbgs() << "Created OpenMP runtime function " << Fn->getName()616<< " with type " << *Fn->getFunctionType() << "\n");617addAttributes(FnID, *Fn);618619} else {620LLVM_DEBUG(dbgs() << "Found OpenMP runtime function " << Fn->getName()621<< " with type " << *Fn->getFunctionType() << "\n");622}623624assert(Fn && "Failed to create OpenMP runtime function");625626return {FnTy, Fn};627}628629Function *OpenMPIRBuilder::getOrCreateRuntimeFunctionPtr(RuntimeFunction FnID) {630FunctionCallee RTLFn = getOrCreateRuntimeFunction(M, FnID);631auto *Fn = dyn_cast<llvm::Function>(RTLFn.getCallee());632assert(Fn && "Failed to create OpenMP runtime function pointer");633return Fn;634}635636void OpenMPIRBuilder::initialize() { initializeTypes(M); }637638static void raiseUserConstantDataAllocasToEntryBlock(IRBuilderBase &Builder,639Function *Function) {640BasicBlock &EntryBlock = Function->getEntryBlock();641Instruction *MoveLocInst = EntryBlock.getFirstNonPHI();642643// Loop over blocks looking for constant allocas, skipping the entry block644// as any allocas there are already in the desired location.645for (auto Block = std::next(Function->begin(), 1); Block != Function->end();646Block++) {647for (auto Inst = Block->getReverseIterator()->begin();648Inst != Block->getReverseIterator()->end();) {649if (auto *AllocaInst = dyn_cast_if_present<llvm::AllocaInst>(Inst)) {650Inst++;651if (!isa<ConstantData>(AllocaInst->getArraySize()))652continue;653AllocaInst->moveBeforePreserving(MoveLocInst);654} else {655Inst++;656}657}658}659}660661void OpenMPIRBuilder::finalize(Function *Fn) {662SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;663SmallVector<BasicBlock *, 32> Blocks;664SmallVector<OutlineInfo, 16> DeferredOutlines;665for (OutlineInfo &OI : OutlineInfos) {666// Skip functions that have not finalized yet; may happen with nested667// function generation.668if (Fn && OI.getFunction() != Fn) {669DeferredOutlines.push_back(OI);670continue;671}672673ParallelRegionBlockSet.clear();674Blocks.clear();675OI.collectBlocks(ParallelRegionBlockSet, Blocks);676677Function *OuterFn = OI.getFunction();678CodeExtractorAnalysisCache CEAC(*OuterFn);679// If we generate code for the target device, we need to allocate680// struct for aggregate params in the device default alloca address space.681// OpenMP runtime requires that the params of the extracted functions are682// passed as zero address space pointers. This flag ensures that683// CodeExtractor generates correct code for extracted functions684// which are used by OpenMP runtime.685bool ArgsInZeroAddressSpace = Config.isTargetDevice();686CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,687/* AggregateArgs */ true,688/* BlockFrequencyInfo */ nullptr,689/* BranchProbabilityInfo */ nullptr,690/* AssumptionCache */ nullptr,691/* AllowVarArgs */ true,692/* AllowAlloca */ true,693/* AllocaBlock*/ OI.OuterAllocaBB,694/* Suffix */ ".omp_par", ArgsInZeroAddressSpace);695696LLVM_DEBUG(dbgs() << "Before outlining: " << *OuterFn << "\n");697LLVM_DEBUG(dbgs() << "Entry " << OI.EntryBB->getName()698<< " Exit: " << OI.ExitBB->getName() << "\n");699assert(Extractor.isEligible() &&700"Expected OpenMP outlining to be possible!");701702for (auto *V : OI.ExcludeArgsFromAggregate)703Extractor.excludeArgFromAggregate(V);704705Function *OutlinedFn = Extractor.extractCodeRegion(CEAC);706707// Forward target-cpu, target-features attributes to the outlined function.708auto TargetCpuAttr = OuterFn->getFnAttribute("target-cpu");709if (TargetCpuAttr.isStringAttribute())710OutlinedFn->addFnAttr(TargetCpuAttr);711712auto TargetFeaturesAttr = OuterFn->getFnAttribute("target-features");713if (TargetFeaturesAttr.isStringAttribute())714OutlinedFn->addFnAttr(TargetFeaturesAttr);715716LLVM_DEBUG(dbgs() << "After outlining: " << *OuterFn << "\n");717LLVM_DEBUG(dbgs() << " Outlined function: " << *OutlinedFn << "\n");718assert(OutlinedFn->getReturnType()->isVoidTy() &&719"OpenMP outlined functions should not return a value!");720721// For compability with the clang CG we move the outlined function after the722// one with the parallel region.723OutlinedFn->removeFromParent();724M.getFunctionList().insertAfter(OuterFn->getIterator(), OutlinedFn);725726// Remove the artificial entry introduced by the extractor right away, we727// made our own entry block after all.728{729BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();730assert(ArtificialEntry.getUniqueSuccessor() == OI.EntryBB);731assert(OI.EntryBB->getUniquePredecessor() == &ArtificialEntry);732// Move instructions from the to-be-deleted ArtificialEntry to the entry733// basic block of the parallel region. CodeExtractor generates734// instructions to unwrap the aggregate argument and may sink735// allocas/bitcasts for values that are solely used in the outlined region736// and do not escape.737assert(!ArtificialEntry.empty() &&738"Expected instructions to add in the outlined region entry");739for (BasicBlock::reverse_iterator It = ArtificialEntry.rbegin(),740End = ArtificialEntry.rend();741It != End;) {742Instruction &I = *It;743It++;744745if (I.isTerminator())746continue;747748I.moveBeforePreserving(*OI.EntryBB, OI.EntryBB->getFirstInsertionPt());749}750751OI.EntryBB->moveBefore(&ArtificialEntry);752ArtificialEntry.eraseFromParent();753}754assert(&OutlinedFn->getEntryBlock() == OI.EntryBB);755assert(OutlinedFn && OutlinedFn->getNumUses() == 1);756757// Run a user callback, e.g. to add attributes.758if (OI.PostOutlineCB)759OI.PostOutlineCB(*OutlinedFn);760}761762// Remove work items that have been completed.763OutlineInfos = std::move(DeferredOutlines);764765// The createTarget functions embeds user written code into766// the target region which may inject allocas which need to767// be moved to the entry block of our target or risk malformed768// optimisations by later passes, this is only relevant for769// the device pass which appears to be a little more delicate770// when it comes to optimisations (however, we do not block on771// that here, it's up to the inserter to the list to do so).772// This notbaly has to occur after the OutlinedInfo candidates773// have been extracted so we have an end product that will not774// be implicitly adversely affected by any raises unless775// intentionally appended to the list.776// NOTE: This only does so for ConstantData, it could be extended777// to ConstantExpr's with further effort, however, they should778// largely be folded when they get here. Extending it to runtime779// defined/read+writeable allocation sizes would be non-trivial780// (need to factor in movement of any stores to variables the781// allocation size depends on, as well as the usual loads,782// otherwise it'll yield the wrong result after movement) and783// likely be more suitable as an LLVM optimisation pass.784for (Function *F : ConstantAllocaRaiseCandidates)785raiseUserConstantDataAllocasToEntryBlock(Builder, F);786787EmitMetadataErrorReportFunctionTy &&ErrorReportFn =788[](EmitMetadataErrorKind Kind,789const TargetRegionEntryInfo &EntryInfo) -> void {790errs() << "Error of kind: " << Kind791<< " when emitting offload entries and metadata during "792"OMPIRBuilder finalization \n";793};794795if (!OffloadInfoManager.empty())796createOffloadEntriesAndInfoMetadata(ErrorReportFn);797798if (Config.EmitLLVMUsedMetaInfo.value_or(false)) {799std::vector<WeakTrackingVH> LLVMCompilerUsed = {800M.getGlobalVariable("__openmp_nvptx_data_transfer_temporary_storage")};801emitUsed("llvm.compiler.used", LLVMCompilerUsed);802}803}804805OpenMPIRBuilder::~OpenMPIRBuilder() {806assert(OutlineInfos.empty() && "There must be no outstanding outlinings");807}808809GlobalValue *OpenMPIRBuilder::createGlobalFlag(unsigned Value, StringRef Name) {810IntegerType *I32Ty = Type::getInt32Ty(M.getContext());811auto *GV =812new GlobalVariable(M, I32Ty,813/* isConstant = */ true, GlobalValue::WeakODRLinkage,814ConstantInt::get(I32Ty, Value), Name);815GV->setVisibility(GlobalValue::HiddenVisibility);816817return GV;818}819820Constant *OpenMPIRBuilder::getOrCreateIdent(Constant *SrcLocStr,821uint32_t SrcLocStrSize,822IdentFlag LocFlags,823unsigned Reserve2Flags) {824// Enable "C-mode".825LocFlags |= OMP_IDENT_FLAG_KMPC;826827Constant *&Ident =828IdentMap[{SrcLocStr, uint64_t(LocFlags) << 31 | Reserve2Flags}];829if (!Ident) {830Constant *I32Null = ConstantInt::getNullValue(Int32);831Constant *IdentData[] = {I32Null,832ConstantInt::get(Int32, uint32_t(LocFlags)),833ConstantInt::get(Int32, Reserve2Flags),834ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};835Constant *Initializer =836ConstantStruct::get(OpenMPIRBuilder::Ident, IdentData);837838// Look for existing encoding of the location + flags, not needed but839// minimizes the difference to the existing solution while we transition.840for (GlobalVariable &GV : M.globals())841if (GV.getValueType() == OpenMPIRBuilder::Ident && GV.hasInitializer())842if (GV.getInitializer() == Initializer)843Ident = &GV;844845if (!Ident) {846auto *GV = new GlobalVariable(847M, OpenMPIRBuilder::Ident,848/* isConstant = */ true, GlobalValue::PrivateLinkage, Initializer, "",849nullptr, GlobalValue::NotThreadLocal,850M.getDataLayout().getDefaultGlobalsAddressSpace());851GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);852GV->setAlignment(Align(8));853Ident = GV;854}855}856857return ConstantExpr::getPointerBitCastOrAddrSpaceCast(Ident, IdentPtr);858}859860Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef LocStr,861uint32_t &SrcLocStrSize) {862SrcLocStrSize = LocStr.size();863Constant *&SrcLocStr = SrcLocStrMap[LocStr];864if (!SrcLocStr) {865Constant *Initializer =866ConstantDataArray::getString(M.getContext(), LocStr);867868// Look for existing encoding of the location, not needed but minimizes the869// difference to the existing solution while we transition.870for (GlobalVariable &GV : M.globals())871if (GV.isConstant() && GV.hasInitializer() &&872GV.getInitializer() == Initializer)873return SrcLocStr = ConstantExpr::getPointerCast(&GV, Int8Ptr);874875SrcLocStr = Builder.CreateGlobalStringPtr(LocStr, /* Name */ "",876/* AddressSpace */ 0, &M);877}878return SrcLocStr;879}880881Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef FunctionName,882StringRef FileName,883unsigned Line, unsigned Column,884uint32_t &SrcLocStrSize) {885SmallString<128> Buffer;886Buffer.push_back(';');887Buffer.append(FileName);888Buffer.push_back(';');889Buffer.append(FunctionName);890Buffer.push_back(';');891Buffer.append(std::to_string(Line));892Buffer.push_back(';');893Buffer.append(std::to_string(Column));894Buffer.push_back(';');895Buffer.push_back(';');896return getOrCreateSrcLocStr(Buffer.str(), SrcLocStrSize);897}898899Constant *900OpenMPIRBuilder::getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize) {901StringRef UnknownLoc = ";unknown;unknown;0;0;;";902return getOrCreateSrcLocStr(UnknownLoc, SrcLocStrSize);903}904905Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(DebugLoc DL,906uint32_t &SrcLocStrSize,907Function *F) {908DILocation *DIL = DL.get();909if (!DIL)910return getOrCreateDefaultSrcLocStr(SrcLocStrSize);911StringRef FileName = M.getName();912if (DIFile *DIF = DIL->getFile())913if (std::optional<StringRef> Source = DIF->getSource())914FileName = *Source;915StringRef Function = DIL->getScope()->getSubprogram()->getName();916if (Function.empty() && F)917Function = F->getName();918return getOrCreateSrcLocStr(Function, FileName, DIL->getLine(),919DIL->getColumn(), SrcLocStrSize);920}921922Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(const LocationDescription &Loc,923uint32_t &SrcLocStrSize) {924return getOrCreateSrcLocStr(Loc.DL, SrcLocStrSize,925Loc.IP.getBlock()->getParent());926}927928Value *OpenMPIRBuilder::getOrCreateThreadID(Value *Ident) {929return Builder.CreateCall(930getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num), Ident,931"omp_global_thread_num");932}933934OpenMPIRBuilder::InsertPointTy935OpenMPIRBuilder::createBarrier(const LocationDescription &Loc, Directive Kind,936bool ForceSimpleCall, bool CheckCancelFlag) {937if (!updateToLocation(Loc))938return Loc.IP;939940// Build call __kmpc_cancel_barrier(loc, thread_id) or941// __kmpc_barrier(loc, thread_id);942943IdentFlag BarrierLocFlags;944switch (Kind) {945case OMPD_for:946BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;947break;948case OMPD_sections:949BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;950break;951case OMPD_single:952BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;953break;954case OMPD_barrier:955BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;956break;957default:958BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;959break;960}961962uint32_t SrcLocStrSize;963Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);964Value *Args[] = {965getOrCreateIdent(SrcLocStr, SrcLocStrSize, BarrierLocFlags),966getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize))};967968// If we are in a cancellable parallel region, barriers are cancellation969// points.970// TODO: Check why we would force simple calls or to ignore the cancel flag.971bool UseCancelBarrier =972!ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);973974Value *Result =975Builder.CreateCall(getOrCreateRuntimeFunctionPtr(976UseCancelBarrier ? OMPRTL___kmpc_cancel_barrier977: OMPRTL___kmpc_barrier),978Args);979980if (UseCancelBarrier && CheckCancelFlag)981emitCancelationCheckImpl(Result, OMPD_parallel);982983return Builder.saveIP();984}985986OpenMPIRBuilder::InsertPointTy987OpenMPIRBuilder::createCancel(const LocationDescription &Loc,988Value *IfCondition,989omp::Directive CanceledDirective) {990if (!updateToLocation(Loc))991return Loc.IP;992993// LLVM utilities like blocks with terminators.994auto *UI = Builder.CreateUnreachable();995996Instruction *ThenTI = UI, *ElseTI = nullptr;997if (IfCondition)998SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);999Builder.SetInsertPoint(ThenTI);10001001Value *CancelKind = nullptr;1002switch (CanceledDirective) {1003#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \1004case DirectiveEnum: \1005CancelKind = Builder.getInt32(Value); \1006break;1007#include "llvm/Frontend/OpenMP/OMPKinds.def"1008default:1009llvm_unreachable("Unknown cancel kind!");1010}10111012uint32_t SrcLocStrSize;1013Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);1014Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);1015Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};1016Value *Result = Builder.CreateCall(1017getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancel), Args);1018auto ExitCB = [this, CanceledDirective, Loc](InsertPointTy IP) {1019if (CanceledDirective == OMPD_parallel) {1020IRBuilder<>::InsertPointGuard IPG(Builder);1021Builder.restoreIP(IP);1022createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),1023omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,1024/* CheckCancelFlag */ false);1025}1026};10271028// The actual cancel logic is shared with others, e.g., cancel_barriers.1029emitCancelationCheckImpl(Result, CanceledDirective, ExitCB);10301031// Update the insertion point and remove the terminator we introduced.1032Builder.SetInsertPoint(UI->getParent());1033UI->eraseFromParent();10341035return Builder.saveIP();1036}10371038OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitTargetKernel(1039const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return,1040Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads,1041Value *HostPtr, ArrayRef<Value *> KernelArgs) {1042if (!updateToLocation(Loc))1043return Loc.IP;10441045Builder.restoreIP(AllocaIP);1046auto *KernelArgsPtr =1047Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs, nullptr, "kernel_args");1048Builder.restoreIP(Loc.IP);10491050for (unsigned I = 0, Size = KernelArgs.size(); I != Size; ++I) {1051llvm::Value *Arg =1052Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr, I);1053Builder.CreateAlignedStore(1054KernelArgs[I], Arg,1055M.getDataLayout().getPrefTypeAlign(KernelArgs[I]->getType()));1056}10571058SmallVector<Value *> OffloadingArgs{Ident, DeviceID, NumTeams,1059NumThreads, HostPtr, KernelArgsPtr};10601061Return = Builder.CreateCall(1062getOrCreateRuntimeFunction(M, OMPRTL___tgt_target_kernel),1063OffloadingArgs);10641065return Builder.saveIP();1066}10671068OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitKernelLaunch(1069const LocationDescription &Loc, Function *OutlinedFn, Value *OutlinedFnID,1070EmitFallbackCallbackTy emitTargetCallFallbackCB, TargetKernelArgs &Args,1071Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP) {10721073if (!updateToLocation(Loc))1074return Loc.IP;10751076Builder.restoreIP(Loc.IP);1077// On top of the arrays that were filled up, the target offloading call1078// takes as arguments the device id as well as the host pointer. The host1079// pointer is used by the runtime library to identify the current target1080// region, so it only has to be unique and not necessarily point to1081// anything. It could be the pointer to the outlined function that1082// implements the target region, but we aren't using that so that the1083// compiler doesn't need to keep that, and could therefore inline the host1084// function if proven worthwhile during optimization.10851086// From this point on, we need to have an ID of the target region defined.1087assert(OutlinedFnID && "Invalid outlined function ID!");1088(void)OutlinedFnID;10891090// Return value of the runtime offloading call.1091Value *Return = nullptr;10921093// Arguments for the target kernel.1094SmallVector<Value *> ArgsVector;1095getKernelArgsVector(Args, Builder, ArgsVector);10961097// The target region is an outlined function launched by the runtime1098// via calls to __tgt_target_kernel().1099//1100// Note that on the host and CPU targets, the runtime implementation of1101// these calls simply call the outlined function without forking threads.1102// The outlined functions themselves have runtime calls to1103// __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by1104// the compiler in emitTeamsCall() and emitParallelCall().1105//1106// In contrast, on the NVPTX target, the implementation of1107// __tgt_target_teams() launches a GPU kernel with the requested number1108// of teams and threads so no additional calls to the runtime are required.1109// Check the error code and execute the host version if required.1110Builder.restoreIP(emitTargetKernel(Builder, AllocaIP, Return, RTLoc, DeviceID,1111Args.NumTeams, Args.NumThreads,1112OutlinedFnID, ArgsVector));11131114BasicBlock *OffloadFailedBlock =1115BasicBlock::Create(Builder.getContext(), "omp_offload.failed");1116BasicBlock *OffloadContBlock =1117BasicBlock::Create(Builder.getContext(), "omp_offload.cont");1118Value *Failed = Builder.CreateIsNotNull(Return);1119Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);11201121auto CurFn = Builder.GetInsertBlock()->getParent();1122emitBlock(OffloadFailedBlock, CurFn);1123Builder.restoreIP(emitTargetCallFallbackCB(Builder.saveIP()));1124emitBranch(OffloadContBlock);1125emitBlock(OffloadContBlock, CurFn, /*IsFinished=*/true);1126return Builder.saveIP();1127}11281129void OpenMPIRBuilder::emitCancelationCheckImpl(Value *CancelFlag,1130omp::Directive CanceledDirective,1131FinalizeCallbackTy ExitCB) {1132assert(isLastFinalizationInfoCancellable(CanceledDirective) &&1133"Unexpected cancellation!");11341135// For a cancel barrier we create two new blocks.1136BasicBlock *BB = Builder.GetInsertBlock();1137BasicBlock *NonCancellationBlock;1138if (Builder.GetInsertPoint() == BB->end()) {1139// TODO: This branch will not be needed once we moved to the1140// OpenMPIRBuilder codegen completely.1141NonCancellationBlock = BasicBlock::Create(1142BB->getContext(), BB->getName() + ".cont", BB->getParent());1143} else {1144NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());1145BB->getTerminator()->eraseFromParent();1146Builder.SetInsertPoint(BB);1147}1148BasicBlock *CancellationBlock = BasicBlock::Create(1149BB->getContext(), BB->getName() + ".cncl", BB->getParent());11501151// Jump to them based on the return value.1152Value *Cmp = Builder.CreateIsNull(CancelFlag);1153Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,1154/* TODO weight */ nullptr, nullptr);11551156// From the cancellation block we finalize all variables and go to the1157// post finalization block that is known to the FiniCB callback.1158Builder.SetInsertPoint(CancellationBlock);1159if (ExitCB)1160ExitCB(Builder.saveIP());1161auto &FI = FinalizationStack.back();1162FI.FiniCB(Builder.saveIP());11631164// The continuation block is where code generation continues.1165Builder.SetInsertPoint(NonCancellationBlock, NonCancellationBlock->begin());1166}11671168// Callback used to create OpenMP runtime calls to support1169// omp parallel clause for the device.1170// We need to use this callback to replace call to the OutlinedFn in OuterFn1171// by the call to the OpenMP DeviceRTL runtime function (kmpc_parallel_51)1172static void targetParallelCallback(1173OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn, Function *OuterFn,1174BasicBlock *OuterAllocaBB, Value *Ident, Value *IfCondition,1175Value *NumThreads, Instruction *PrivTID, AllocaInst *PrivTIDAddr,1176Value *ThreadID, const SmallVector<Instruction *, 4> &ToBeDeleted) {1177// Add some known attributes.1178IRBuilder<> &Builder = OMPIRBuilder->Builder;1179OutlinedFn.addParamAttr(0, Attribute::NoAlias);1180OutlinedFn.addParamAttr(1, Attribute::NoAlias);1181OutlinedFn.addParamAttr(0, Attribute::NoUndef);1182OutlinedFn.addParamAttr(1, Attribute::NoUndef);1183OutlinedFn.addFnAttr(Attribute::NoUnwind);11841185assert(OutlinedFn.arg_size() >= 2 &&1186"Expected at least tid and bounded tid as arguments");1187unsigned NumCapturedVars = OutlinedFn.arg_size() - /* tid & bounded tid */ 2;11881189CallInst *CI = cast<CallInst>(OutlinedFn.user_back());1190assert(CI && "Expected call instruction to outlined function");1191CI->getParent()->setName("omp_parallel");11921193Builder.SetInsertPoint(CI);1194Type *PtrTy = OMPIRBuilder->VoidPtr;1195Value *NullPtrValue = Constant::getNullValue(PtrTy);11961197// Add alloca for kernel args1198OpenMPIRBuilder ::InsertPointTy CurrentIP = Builder.saveIP();1199Builder.SetInsertPoint(OuterAllocaBB, OuterAllocaBB->getFirstInsertionPt());1200AllocaInst *ArgsAlloca =1201Builder.CreateAlloca(ArrayType::get(PtrTy, NumCapturedVars));1202Value *Args = ArgsAlloca;1203// Add address space cast if array for storing arguments is not allocated1204// in address space 01205if (ArgsAlloca->getAddressSpace())1206Args = Builder.CreatePointerCast(ArgsAlloca, PtrTy);1207Builder.restoreIP(CurrentIP);12081209// Store captured vars which are used by kmpc_parallel_511210for (unsigned Idx = 0; Idx < NumCapturedVars; Idx++) {1211Value *V = *(CI->arg_begin() + 2 + Idx);1212Value *StoreAddress = Builder.CreateConstInBoundsGEP2_64(1213ArrayType::get(PtrTy, NumCapturedVars), Args, 0, Idx);1214Builder.CreateStore(V, StoreAddress);1215}12161217Value *Cond =1218IfCondition ? Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32)1219: Builder.getInt32(1);12201221// Build kmpc_parallel_51 call1222Value *Parallel51CallArgs[] = {1223/* identifier*/ Ident,1224/* global thread num*/ ThreadID,1225/* if expression */ Cond,1226/* number of threads */ NumThreads ? NumThreads : Builder.getInt32(-1),1227/* Proc bind */ Builder.getInt32(-1),1228/* outlined function */1229Builder.CreateBitCast(&OutlinedFn, OMPIRBuilder->ParallelTaskPtr),1230/* wrapper function */ NullPtrValue,1231/* arguments of the outlined funciton*/ Args,1232/* number of arguments */ Builder.getInt64(NumCapturedVars)};12331234FunctionCallee RTLFn =1235OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_parallel_51);12361237Builder.CreateCall(RTLFn, Parallel51CallArgs);12381239LLVM_DEBUG(dbgs() << "With kmpc_parallel_51 placed: "1240<< *Builder.GetInsertBlock()->getParent() << "\n");12411242// Initialize the local TID stack location with the argument value.1243Builder.SetInsertPoint(PrivTID);1244Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();1245Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),1246PrivTIDAddr);12471248// Remove redundant call to the outlined function.1249CI->eraseFromParent();12501251for (Instruction *I : ToBeDeleted) {1252I->eraseFromParent();1253}1254}12551256// Callback used to create OpenMP runtime calls to support1257// omp parallel clause for the host.1258// We need to use this callback to replace call to the OutlinedFn in OuterFn1259// by the call to the OpenMP host runtime function ( __kmpc_fork_call[_if])1260static void1261hostParallelCallback(OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn,1262Function *OuterFn, Value *Ident, Value *IfCondition,1263Instruction *PrivTID, AllocaInst *PrivTIDAddr,1264const SmallVector<Instruction *, 4> &ToBeDeleted) {1265IRBuilder<> &Builder = OMPIRBuilder->Builder;1266FunctionCallee RTLFn;1267if (IfCondition) {1268RTLFn =1269OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call_if);1270} else {1271RTLFn =1272OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);1273}1274if (auto *F = dyn_cast<Function>(RTLFn.getCallee())) {1275if (!F->hasMetadata(LLVMContext::MD_callback)) {1276LLVMContext &Ctx = F->getContext();1277MDBuilder MDB(Ctx);1278// Annotate the callback behavior of the __kmpc_fork_call:1279// - The callback callee is argument number 2 (microtask).1280// - The first two arguments of the callback callee are unknown (-1).1281// - All variadic arguments to the __kmpc_fork_call are passed to the1282// callback callee.1283F->addMetadata(LLVMContext::MD_callback,1284*MDNode::get(Ctx, {MDB.createCallbackEncoding(12852, {-1, -1},1286/* VarArgsArePassed */ true)}));1287}1288}1289// Add some known attributes.1290OutlinedFn.addParamAttr(0, Attribute::NoAlias);1291OutlinedFn.addParamAttr(1, Attribute::NoAlias);1292OutlinedFn.addFnAttr(Attribute::NoUnwind);12931294assert(OutlinedFn.arg_size() >= 2 &&1295"Expected at least tid and bounded tid as arguments");1296unsigned NumCapturedVars = OutlinedFn.arg_size() - /* tid & bounded tid */ 2;12971298CallInst *CI = cast<CallInst>(OutlinedFn.user_back());1299CI->getParent()->setName("omp_parallel");1300Builder.SetInsertPoint(CI);13011302// Build call __kmpc_fork_call[_if](Ident, n, microtask, var1, .., varn);1303Value *ForkCallArgs[] = {1304Ident, Builder.getInt32(NumCapturedVars),1305Builder.CreateBitCast(&OutlinedFn, OMPIRBuilder->ParallelTaskPtr)};13061307SmallVector<Value *, 16> RealArgs;1308RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));1309if (IfCondition) {1310Value *Cond = Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32);1311RealArgs.push_back(Cond);1312}1313RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());13141315// __kmpc_fork_call_if always expects a void ptr as the last argument1316// If there are no arguments, pass a null pointer.1317auto PtrTy = OMPIRBuilder->VoidPtr;1318if (IfCondition && NumCapturedVars == 0) {1319Value *NullPtrValue = Constant::getNullValue(PtrTy);1320RealArgs.push_back(NullPtrValue);1321}1322if (IfCondition && RealArgs.back()->getType() != PtrTy)1323RealArgs.back() = Builder.CreateBitCast(RealArgs.back(), PtrTy);13241325Builder.CreateCall(RTLFn, RealArgs);13261327LLVM_DEBUG(dbgs() << "With fork_call placed: "1328<< *Builder.GetInsertBlock()->getParent() << "\n");13291330// Initialize the local TID stack location with the argument value.1331Builder.SetInsertPoint(PrivTID);1332Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();1333Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),1334PrivTIDAddr);13351336// Remove redundant call to the outlined function.1337CI->eraseFromParent();13381339for (Instruction *I : ToBeDeleted) {1340I->eraseFromParent();1341}1342}13431344IRBuilder<>::InsertPoint OpenMPIRBuilder::createParallel(1345const LocationDescription &Loc, InsertPointTy OuterAllocaIP,1346BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,1347FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,1348omp::ProcBindKind ProcBind, bool IsCancellable) {1349assert(!isConflictIP(Loc.IP, OuterAllocaIP) && "IPs must not be ambiguous");13501351if (!updateToLocation(Loc))1352return Loc.IP;13531354uint32_t SrcLocStrSize;1355Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);1356Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);1357Value *ThreadID = getOrCreateThreadID(Ident);1358// If we generate code for the target device, we need to allocate1359// struct for aggregate params in the device default alloca address space.1360// OpenMP runtime requires that the params of the extracted functions are1361// passed as zero address space pointers. This flag ensures that extracted1362// function arguments are declared in zero address space1363bool ArgsInZeroAddressSpace = Config.isTargetDevice();13641365// Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)1366// only if we compile for host side.1367if (NumThreads && !Config.isTargetDevice()) {1368Value *Args[] = {1369Ident, ThreadID,1370Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};1371Builder.CreateCall(1372getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);1373}13741375if (ProcBind != OMP_PROC_BIND_default) {1376// Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)1377Value *Args[] = {1378Ident, ThreadID,1379ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};1380Builder.CreateCall(1381getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);1382}13831384BasicBlock *InsertBB = Builder.GetInsertBlock();1385Function *OuterFn = InsertBB->getParent();13861387// Save the outer alloca block because the insertion iterator may get1388// invalidated and we still need this later.1389BasicBlock *OuterAllocaBlock = OuterAllocaIP.getBlock();13901391// Vector to remember instructions we used only during the modeling but which1392// we want to delete at the end.1393SmallVector<Instruction *, 4> ToBeDeleted;13941395// Change the location to the outer alloca insertion point to create and1396// initialize the allocas we pass into the parallel region.1397InsertPointTy NewOuter(OuterAllocaBlock, OuterAllocaBlock->begin());1398Builder.restoreIP(NewOuter);1399AllocaInst *TIDAddrAlloca = Builder.CreateAlloca(Int32, nullptr, "tid.addr");1400AllocaInst *ZeroAddrAlloca =1401Builder.CreateAlloca(Int32, nullptr, "zero.addr");1402Instruction *TIDAddr = TIDAddrAlloca;1403Instruction *ZeroAddr = ZeroAddrAlloca;1404if (ArgsInZeroAddressSpace && M.getDataLayout().getAllocaAddrSpace() != 0) {1405// Add additional casts to enforce pointers in zero address space1406TIDAddr = new AddrSpaceCastInst(1407TIDAddrAlloca, PointerType ::get(M.getContext(), 0), "tid.addr.ascast");1408TIDAddr->insertAfter(TIDAddrAlloca);1409ToBeDeleted.push_back(TIDAddr);1410ZeroAddr = new AddrSpaceCastInst(ZeroAddrAlloca,1411PointerType ::get(M.getContext(), 0),1412"zero.addr.ascast");1413ZeroAddr->insertAfter(ZeroAddrAlloca);1414ToBeDeleted.push_back(ZeroAddr);1415}14161417// We only need TIDAddr and ZeroAddr for modeling purposes to get the1418// associated arguments in the outlined function, so we delete them later.1419ToBeDeleted.push_back(TIDAddrAlloca);1420ToBeDeleted.push_back(ZeroAddrAlloca);14211422// Create an artificial insertion point that will also ensure the blocks we1423// are about to split are not degenerated.1424auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);14251426BasicBlock *EntryBB = UI->getParent();1427BasicBlock *PRegEntryBB = EntryBB->splitBasicBlock(UI, "omp.par.entry");1428BasicBlock *PRegBodyBB = PRegEntryBB->splitBasicBlock(UI, "omp.par.region");1429BasicBlock *PRegPreFiniBB =1430PRegBodyBB->splitBasicBlock(UI, "omp.par.pre_finalize");1431BasicBlock *PRegExitBB = PRegPreFiniBB->splitBasicBlock(UI, "omp.par.exit");14321433auto FiniCBWrapper = [&](InsertPointTy IP) {1434// Hide "open-ended" blocks from the given FiniCB by setting the right jump1435// target to the region exit block.1436if (IP.getBlock()->end() == IP.getPoint()) {1437IRBuilder<>::InsertPointGuard IPG(Builder);1438Builder.restoreIP(IP);1439Instruction *I = Builder.CreateBr(PRegExitBB);1440IP = InsertPointTy(I->getParent(), I->getIterator());1441}1442assert(IP.getBlock()->getTerminator()->getNumSuccessors() == 1 &&1443IP.getBlock()->getTerminator()->getSuccessor(0) == PRegExitBB &&1444"Unexpected insertion point for finalization call!");1445return FiniCB(IP);1446};14471448FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});14491450// Generate the privatization allocas in the block that will become the entry1451// of the outlined function.1452Builder.SetInsertPoint(PRegEntryBB->getTerminator());1453InsertPointTy InnerAllocaIP = Builder.saveIP();14541455AllocaInst *PrivTIDAddr =1456Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");1457Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");14581459// Add some fake uses for OpenMP provided arguments.1460ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));1461Instruction *ZeroAddrUse =1462Builder.CreateLoad(Int32, ZeroAddr, "zero.addr.use");1463ToBeDeleted.push_back(ZeroAddrUse);14641465// EntryBB1466// |1467// V1468// PRegionEntryBB <- Privatization allocas are placed here.1469// |1470// V1471// PRegionBodyBB <- BodeGen is invoked here.1472// |1473// V1474// PRegPreFiniBB <- The block we will start finalization from.1475// |1476// V1477// PRegionExitBB <- A common exit to simplify block collection.1478//14791480LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");14811482// Let the caller create the body.1483assert(BodyGenCB && "Expected body generation callback!");1484InsertPointTy CodeGenIP(PRegBodyBB, PRegBodyBB->begin());1485BodyGenCB(InnerAllocaIP, CodeGenIP);14861487LLVM_DEBUG(dbgs() << "After body codegen: " << *OuterFn << "\n");14881489OutlineInfo OI;1490if (Config.isTargetDevice()) {1491// Generate OpenMP target specific runtime call1492OI.PostOutlineCB = [=, ToBeDeletedVec =1493std::move(ToBeDeleted)](Function &OutlinedFn) {1494targetParallelCallback(this, OutlinedFn, OuterFn, OuterAllocaBlock, Ident,1495IfCondition, NumThreads, PrivTID, PrivTIDAddr,1496ThreadID, ToBeDeletedVec);1497};1498} else {1499// Generate OpenMP host runtime call1500OI.PostOutlineCB = [=, ToBeDeletedVec =1501std::move(ToBeDeleted)](Function &OutlinedFn) {1502hostParallelCallback(this, OutlinedFn, OuterFn, Ident, IfCondition,1503PrivTID, PrivTIDAddr, ToBeDeletedVec);1504};1505}15061507OI.OuterAllocaBB = OuterAllocaBlock;1508OI.EntryBB = PRegEntryBB;1509OI.ExitBB = PRegExitBB;15101511SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;1512SmallVector<BasicBlock *, 32> Blocks;1513OI.collectBlocks(ParallelRegionBlockSet, Blocks);15141515// Ensure a single exit node for the outlined region by creating one.1516// We might have multiple incoming edges to the exit now due to finalizations,1517// e.g., cancel calls that cause the control flow to leave the region.1518BasicBlock *PRegOutlinedExitBB = PRegExitBB;1519PRegExitBB = SplitBlock(PRegExitBB, &*PRegExitBB->getFirstInsertionPt());1520PRegOutlinedExitBB->setName("omp.par.outlined.exit");1521Blocks.push_back(PRegOutlinedExitBB);15221523CodeExtractorAnalysisCache CEAC(*OuterFn);1524CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,1525/* AggregateArgs */ false,1526/* BlockFrequencyInfo */ nullptr,1527/* BranchProbabilityInfo */ nullptr,1528/* AssumptionCache */ nullptr,1529/* AllowVarArgs */ true,1530/* AllowAlloca */ true,1531/* AllocationBlock */ OuterAllocaBlock,1532/* Suffix */ ".omp_par", ArgsInZeroAddressSpace);15331534// Find inputs to, outputs from the code region.1535BasicBlock *CommonExit = nullptr;1536SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;1537Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);1538Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands);15391540LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");15411542FunctionCallee TIDRTLFn =1543getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);15441545auto PrivHelper = [&](Value &V) {1546if (&V == TIDAddr || &V == ZeroAddr) {1547OI.ExcludeArgsFromAggregate.push_back(&V);1548return;1549}15501551SetVector<Use *> Uses;1552for (Use &U : V.uses())1553if (auto *UserI = dyn_cast<Instruction>(U.getUser()))1554if (ParallelRegionBlockSet.count(UserI->getParent()))1555Uses.insert(&U);15561557// __kmpc_fork_call expects extra arguments as pointers. If the input1558// already has a pointer type, everything is fine. Otherwise, store the1559// value onto stack and load it back inside the to-be-outlined region. This1560// will ensure only the pointer will be passed to the function.1561// FIXME: if there are more than 15 trailing arguments, they must be1562// additionally packed in a struct.1563Value *Inner = &V;1564if (!V.getType()->isPointerTy()) {1565IRBuilder<>::InsertPointGuard Guard(Builder);1566LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");15671568Builder.restoreIP(OuterAllocaIP);1569Value *Ptr =1570Builder.CreateAlloca(V.getType(), nullptr, V.getName() + ".reloaded");15711572// Store to stack at end of the block that currently branches to the entry1573// block of the to-be-outlined region.1574Builder.SetInsertPoint(InsertBB,1575InsertBB->getTerminator()->getIterator());1576Builder.CreateStore(&V, Ptr);15771578// Load back next to allocations in the to-be-outlined region.1579Builder.restoreIP(InnerAllocaIP);1580Inner = Builder.CreateLoad(V.getType(), Ptr);1581}15821583Value *ReplacementValue = nullptr;1584CallInst *CI = dyn_cast<CallInst>(&V);1585if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {1586ReplacementValue = PrivTID;1587} else {1588Builder.restoreIP(1589PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue));1590InnerAllocaIP = {1591InnerAllocaIP.getBlock(),1592InnerAllocaIP.getBlock()->getTerminator()->getIterator()};15931594assert(ReplacementValue &&1595"Expected copy/create callback to set replacement value!");1596if (ReplacementValue == &V)1597return;1598}15991600for (Use *UPtr : Uses)1601UPtr->set(ReplacementValue);1602};16031604// Reset the inner alloca insertion as it will be used for loading the values1605// wrapped into pointers before passing them into the to-be-outlined region.1606// Configure it to insert immediately after the fake use of zero address so1607// that they are available in the generated body and so that the1608// OpenMP-related values (thread ID and zero address pointers) remain leading1609// in the argument list.1610InnerAllocaIP = IRBuilder<>::InsertPoint(1611ZeroAddrUse->getParent(), ZeroAddrUse->getNextNode()->getIterator());16121613// Reset the outer alloca insertion point to the entry of the relevant block1614// in case it was invalidated.1615OuterAllocaIP = IRBuilder<>::InsertPoint(1616OuterAllocaBlock, OuterAllocaBlock->getFirstInsertionPt());16171618for (Value *Input : Inputs) {1619LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");1620PrivHelper(*Input);1621}1622LLVM_DEBUG({1623for (Value *Output : Outputs)1624LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");1625});1626assert(Outputs.empty() &&1627"OpenMP outlining should not produce live-out values!");16281629LLVM_DEBUG(dbgs() << "After privatization: " << *OuterFn << "\n");1630LLVM_DEBUG({1631for (auto *BB : Blocks)1632dbgs() << " PBR: " << BB->getName() << "\n";1633});16341635// Adjust the finalization stack, verify the adjustment, and call the1636// finalize function a last time to finalize values between the pre-fini1637// block and the exit block if we left the parallel "the normal way".1638auto FiniInfo = FinalizationStack.pop_back_val();1639(void)FiniInfo;1640assert(FiniInfo.DK == OMPD_parallel &&1641"Unexpected finalization stack state!");16421643Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();16441645InsertPointTy PreFiniIP(PRegPreFiniBB, PRegPreFiniTI->getIterator());1646FiniCB(PreFiniIP);16471648// Register the outlined info.1649addOutlineInfo(std::move(OI));16501651InsertPointTy AfterIP(UI->getParent(), UI->getParent()->end());1652UI->eraseFromParent();16531654return AfterIP;1655}16561657void OpenMPIRBuilder::emitFlush(const LocationDescription &Loc) {1658// Build call void __kmpc_flush(ident_t *loc)1659uint32_t SrcLocStrSize;1660Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);1661Value *Args[] = {getOrCreateIdent(SrcLocStr, SrcLocStrSize)};16621663Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), Args);1664}16651666void OpenMPIRBuilder::createFlush(const LocationDescription &Loc) {1667if (!updateToLocation(Loc))1668return;1669emitFlush(Loc);1670}16711672void OpenMPIRBuilder::emitTaskwaitImpl(const LocationDescription &Loc) {1673// Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int321674// global_tid);1675uint32_t SrcLocStrSize;1676Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);1677Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);1678Value *Args[] = {Ident, getOrCreateThreadID(Ident)};16791680// Ignore return result until untied tasks are supported.1681Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait),1682Args);1683}16841685void OpenMPIRBuilder::createTaskwait(const LocationDescription &Loc) {1686if (!updateToLocation(Loc))1687return;1688emitTaskwaitImpl(Loc);1689}16901691void OpenMPIRBuilder::emitTaskyieldImpl(const LocationDescription &Loc) {1692// Build call __kmpc_omp_taskyield(loc, thread_id, 0);1693uint32_t SrcLocStrSize;1694Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);1695Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);1696Constant *I32Null = ConstantInt::getNullValue(Int32);1697Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};16981699Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield),1700Args);1701}17021703void OpenMPIRBuilder::createTaskyield(const LocationDescription &Loc) {1704if (!updateToLocation(Loc))1705return;1706emitTaskyieldImpl(Loc);1707}17081709// Processes the dependencies in Dependencies and does the following1710// - Allocates space on the stack of an array of DependInfo objects1711// - Populates each DependInfo object with relevant information of1712// the corresponding dependence.1713// - All code is inserted in the entry block of the current function.1714static Value *emitTaskDependencies(1715OpenMPIRBuilder &OMPBuilder,1716SmallVectorImpl<OpenMPIRBuilder::DependData> &Dependencies) {1717// Early return if we have no dependencies to process1718if (Dependencies.empty())1719return nullptr;17201721// Given a vector of DependData objects, in this function we create an1722// array on the stack that holds kmp_dep_info objects corresponding1723// to each dependency. This is then passed to the OpenMP runtime.1724// For example, if there are 'n' dependencies then the following psedo1725// code is generated. Assume the first dependence is on a variable 'a'1726//1727// \code{c}1728// DepArray = alloc(n x sizeof(kmp_depend_info);1729// idx = 0;1730// DepArray[idx].base_addr = ptrtoint(&a);1731// DepArray[idx].len = 8;1732// DepArray[idx].flags = Dep.DepKind; /*(See OMPContants.h for DepKind)*/1733// ++idx;1734// DepArray[idx].base_addr = ...;1735// \endcode17361737IRBuilderBase &Builder = OMPBuilder.Builder;1738Type *DependInfo = OMPBuilder.DependInfo;1739Module &M = OMPBuilder.M;17401741Value *DepArray = nullptr;1742OpenMPIRBuilder::InsertPointTy OldIP = Builder.saveIP();1743Builder.SetInsertPoint(1744OldIP.getBlock()->getParent()->getEntryBlock().getTerminator());17451746Type *DepArrayTy = ArrayType::get(DependInfo, Dependencies.size());1747DepArray = Builder.CreateAlloca(DepArrayTy, nullptr, ".dep.arr.addr");17481749for (const auto &[DepIdx, Dep] : enumerate(Dependencies)) {1750Value *Base =1751Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);1752// Store the pointer to the variable1753Value *Addr = Builder.CreateStructGEP(1754DependInfo, Base,1755static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));1756Value *DepValPtr = Builder.CreatePtrToInt(Dep.DepVal, Builder.getInt64Ty());1757Builder.CreateStore(DepValPtr, Addr);1758// Store the size of the variable1759Value *Size = Builder.CreateStructGEP(1760DependInfo, Base, static_cast<unsigned int>(RTLDependInfoFields::Len));1761Builder.CreateStore(1762Builder.getInt64(M.getDataLayout().getTypeStoreSize(Dep.DepValueType)),1763Size);1764// Store the dependency kind1765Value *Flags = Builder.CreateStructGEP(1766DependInfo, Base,1767static_cast<unsigned int>(RTLDependInfoFields::Flags));1768Builder.CreateStore(1769ConstantInt::get(Builder.getInt8Ty(),1770static_cast<unsigned int>(Dep.DepKind)),1771Flags);1772}1773Builder.restoreIP(OldIP);1774return DepArray;1775}17761777OpenMPIRBuilder::InsertPointTy1778OpenMPIRBuilder::createTask(const LocationDescription &Loc,1779InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB,1780bool Tied, Value *Final, Value *IfCondition,1781SmallVector<DependData> Dependencies) {17821783if (!updateToLocation(Loc))1784return InsertPointTy();17851786uint32_t SrcLocStrSize;1787Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);1788Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);1789// The current basic block is split into four basic blocks. After outlining,1790// they will be mapped as follows:1791// ```1792// def current_fn() {1793// current_basic_block:1794// br label %task.exit1795// task.exit:1796// ; instructions after task1797// }1798// def outlined_fn() {1799// task.alloca:1800// br label %task.body1801// task.body:1802// ret void1803// }1804// ```1805BasicBlock *TaskExitBB = splitBB(Builder, /*CreateBranch=*/true, "task.exit");1806BasicBlock *TaskBodyBB = splitBB(Builder, /*CreateBranch=*/true, "task.body");1807BasicBlock *TaskAllocaBB =1808splitBB(Builder, /*CreateBranch=*/true, "task.alloca");18091810InsertPointTy TaskAllocaIP =1811InsertPointTy(TaskAllocaBB, TaskAllocaBB->begin());1812InsertPointTy TaskBodyIP = InsertPointTy(TaskBodyBB, TaskBodyBB->begin());1813BodyGenCB(TaskAllocaIP, TaskBodyIP);18141815OutlineInfo OI;1816OI.EntryBB = TaskAllocaBB;1817OI.OuterAllocaBB = AllocaIP.getBlock();1818OI.ExitBB = TaskExitBB;18191820// Add the thread ID argument.1821SmallVector<Instruction *, 4> ToBeDeleted;1822OI.ExcludeArgsFromAggregate.push_back(createFakeIntVal(1823Builder, AllocaIP, ToBeDeleted, TaskAllocaIP, "global.tid", false));18241825OI.PostOutlineCB = [this, Ident, Tied, Final, IfCondition, Dependencies,1826TaskAllocaBB, ToBeDeleted](Function &OutlinedFn) mutable {1827// Replace the Stale CI by appropriate RTL function call.1828assert(OutlinedFn.getNumUses() == 1 &&1829"there must be a single user for the outlined function");1830CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());18311832// HasShareds is true if any variables are captured in the outlined region,1833// false otherwise.1834bool HasShareds = StaleCI->arg_size() > 1;1835Builder.SetInsertPoint(StaleCI);18361837// Gather the arguments for emitting the runtime call for1838// @__kmpc_omp_task_alloc1839Function *TaskAllocFn =1840getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);18411842// Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)1843// call.1844Value *ThreadID = getOrCreateThreadID(Ident);18451846// Argument - `flags`1847// Task is tied iff (Flags & 1) == 1.1848// Task is untied iff (Flags & 1) == 0.1849// Task is final iff (Flags & 2) == 2.1850// Task is not final iff (Flags & 2) == 0.1851// TODO: Handle the other flags.1852Value *Flags = Builder.getInt32(Tied);1853if (Final) {1854Value *FinalFlag =1855Builder.CreateSelect(Final, Builder.getInt32(2), Builder.getInt32(0));1856Flags = Builder.CreateOr(FinalFlag, Flags);1857}18581859// Argument - `sizeof_kmp_task_t` (TaskSize)1860// Tasksize refers to the size in bytes of kmp_task_t data structure1861// including private vars accessed in task.1862// TODO: add kmp_task_t_with_privates (privates)1863Value *TaskSize = Builder.getInt64(1864divideCeil(M.getDataLayout().getTypeSizeInBits(Task), 8));18651866// Argument - `sizeof_shareds` (SharedsSize)1867// SharedsSize refers to the shareds array size in the kmp_task_t data1868// structure.1869Value *SharedsSize = Builder.getInt64(0);1870if (HasShareds) {1871AllocaInst *ArgStructAlloca =1872dyn_cast<AllocaInst>(StaleCI->getArgOperand(1));1873assert(ArgStructAlloca &&1874"Unable to find the alloca instruction corresponding to arguments "1875"for extracted function");1876StructType *ArgStructType =1877dyn_cast<StructType>(ArgStructAlloca->getAllocatedType());1878assert(ArgStructType && "Unable to find struct type corresponding to "1879"arguments for extracted function");1880SharedsSize =1881Builder.getInt64(M.getDataLayout().getTypeStoreSize(ArgStructType));1882}1883// Emit the @__kmpc_omp_task_alloc runtime call1884// The runtime call returns a pointer to an area where the task captured1885// variables must be copied before the task is run (TaskData)1886CallInst *TaskData = Builder.CreateCall(1887TaskAllocFn, {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,1888/*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,1889/*task_func=*/&OutlinedFn});18901891// Copy the arguments for outlined function1892if (HasShareds) {1893Value *Shareds = StaleCI->getArgOperand(1);1894Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());1895Value *TaskShareds = Builder.CreateLoad(VoidPtr, TaskData);1896Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,1897SharedsSize);1898}18991900Value *DepArray = nullptr;1901if (Dependencies.size()) {1902InsertPointTy OldIP = Builder.saveIP();1903Builder.SetInsertPoint(1904&OldIP.getBlock()->getParent()->getEntryBlock().back());19051906Type *DepArrayTy = ArrayType::get(DependInfo, Dependencies.size());1907DepArray = Builder.CreateAlloca(DepArrayTy, nullptr, ".dep.arr.addr");19081909unsigned P = 0;1910for (const DependData &Dep : Dependencies) {1911Value *Base =1912Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, P);1913// Store the pointer to the variable1914Value *Addr = Builder.CreateStructGEP(1915DependInfo, Base,1916static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));1917Value *DepValPtr =1918Builder.CreatePtrToInt(Dep.DepVal, Builder.getInt64Ty());1919Builder.CreateStore(DepValPtr, Addr);1920// Store the size of the variable1921Value *Size = Builder.CreateStructGEP(1922DependInfo, Base,1923static_cast<unsigned int>(RTLDependInfoFields::Len));1924Builder.CreateStore(Builder.getInt64(M.getDataLayout().getTypeStoreSize(1925Dep.DepValueType)),1926Size);1927// Store the dependency kind1928Value *Flags = Builder.CreateStructGEP(1929DependInfo, Base,1930static_cast<unsigned int>(RTLDependInfoFields::Flags));1931Builder.CreateStore(1932ConstantInt::get(Builder.getInt8Ty(),1933static_cast<unsigned int>(Dep.DepKind)),1934Flags);1935++P;1936}19371938Builder.restoreIP(OldIP);1939}19401941// In the presence of the `if` clause, the following IR is generated:1942// ...1943// %data = call @__kmpc_omp_task_alloc(...)1944// br i1 %if_condition, label %then, label %else1945// then:1946// call @__kmpc_omp_task(...)1947// br label %exit1948// else:1949// ;; Wait for resolution of dependencies, if any, before1950// ;; beginning the task1951// call @__kmpc_omp_wait_deps(...)1952// call @__kmpc_omp_task_begin_if0(...)1953// call @outlined_fn(...)1954// call @__kmpc_omp_task_complete_if0(...)1955// br label %exit1956// exit:1957// ...1958if (IfCondition) {1959// `SplitBlockAndInsertIfThenElse` requires the block to have a1960// terminator.1961splitBB(Builder, /*CreateBranch=*/true, "if.end");1962Instruction *IfTerminator =1963Builder.GetInsertPoint()->getParent()->getTerminator();1964Instruction *ThenTI = IfTerminator, *ElseTI = nullptr;1965Builder.SetInsertPoint(IfTerminator);1966SplitBlockAndInsertIfThenElse(IfCondition, IfTerminator, &ThenTI,1967&ElseTI);1968Builder.SetInsertPoint(ElseTI);19691970if (Dependencies.size()) {1971Function *TaskWaitFn =1972getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_wait_deps);1973Builder.CreateCall(1974TaskWaitFn,1975{Ident, ThreadID, Builder.getInt32(Dependencies.size()), DepArray,1976ConstantInt::get(Builder.getInt32Ty(), 0),1977ConstantPointerNull::get(PointerType::getUnqual(M.getContext()))});1978}1979Function *TaskBeginFn =1980getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_begin_if0);1981Function *TaskCompleteFn =1982getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_complete_if0);1983Builder.CreateCall(TaskBeginFn, {Ident, ThreadID, TaskData});1984CallInst *CI = nullptr;1985if (HasShareds)1986CI = Builder.CreateCall(&OutlinedFn, {ThreadID, TaskData});1987else1988CI = Builder.CreateCall(&OutlinedFn, {ThreadID});1989CI->setDebugLoc(StaleCI->getDebugLoc());1990Builder.CreateCall(TaskCompleteFn, {Ident, ThreadID, TaskData});1991Builder.SetInsertPoint(ThenTI);1992}19931994if (Dependencies.size()) {1995Function *TaskFn =1996getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps);1997Builder.CreateCall(1998TaskFn,1999{Ident, ThreadID, TaskData, Builder.getInt32(Dependencies.size()),2000DepArray, ConstantInt::get(Builder.getInt32Ty(), 0),2001ConstantPointerNull::get(PointerType::getUnqual(M.getContext()))});20022003} else {2004// Emit the @__kmpc_omp_task runtime call to spawn the task2005Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);2006Builder.CreateCall(TaskFn, {Ident, ThreadID, TaskData});2007}20082009StaleCI->eraseFromParent();20102011Builder.SetInsertPoint(TaskAllocaBB, TaskAllocaBB->begin());2012if (HasShareds) {2013LoadInst *Shareds = Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));2014OutlinedFn.getArg(1)->replaceUsesWithIf(2015Shareds, [Shareds](Use &U) { return U.getUser() != Shareds; });2016}20172018llvm::for_each(llvm::reverse(ToBeDeleted),2019[](Instruction *I) { I->eraseFromParent(); });2020};20212022addOutlineInfo(std::move(OI));2023Builder.SetInsertPoint(TaskExitBB, TaskExitBB->begin());20242025return Builder.saveIP();2026}20272028OpenMPIRBuilder::InsertPointTy2029OpenMPIRBuilder::createTaskgroup(const LocationDescription &Loc,2030InsertPointTy AllocaIP,2031BodyGenCallbackTy BodyGenCB) {2032if (!updateToLocation(Loc))2033return InsertPointTy();20342035uint32_t SrcLocStrSize;2036Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);2037Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);2038Value *ThreadID = getOrCreateThreadID(Ident);20392040// Emit the @__kmpc_taskgroup runtime call to start the taskgroup2041Function *TaskgroupFn =2042getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskgroup);2043Builder.CreateCall(TaskgroupFn, {Ident, ThreadID});20442045BasicBlock *TaskgroupExitBB = splitBB(Builder, true, "taskgroup.exit");2046BodyGenCB(AllocaIP, Builder.saveIP());20472048Builder.SetInsertPoint(TaskgroupExitBB);2049// Emit the @__kmpc_end_taskgroup runtime call to end the taskgroup2050Function *EndTaskgroupFn =2051getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_taskgroup);2052Builder.CreateCall(EndTaskgroupFn, {Ident, ThreadID});20532054return Builder.saveIP();2055}20562057OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSections(2058const LocationDescription &Loc, InsertPointTy AllocaIP,2059ArrayRef<StorableBodyGenCallbackTy> SectionCBs, PrivatizeCallbackTy PrivCB,2060FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait) {2061assert(!isConflictIP(AllocaIP, Loc.IP) && "Dedicated IP allocas required");20622063if (!updateToLocation(Loc))2064return Loc.IP;20652066auto FiniCBWrapper = [&](InsertPointTy IP) {2067if (IP.getBlock()->end() != IP.getPoint())2068return FiniCB(IP);2069// This must be done otherwise any nested constructs using FinalizeOMPRegion2070// will fail because that function requires the Finalization Basic Block to2071// have a terminator, which is already removed by EmitOMPRegionBody.2072// IP is currently at cancelation block.2073// We need to backtrack to the condition block to fetch2074// the exit block and create a branch from cancelation2075// to exit block.2076IRBuilder<>::InsertPointGuard IPG(Builder);2077Builder.restoreIP(IP);2078auto *CaseBB = IP.getBlock()->getSinglePredecessor();2079auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();2080auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);2081Instruction *I = Builder.CreateBr(ExitBB);2082IP = InsertPointTy(I->getParent(), I->getIterator());2083return FiniCB(IP);2084};20852086FinalizationStack.push_back({FiniCBWrapper, OMPD_sections, IsCancellable});20872088// Each section is emitted as a switch case2089// Each finalization callback is handled from clang.EmitOMPSectionDirective()2090// -> OMP.createSection() which generates the IR for each section2091// Iterate through all sections and emit a switch construct:2092// switch (IV) {2093// case 0:2094// <SectionStmt[0]>;2095// break;2096// ...2097// case <NumSection> - 1:2098// <SectionStmt[<NumSection> - 1]>;2099// break;2100// }2101// ...2102// section_loop.after:2103// <FiniCB>;2104auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, Value *IndVar) {2105Builder.restoreIP(CodeGenIP);2106BasicBlock *Continue =2107splitBBWithSuffix(Builder, /*CreateBranch=*/false, ".sections.after");2108Function *CurFn = Continue->getParent();2109SwitchInst *SwitchStmt = Builder.CreateSwitch(IndVar, Continue);21102111unsigned CaseNumber = 0;2112for (auto SectionCB : SectionCBs) {2113BasicBlock *CaseBB = BasicBlock::Create(2114M.getContext(), "omp_section_loop.body.case", CurFn, Continue);2115SwitchStmt->addCase(Builder.getInt32(CaseNumber), CaseBB);2116Builder.SetInsertPoint(CaseBB);2117BranchInst *CaseEndBr = Builder.CreateBr(Continue);2118SectionCB(InsertPointTy(),2119{CaseEndBr->getParent(), CaseEndBr->getIterator()});2120CaseNumber++;2121}2122// remove the existing terminator from body BB since there can be no2123// terminators after switch/case2124};2125// Loop body ends here2126// LowerBound, UpperBound, and STride for createCanonicalLoop2127Type *I32Ty = Type::getInt32Ty(M.getContext());2128Value *LB = ConstantInt::get(I32Ty, 0);2129Value *UB = ConstantInt::get(I32Ty, SectionCBs.size());2130Value *ST = ConstantInt::get(I32Ty, 1);2131llvm::CanonicalLoopInfo *LoopInfo = createCanonicalLoop(2132Loc, LoopBodyGenCB, LB, UB, ST, true, false, AllocaIP, "section_loop");2133InsertPointTy AfterIP =2134applyStaticWorkshareLoop(Loc.DL, LoopInfo, AllocaIP, !IsNowait);21352136// Apply the finalization callback in LoopAfterBB2137auto FiniInfo = FinalizationStack.pop_back_val();2138assert(FiniInfo.DK == OMPD_sections &&2139"Unexpected finalization stack state!");2140if (FinalizeCallbackTy &CB = FiniInfo.FiniCB) {2141Builder.restoreIP(AfterIP);2142BasicBlock *FiniBB =2143splitBBWithSuffix(Builder, /*CreateBranch=*/true, "sections.fini");2144CB(Builder.saveIP());2145AfterIP = {FiniBB, FiniBB->begin()};2146}21472148return AfterIP;2149}21502151OpenMPIRBuilder::InsertPointTy2152OpenMPIRBuilder::createSection(const LocationDescription &Loc,2153BodyGenCallbackTy BodyGenCB,2154FinalizeCallbackTy FiniCB) {2155if (!updateToLocation(Loc))2156return Loc.IP;21572158auto FiniCBWrapper = [&](InsertPointTy IP) {2159if (IP.getBlock()->end() != IP.getPoint())2160return FiniCB(IP);2161// This must be done otherwise any nested constructs using FinalizeOMPRegion2162// will fail because that function requires the Finalization Basic Block to2163// have a terminator, which is already removed by EmitOMPRegionBody.2164// IP is currently at cancelation block.2165// We need to backtrack to the condition block to fetch2166// the exit block and create a branch from cancelation2167// to exit block.2168IRBuilder<>::InsertPointGuard IPG(Builder);2169Builder.restoreIP(IP);2170auto *CaseBB = Loc.IP.getBlock();2171auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();2172auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);2173Instruction *I = Builder.CreateBr(ExitBB);2174IP = InsertPointTy(I->getParent(), I->getIterator());2175return FiniCB(IP);2176};21772178Directive OMPD = Directive::OMPD_sections;2179// Since we are using Finalization Callback here, HasFinalize2180// and IsCancellable have to be true2181return EmitOMPInlinedRegion(OMPD, nullptr, nullptr, BodyGenCB, FiniCBWrapper,2182/*Conditional*/ false, /*hasFinalize*/ true,2183/*IsCancellable*/ true);2184}21852186static OpenMPIRBuilder::InsertPointTy getInsertPointAfterInstr(Instruction *I) {2187BasicBlock::iterator IT(I);2188IT++;2189return OpenMPIRBuilder::InsertPointTy(I->getParent(), IT);2190}21912192void OpenMPIRBuilder::emitUsed(StringRef Name,2193std::vector<WeakTrackingVH> &List) {2194if (List.empty())2195return;21962197// Convert List to what ConstantArray needs.2198SmallVector<Constant *, 8> UsedArray;2199UsedArray.resize(List.size());2200for (unsigned I = 0, E = List.size(); I != E; ++I)2201UsedArray[I] = ConstantExpr::getPointerBitCastOrAddrSpaceCast(2202cast<Constant>(&*List[I]), Builder.getPtrTy());22032204if (UsedArray.empty())2205return;2206ArrayType *ATy = ArrayType::get(Builder.getPtrTy(), UsedArray.size());22072208auto *GV = new GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,2209ConstantArray::get(ATy, UsedArray), Name);22102211GV->setSection("llvm.metadata");2212}22132214Value *OpenMPIRBuilder::getGPUThreadID() {2215return Builder.CreateCall(2216getOrCreateRuntimeFunction(M,2217OMPRTL___kmpc_get_hardware_thread_id_in_block),2218{});2219}22202221Value *OpenMPIRBuilder::getGPUWarpSize() {2222return Builder.CreateCall(2223getOrCreateRuntimeFunction(M, OMPRTL___kmpc_get_warp_size), {});2224}22252226Value *OpenMPIRBuilder::getNVPTXWarpID() {2227unsigned LaneIDBits = Log2_32(Config.getGridValue().GV_Warp_Size);2228return Builder.CreateAShr(getGPUThreadID(), LaneIDBits, "nvptx_warp_id");2229}22302231Value *OpenMPIRBuilder::getNVPTXLaneID() {2232unsigned LaneIDBits = Log2_32(Config.getGridValue().GV_Warp_Size);2233assert(LaneIDBits < 32 && "Invalid LaneIDBits size in NVPTX device.");2234unsigned LaneIDMask = ~0u >> (32u - LaneIDBits);2235return Builder.CreateAnd(getGPUThreadID(), Builder.getInt32(LaneIDMask),2236"nvptx_lane_id");2237}22382239Value *OpenMPIRBuilder::castValueToType(InsertPointTy AllocaIP, Value *From,2240Type *ToType) {2241Type *FromType = From->getType();2242uint64_t FromSize = M.getDataLayout().getTypeStoreSize(FromType);2243uint64_t ToSize = M.getDataLayout().getTypeStoreSize(ToType);2244assert(FromSize > 0 && "From size must be greater than zero");2245assert(ToSize > 0 && "To size must be greater than zero");2246if (FromType == ToType)2247return From;2248if (FromSize == ToSize)2249return Builder.CreateBitCast(From, ToType);2250if (ToType->isIntegerTy() && FromType->isIntegerTy())2251return Builder.CreateIntCast(From, ToType, /*isSigned*/ true);2252InsertPointTy SaveIP = Builder.saveIP();2253Builder.restoreIP(AllocaIP);2254Value *CastItem = Builder.CreateAlloca(ToType);2255Builder.restoreIP(SaveIP);22562257Value *ValCastItem = Builder.CreatePointerBitCastOrAddrSpaceCast(2258CastItem, FromType->getPointerTo());2259Builder.CreateStore(From, ValCastItem);2260return Builder.CreateLoad(ToType, CastItem);2261}22622263Value *OpenMPIRBuilder::createRuntimeShuffleFunction(InsertPointTy AllocaIP,2264Value *Element,2265Type *ElementType,2266Value *Offset) {2267uint64_t Size = M.getDataLayout().getTypeStoreSize(ElementType);2268assert(Size <= 8 && "Unsupported bitwidth in shuffle instruction");22692270// Cast all types to 32- or 64-bit values before calling shuffle routines.2271Type *CastTy = Builder.getIntNTy(Size <= 4 ? 32 : 64);2272Value *ElemCast = castValueToType(AllocaIP, Element, CastTy);2273Value *WarpSize =2274Builder.CreateIntCast(getGPUWarpSize(), Builder.getInt16Ty(), true);2275Function *ShuffleFunc = getOrCreateRuntimeFunctionPtr(2276Size <= 4 ? RuntimeFunction::OMPRTL___kmpc_shuffle_int322277: RuntimeFunction::OMPRTL___kmpc_shuffle_int64);2278Value *WarpSizeCast =2279Builder.CreateIntCast(WarpSize, Builder.getInt16Ty(), /*isSigned=*/true);2280Value *ShuffleCall =2281Builder.CreateCall(ShuffleFunc, {ElemCast, Offset, WarpSizeCast});2282return castValueToType(AllocaIP, ShuffleCall, CastTy);2283}22842285void OpenMPIRBuilder::shuffleAndStore(InsertPointTy AllocaIP, Value *SrcAddr,2286Value *DstAddr, Type *ElemType,2287Value *Offset, Type *ReductionArrayTy) {2288uint64_t Size = M.getDataLayout().getTypeStoreSize(ElemType);2289// Create the loop over the big sized data.2290// ptr = (void*)Elem;2291// ptrEnd = (void*) Elem + 1;2292// Step = 8;2293// while (ptr + Step < ptrEnd)2294// shuffle((int64_t)*ptr);2295// Step = 4;2296// while (ptr + Step < ptrEnd)2297// shuffle((int32_t)*ptr);2298// ...2299Type *IndexTy = Builder.getIndexTy(2300M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());2301Value *ElemPtr = DstAddr;2302Value *Ptr = SrcAddr;2303for (unsigned IntSize = 8; IntSize >= 1; IntSize /= 2) {2304if (Size < IntSize)2305continue;2306Type *IntType = Builder.getIntNTy(IntSize * 8);2307Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(2308Ptr, IntType->getPointerTo(), Ptr->getName() + ".ascast");2309Value *SrcAddrGEP =2310Builder.CreateGEP(ElemType, SrcAddr, {ConstantInt::get(IndexTy, 1)});2311ElemPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(2312ElemPtr, IntType->getPointerTo(), ElemPtr->getName() + ".ascast");23132314Function *CurFunc = Builder.GetInsertBlock()->getParent();2315if ((Size / IntSize) > 1) {2316Value *PtrEnd = Builder.CreatePointerBitCastOrAddrSpaceCast(2317SrcAddrGEP, Builder.getPtrTy());2318BasicBlock *PreCondBB =2319BasicBlock::Create(M.getContext(), ".shuffle.pre_cond");2320BasicBlock *ThenBB = BasicBlock::Create(M.getContext(), ".shuffle.then");2321BasicBlock *ExitBB = BasicBlock::Create(M.getContext(), ".shuffle.exit");2322BasicBlock *CurrentBB = Builder.GetInsertBlock();2323emitBlock(PreCondBB, CurFunc);2324PHINode *PhiSrc =2325Builder.CreatePHI(Ptr->getType(), /*NumReservedValues=*/2);2326PhiSrc->addIncoming(Ptr, CurrentBB);2327PHINode *PhiDest =2328Builder.CreatePHI(ElemPtr->getType(), /*NumReservedValues=*/2);2329PhiDest->addIncoming(ElemPtr, CurrentBB);2330Ptr = PhiSrc;2331ElemPtr = PhiDest;2332Value *PtrDiff = Builder.CreatePtrDiff(2333Builder.getInt8Ty(), PtrEnd,2334Builder.CreatePointerBitCastOrAddrSpaceCast(Ptr, Builder.getPtrTy()));2335Builder.CreateCondBr(2336Builder.CreateICmpSGT(PtrDiff, Builder.getInt64(IntSize - 1)), ThenBB,2337ExitBB);2338emitBlock(ThenBB, CurFunc);2339Value *Res = createRuntimeShuffleFunction(2340AllocaIP,2341Builder.CreateAlignedLoad(2342IntType, Ptr, M.getDataLayout().getPrefTypeAlign(ElemType)),2343IntType, Offset);2344Builder.CreateAlignedStore(Res, ElemPtr,2345M.getDataLayout().getPrefTypeAlign(ElemType));2346Value *LocalPtr =2347Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});2348Value *LocalElemPtr =2349Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});2350PhiSrc->addIncoming(LocalPtr, ThenBB);2351PhiDest->addIncoming(LocalElemPtr, ThenBB);2352emitBranch(PreCondBB);2353emitBlock(ExitBB, CurFunc);2354} else {2355Value *Res = createRuntimeShuffleFunction(2356AllocaIP, Builder.CreateLoad(IntType, Ptr), IntType, Offset);2357if (ElemType->isIntegerTy() && ElemType->getScalarSizeInBits() <2358Res->getType()->getScalarSizeInBits())2359Res = Builder.CreateTrunc(Res, ElemType);2360Builder.CreateStore(Res, ElemPtr);2361Ptr = Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});2362ElemPtr =2363Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});2364}2365Size = Size % IntSize;2366}2367}23682369void OpenMPIRBuilder::emitReductionListCopy(2370InsertPointTy AllocaIP, CopyAction Action, Type *ReductionArrayTy,2371ArrayRef<ReductionInfo> ReductionInfos, Value *SrcBase, Value *DestBase,2372CopyOptionsTy CopyOptions) {2373Type *IndexTy = Builder.getIndexTy(2374M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());2375Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;23762377// Iterates, element-by-element, through the source Reduce list and2378// make a copy.2379for (auto En : enumerate(ReductionInfos)) {2380const ReductionInfo &RI = En.value();2381Value *SrcElementAddr = nullptr;2382Value *DestElementAddr = nullptr;2383Value *DestElementPtrAddr = nullptr;2384// Should we shuffle in an element from a remote lane?2385bool ShuffleInElement = false;2386// Set to true to update the pointer in the dest Reduce list to a2387// newly created element.2388bool UpdateDestListPtr = false;23892390// Step 1.1: Get the address for the src element in the Reduce list.2391Value *SrcElementPtrAddr = Builder.CreateInBoundsGEP(2392ReductionArrayTy, SrcBase,2393{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});2394SrcElementAddr = Builder.CreateLoad(Builder.getPtrTy(), SrcElementPtrAddr);23952396// Step 1.2: Create a temporary to store the element in the destination2397// Reduce list.2398DestElementPtrAddr = Builder.CreateInBoundsGEP(2399ReductionArrayTy, DestBase,2400{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});2401switch (Action) {2402case CopyAction::RemoteLaneToThread: {2403InsertPointTy CurIP = Builder.saveIP();2404Builder.restoreIP(AllocaIP);2405AllocaInst *DestAlloca = Builder.CreateAlloca(RI.ElementType, nullptr,2406".omp.reduction.element");2407DestAlloca->setAlignment(2408M.getDataLayout().getPrefTypeAlign(RI.ElementType));2409DestElementAddr = DestAlloca;2410DestElementAddr =2411Builder.CreateAddrSpaceCast(DestElementAddr, Builder.getPtrTy(),2412DestElementAddr->getName() + ".ascast");2413Builder.restoreIP(CurIP);2414ShuffleInElement = true;2415UpdateDestListPtr = true;2416break;2417}2418case CopyAction::ThreadCopy: {2419DestElementAddr =2420Builder.CreateLoad(Builder.getPtrTy(), DestElementPtrAddr);2421break;2422}2423}24242425// Now that all active lanes have read the element in the2426// Reduce list, shuffle over the value from the remote lane.2427if (ShuffleInElement) {2428shuffleAndStore(AllocaIP, SrcElementAddr, DestElementAddr, RI.ElementType,2429RemoteLaneOffset, ReductionArrayTy);2430} else {2431switch (RI.EvaluationKind) {2432case EvalKind::Scalar: {2433Value *Elem = Builder.CreateLoad(RI.ElementType, SrcElementAddr);2434// Store the source element value to the dest element address.2435Builder.CreateStore(Elem, DestElementAddr);2436break;2437}2438case EvalKind::Complex: {2439Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(2440RI.ElementType, SrcElementAddr, 0, 0, ".realp");2441Value *SrcReal = Builder.CreateLoad(2442RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");2443Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(2444RI.ElementType, SrcElementAddr, 0, 1, ".imagp");2445Value *SrcImg = Builder.CreateLoad(2446RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");24472448Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(2449RI.ElementType, DestElementAddr, 0, 0, ".realp");2450Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(2451RI.ElementType, DestElementAddr, 0, 1, ".imagp");2452Builder.CreateStore(SrcReal, DestRealPtr);2453Builder.CreateStore(SrcImg, DestImgPtr);2454break;2455}2456case EvalKind::Aggregate: {2457Value *SizeVal = Builder.getInt64(2458M.getDataLayout().getTypeStoreSize(RI.ElementType));2459Builder.CreateMemCpy(2460DestElementAddr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),2461SrcElementAddr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),2462SizeVal, false);2463break;2464}2465};2466}24672468// Step 3.1: Modify reference in dest Reduce list as needed.2469// Modifying the reference in Reduce list to point to the newly2470// created element. The element is live in the current function2471// scope and that of functions it invokes (i.e., reduce_function).2472// RemoteReduceData[i] = (void*)&RemoteElem2473if (UpdateDestListPtr) {2474Value *CastDestAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(2475DestElementAddr, Builder.getPtrTy(),2476DestElementAddr->getName() + ".ascast");2477Builder.CreateStore(CastDestAddr, DestElementPtrAddr);2478}2479}2480}24812482Function *OpenMPIRBuilder::emitInterWarpCopyFunction(2483const LocationDescription &Loc, ArrayRef<ReductionInfo> ReductionInfos,2484AttributeList FuncAttrs) {2485InsertPointTy SavedIP = Builder.saveIP();2486LLVMContext &Ctx = M.getContext();2487FunctionType *FuncTy = FunctionType::get(2488Builder.getVoidTy(), {Builder.getPtrTy(), Builder.getInt32Ty()},2489/* IsVarArg */ false);2490Function *WcFunc =2491Function::Create(FuncTy, GlobalVariable::InternalLinkage,2492"_omp_reduction_inter_warp_copy_func", &M);2493WcFunc->setAttributes(FuncAttrs);2494WcFunc->addParamAttr(0, Attribute::NoUndef);2495WcFunc->addParamAttr(1, Attribute::NoUndef);2496BasicBlock *EntryBB = BasicBlock::Create(M.getContext(), "entry", WcFunc);2497Builder.SetInsertPoint(EntryBB);24982499// ReduceList: thread local Reduce list.2500// At the stage of the computation when this function is called, partially2501// aggregated values reside in the first lane of every active warp.2502Argument *ReduceListArg = WcFunc->getArg(0);2503// NumWarps: number of warps active in the parallel region. This could2504// be smaller than 32 (max warps in a CTA) for partial block reduction.2505Argument *NumWarpsArg = WcFunc->getArg(1);25062507// This array is used as a medium to transfer, one reduce element at a time,2508// the data from the first lane of every warp to lanes in the first warp2509// in order to perform the final step of a reduction in a parallel region2510// (reduction across warps). The array is placed in NVPTX __shared__ memory2511// for reduced latency, as well as to have a distinct copy for concurrently2512// executing target regions. The array is declared with common linkage so2513// as to be shared across compilation units.2514StringRef TransferMediumName =2515"__openmp_nvptx_data_transfer_temporary_storage";2516GlobalVariable *TransferMedium = M.getGlobalVariable(TransferMediumName);2517unsigned WarpSize = Config.getGridValue().GV_Warp_Size;2518ArrayType *ArrayTy = ArrayType::get(Builder.getInt32Ty(), WarpSize);2519if (!TransferMedium) {2520TransferMedium = new GlobalVariable(2521M, ArrayTy, /*isConstant=*/false, GlobalVariable::WeakAnyLinkage,2522UndefValue::get(ArrayTy), TransferMediumName,2523/*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,2524/*AddressSpace=*/3);2525}25262527// Get the CUDA thread id of the current OpenMP thread on the GPU.2528Value *GPUThreadID = getGPUThreadID();2529// nvptx_lane_id = nvptx_id % warpsize2530Value *LaneID = getNVPTXLaneID();2531// nvptx_warp_id = nvptx_id / warpsize2532Value *WarpID = getNVPTXWarpID();25332534InsertPointTy AllocaIP =2535InsertPointTy(Builder.GetInsertBlock(),2536Builder.GetInsertBlock()->getFirstInsertionPt());2537Type *Arg0Type = ReduceListArg->getType();2538Type *Arg1Type = NumWarpsArg->getType();2539Builder.restoreIP(AllocaIP);2540AllocaInst *ReduceListAlloca = Builder.CreateAlloca(2541Arg0Type, nullptr, ReduceListArg->getName() + ".addr");2542AllocaInst *NumWarpsAlloca =2543Builder.CreateAlloca(Arg1Type, nullptr, NumWarpsArg->getName() + ".addr");2544Value *ReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2545ReduceListAlloca, Arg0Type, ReduceListAlloca->getName() + ".ascast");2546Value *NumWarpsAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2547NumWarpsAlloca, Arg1Type->getPointerTo(),2548NumWarpsAlloca->getName() + ".ascast");2549Builder.CreateStore(ReduceListArg, ReduceListAddrCast);2550Builder.CreateStore(NumWarpsArg, NumWarpsAddrCast);2551AllocaIP = getInsertPointAfterInstr(NumWarpsAlloca);2552InsertPointTy CodeGenIP =2553getInsertPointAfterInstr(&Builder.GetInsertBlock()->back());2554Builder.restoreIP(CodeGenIP);25552556Value *ReduceList =2557Builder.CreateLoad(Builder.getPtrTy(), ReduceListAddrCast);25582559for (auto En : enumerate(ReductionInfos)) {2560//2561// Warp master copies reduce element to transfer medium in __shared__2562// memory.2563//2564const ReductionInfo &RI = En.value();2565unsigned RealTySize = M.getDataLayout().getTypeAllocSize(RI.ElementType);2566for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /= 2) {2567Type *CType = Builder.getIntNTy(TySize * 8);25682569unsigned NumIters = RealTySize / TySize;2570if (NumIters == 0)2571continue;2572Value *Cnt = nullptr;2573Value *CntAddr = nullptr;2574BasicBlock *PrecondBB = nullptr;2575BasicBlock *ExitBB = nullptr;2576if (NumIters > 1) {2577CodeGenIP = Builder.saveIP();2578Builder.restoreIP(AllocaIP);2579CntAddr =2580Builder.CreateAlloca(Builder.getInt32Ty(), nullptr, ".cnt.addr");25812582CntAddr = Builder.CreateAddrSpaceCast(CntAddr, Builder.getPtrTy(),2583CntAddr->getName() + ".ascast");2584Builder.restoreIP(CodeGenIP);2585Builder.CreateStore(Constant::getNullValue(Builder.getInt32Ty()),2586CntAddr,2587/*Volatile=*/false);2588PrecondBB = BasicBlock::Create(Ctx, "precond");2589ExitBB = BasicBlock::Create(Ctx, "exit");2590BasicBlock *BodyBB = BasicBlock::Create(Ctx, "body");2591emitBlock(PrecondBB, Builder.GetInsertBlock()->getParent());2592Cnt = Builder.CreateLoad(Builder.getInt32Ty(), CntAddr,2593/*Volatile=*/false);2594Value *Cmp = Builder.CreateICmpULT(2595Cnt, ConstantInt::get(Builder.getInt32Ty(), NumIters));2596Builder.CreateCondBr(Cmp, BodyBB, ExitBB);2597emitBlock(BodyBB, Builder.GetInsertBlock()->getParent());2598}25992600// kmpc_barrier.2601createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),2602omp::Directive::OMPD_unknown,2603/* ForceSimpleCall */ false,2604/* CheckCancelFlag */ true);2605BasicBlock *ThenBB = BasicBlock::Create(Ctx, "then");2606BasicBlock *ElseBB = BasicBlock::Create(Ctx, "else");2607BasicBlock *MergeBB = BasicBlock::Create(Ctx, "ifcont");26082609// if (lane_id == 0)2610Value *IsWarpMaster = Builder.CreateIsNull(LaneID, "warp_master");2611Builder.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);2612emitBlock(ThenBB, Builder.GetInsertBlock()->getParent());26132614// Reduce element = LocalReduceList[i]2615auto *RedListArrayTy =2616ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());2617Type *IndexTy = Builder.getIndexTy(2618M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());2619Value *ElemPtrPtr =2620Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,2621{ConstantInt::get(IndexTy, 0),2622ConstantInt::get(IndexTy, En.index())});2623// elemptr = ((CopyType*)(elemptrptr)) + I2624Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);2625if (NumIters > 1)2626ElemPtr = Builder.CreateGEP(Builder.getInt32Ty(), ElemPtr, Cnt);26272628// Get pointer to location in transfer medium.2629// MediumPtr = &medium[warp_id]2630Value *MediumPtr = Builder.CreateInBoundsGEP(2631ArrayTy, TransferMedium, {Builder.getInt64(0), WarpID});2632// elem = *elemptr2633//*MediumPtr = elem2634Value *Elem = Builder.CreateLoad(CType, ElemPtr);2635// Store the source element value to the dest element address.2636Builder.CreateStore(Elem, MediumPtr,2637/*IsVolatile*/ true);2638Builder.CreateBr(MergeBB);26392640// else2641emitBlock(ElseBB, Builder.GetInsertBlock()->getParent());2642Builder.CreateBr(MergeBB);26432644// endif2645emitBlock(MergeBB, Builder.GetInsertBlock()->getParent());2646createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),2647omp::Directive::OMPD_unknown,2648/* ForceSimpleCall */ false,2649/* CheckCancelFlag */ true);26502651// Warp 0 copies reduce element from transfer medium2652BasicBlock *W0ThenBB = BasicBlock::Create(Ctx, "then");2653BasicBlock *W0ElseBB = BasicBlock::Create(Ctx, "else");2654BasicBlock *W0MergeBB = BasicBlock::Create(Ctx, "ifcont");26552656Value *NumWarpsVal =2657Builder.CreateLoad(Builder.getInt32Ty(), NumWarpsAddrCast);2658// Up to 32 threads in warp 0 are active.2659Value *IsActiveThread =2660Builder.CreateICmpULT(GPUThreadID, NumWarpsVal, "is_active_thread");2661Builder.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);26622663emitBlock(W0ThenBB, Builder.GetInsertBlock()->getParent());26642665// SecMediumPtr = &medium[tid]2666// SrcMediumVal = *SrcMediumPtr2667Value *SrcMediumPtrVal = Builder.CreateInBoundsGEP(2668ArrayTy, TransferMedium, {Builder.getInt64(0), GPUThreadID});2669// TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I2670Value *TargetElemPtrPtr =2671Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,2672{ConstantInt::get(IndexTy, 0),2673ConstantInt::get(IndexTy, En.index())});2674Value *TargetElemPtrVal =2675Builder.CreateLoad(Builder.getPtrTy(), TargetElemPtrPtr);2676Value *TargetElemPtr = TargetElemPtrVal;2677if (NumIters > 1)2678TargetElemPtr =2679Builder.CreateGEP(Builder.getInt32Ty(), TargetElemPtr, Cnt);26802681// *TargetElemPtr = SrcMediumVal;2682Value *SrcMediumValue =2683Builder.CreateLoad(CType, SrcMediumPtrVal, /*IsVolatile*/ true);2684Builder.CreateStore(SrcMediumValue, TargetElemPtr);2685Builder.CreateBr(W0MergeBB);26862687emitBlock(W0ElseBB, Builder.GetInsertBlock()->getParent());2688Builder.CreateBr(W0MergeBB);26892690emitBlock(W0MergeBB, Builder.GetInsertBlock()->getParent());26912692if (NumIters > 1) {2693Cnt = Builder.CreateNSWAdd(2694Cnt, ConstantInt::get(Builder.getInt32Ty(), /*V=*/1));2695Builder.CreateStore(Cnt, CntAddr, /*Volatile=*/false);26962697auto *CurFn = Builder.GetInsertBlock()->getParent();2698emitBranch(PrecondBB);2699emitBlock(ExitBB, CurFn);2700}2701RealTySize %= TySize;2702}2703}27042705Builder.CreateRetVoid();2706Builder.restoreIP(SavedIP);27072708return WcFunc;2709}27102711Function *OpenMPIRBuilder::emitShuffleAndReduceFunction(2712ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,2713AttributeList FuncAttrs) {2714LLVMContext &Ctx = M.getContext();2715FunctionType *FuncTy =2716FunctionType::get(Builder.getVoidTy(),2717{Builder.getPtrTy(), Builder.getInt16Ty(),2718Builder.getInt16Ty(), Builder.getInt16Ty()},2719/* IsVarArg */ false);2720Function *SarFunc =2721Function::Create(FuncTy, GlobalVariable::InternalLinkage,2722"_omp_reduction_shuffle_and_reduce_func", &M);2723SarFunc->setAttributes(FuncAttrs);2724SarFunc->addParamAttr(0, Attribute::NoUndef);2725SarFunc->addParamAttr(1, Attribute::NoUndef);2726SarFunc->addParamAttr(2, Attribute::NoUndef);2727SarFunc->addParamAttr(3, Attribute::NoUndef);2728SarFunc->addParamAttr(1, Attribute::SExt);2729SarFunc->addParamAttr(2, Attribute::SExt);2730SarFunc->addParamAttr(3, Attribute::SExt);2731BasicBlock *EntryBB = BasicBlock::Create(M.getContext(), "entry", SarFunc);2732Builder.SetInsertPoint(EntryBB);27332734// Thread local Reduce list used to host the values of data to be reduced.2735Argument *ReduceListArg = SarFunc->getArg(0);2736// Current lane id; could be logical.2737Argument *LaneIDArg = SarFunc->getArg(1);2738// Offset of the remote source lane relative to the current lane.2739Argument *RemoteLaneOffsetArg = SarFunc->getArg(2);2740// Algorithm version. This is expected to be known at compile time.2741Argument *AlgoVerArg = SarFunc->getArg(3);27422743Type *ReduceListArgType = ReduceListArg->getType();2744Type *LaneIDArgType = LaneIDArg->getType();2745Type *LaneIDArgPtrType = LaneIDArg->getType()->getPointerTo();2746Value *ReduceListAlloca = Builder.CreateAlloca(2747ReduceListArgType, nullptr, ReduceListArg->getName() + ".addr");2748Value *LaneIdAlloca = Builder.CreateAlloca(LaneIDArgType, nullptr,2749LaneIDArg->getName() + ".addr");2750Value *RemoteLaneOffsetAlloca = Builder.CreateAlloca(2751LaneIDArgType, nullptr, RemoteLaneOffsetArg->getName() + ".addr");2752Value *AlgoVerAlloca = Builder.CreateAlloca(LaneIDArgType, nullptr,2753AlgoVerArg->getName() + ".addr");2754ArrayType *RedListArrayTy =2755ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());27562757// Create a local thread-private variable to host the Reduce list2758// from a remote lane.2759Instruction *RemoteReductionListAlloca = Builder.CreateAlloca(2760RedListArrayTy, nullptr, ".omp.reduction.remote_reduce_list");27612762Value *ReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2763ReduceListAlloca, ReduceListArgType,2764ReduceListAlloca->getName() + ".ascast");2765Value *LaneIdAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2766LaneIdAlloca, LaneIDArgPtrType, LaneIdAlloca->getName() + ".ascast");2767Value *RemoteLaneOffsetAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2768RemoteLaneOffsetAlloca, LaneIDArgPtrType,2769RemoteLaneOffsetAlloca->getName() + ".ascast");2770Value *AlgoVerAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2771AlgoVerAlloca, LaneIDArgPtrType, AlgoVerAlloca->getName() + ".ascast");2772Value *RemoteListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2773RemoteReductionListAlloca, Builder.getPtrTy(),2774RemoteReductionListAlloca->getName() + ".ascast");27752776Builder.CreateStore(ReduceListArg, ReduceListAddrCast);2777Builder.CreateStore(LaneIDArg, LaneIdAddrCast);2778Builder.CreateStore(RemoteLaneOffsetArg, RemoteLaneOffsetAddrCast);2779Builder.CreateStore(AlgoVerArg, AlgoVerAddrCast);27802781Value *ReduceList = Builder.CreateLoad(ReduceListArgType, ReduceListAddrCast);2782Value *LaneId = Builder.CreateLoad(LaneIDArgType, LaneIdAddrCast);2783Value *RemoteLaneOffset =2784Builder.CreateLoad(LaneIDArgType, RemoteLaneOffsetAddrCast);2785Value *AlgoVer = Builder.CreateLoad(LaneIDArgType, AlgoVerAddrCast);27862787InsertPointTy AllocaIP = getInsertPointAfterInstr(RemoteReductionListAlloca);27882789// This loop iterates through the list of reduce elements and copies,2790// element by element, from a remote lane in the warp to RemoteReduceList,2791// hosted on the thread's stack.2792emitReductionListCopy(2793AllocaIP, CopyAction::RemoteLaneToThread, RedListArrayTy, ReductionInfos,2794ReduceList, RemoteListAddrCast, {RemoteLaneOffset, nullptr, nullptr});27952796// The actions to be performed on the Remote Reduce list is dependent2797// on the algorithm version.2798//2799// if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&2800// LaneId % 2 == 0 && Offset > 0):2801// do the reduction value aggregation2802//2803// The thread local variable Reduce list is mutated in place to host the2804// reduced data, which is the aggregated value produced from local and2805// remote lanes.2806//2807// Note that AlgoVer is expected to be a constant integer known at compile2808// time.2809// When AlgoVer==0, the first conjunction evaluates to true, making2810// the entire predicate true during compile time.2811// When AlgoVer==1, the second conjunction has only the second part to be2812// evaluated during runtime. Other conjunctions evaluates to false2813// during compile time.2814// When AlgoVer==2, the third conjunction has only the second part to be2815// evaluated during runtime. Other conjunctions evaluates to false2816// during compile time.2817Value *CondAlgo0 = Builder.CreateIsNull(AlgoVer);2818Value *Algo1 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(1));2819Value *LaneComp = Builder.CreateICmpULT(LaneId, RemoteLaneOffset);2820Value *CondAlgo1 = Builder.CreateAnd(Algo1, LaneComp);2821Value *Algo2 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(2));2822Value *LaneIdAnd1 = Builder.CreateAnd(LaneId, Builder.getInt16(1));2823Value *LaneIdComp = Builder.CreateIsNull(LaneIdAnd1);2824Value *Algo2AndLaneIdComp = Builder.CreateAnd(Algo2, LaneIdComp);2825Value *RemoteOffsetComp =2826Builder.CreateICmpSGT(RemoteLaneOffset, Builder.getInt16(0));2827Value *CondAlgo2 = Builder.CreateAnd(Algo2AndLaneIdComp, RemoteOffsetComp);2828Value *CA0OrCA1 = Builder.CreateOr(CondAlgo0, CondAlgo1);2829Value *CondReduce = Builder.CreateOr(CA0OrCA1, CondAlgo2);28302831BasicBlock *ThenBB = BasicBlock::Create(Ctx, "then");2832BasicBlock *ElseBB = BasicBlock::Create(Ctx, "else");2833BasicBlock *MergeBB = BasicBlock::Create(Ctx, "ifcont");28342835Builder.CreateCondBr(CondReduce, ThenBB, ElseBB);2836emitBlock(ThenBB, Builder.GetInsertBlock()->getParent());2837Value *LocalReduceListPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(2838ReduceList, Builder.getPtrTy());2839Value *RemoteReduceListPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(2840RemoteListAddrCast, Builder.getPtrTy());2841Builder.CreateCall(ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr})2842->addFnAttr(Attribute::NoUnwind);2843Builder.CreateBr(MergeBB);28442845emitBlock(ElseBB, Builder.GetInsertBlock()->getParent());2846Builder.CreateBr(MergeBB);28472848emitBlock(MergeBB, Builder.GetInsertBlock()->getParent());28492850// if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local2851// Reduce list.2852Algo1 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(1));2853Value *LaneIdGtOffset = Builder.CreateICmpUGE(LaneId, RemoteLaneOffset);2854Value *CondCopy = Builder.CreateAnd(Algo1, LaneIdGtOffset);28552856BasicBlock *CpyThenBB = BasicBlock::Create(Ctx, "then");2857BasicBlock *CpyElseBB = BasicBlock::Create(Ctx, "else");2858BasicBlock *CpyMergeBB = BasicBlock::Create(Ctx, "ifcont");2859Builder.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);28602861emitBlock(CpyThenBB, Builder.GetInsertBlock()->getParent());2862emitReductionListCopy(AllocaIP, CopyAction::ThreadCopy, RedListArrayTy,2863ReductionInfos, RemoteListAddrCast, ReduceList);2864Builder.CreateBr(CpyMergeBB);28652866emitBlock(CpyElseBB, Builder.GetInsertBlock()->getParent());2867Builder.CreateBr(CpyMergeBB);28682869emitBlock(CpyMergeBB, Builder.GetInsertBlock()->getParent());28702871Builder.CreateRetVoid();28722873return SarFunc;2874}28752876Function *OpenMPIRBuilder::emitListToGlobalCopyFunction(2877ArrayRef<ReductionInfo> ReductionInfos, Type *ReductionsBufferTy,2878AttributeList FuncAttrs) {2879OpenMPIRBuilder::InsertPointTy OldIP = Builder.saveIP();2880LLVMContext &Ctx = M.getContext();2881FunctionType *FuncTy = FunctionType::get(2882Builder.getVoidTy(),2883{Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},2884/* IsVarArg */ false);2885Function *LtGCFunc =2886Function::Create(FuncTy, GlobalVariable::InternalLinkage,2887"_omp_reduction_list_to_global_copy_func", &M);2888LtGCFunc->setAttributes(FuncAttrs);2889LtGCFunc->addParamAttr(0, Attribute::NoUndef);2890LtGCFunc->addParamAttr(1, Attribute::NoUndef);2891LtGCFunc->addParamAttr(2, Attribute::NoUndef);28922893BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", LtGCFunc);2894Builder.SetInsertPoint(EntryBlock);28952896// Buffer: global reduction buffer.2897Argument *BufferArg = LtGCFunc->getArg(0);2898// Idx: index of the buffer.2899Argument *IdxArg = LtGCFunc->getArg(1);2900// ReduceList: thread local Reduce list.2901Argument *ReduceListArg = LtGCFunc->getArg(2);29022903Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,2904BufferArg->getName() + ".addr");2905Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,2906IdxArg->getName() + ".addr");2907Value *ReduceListArgAlloca = Builder.CreateAlloca(2908Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");2909Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2910BufferArgAlloca, Builder.getPtrTy(),2911BufferArgAlloca->getName() + ".ascast");2912Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2913IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");2914Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(2915ReduceListArgAlloca, Builder.getPtrTy(),2916ReduceListArgAlloca->getName() + ".ascast");29172918Builder.CreateStore(BufferArg, BufferArgAddrCast);2919Builder.CreateStore(IdxArg, IdxArgAddrCast);2920Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);29212922Value *LocalReduceList =2923Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);2924Value *BufferArgVal =2925Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);2926Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};2927Type *IndexTy = Builder.getIndexTy(2928M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());2929for (auto En : enumerate(ReductionInfos)) {2930const ReductionInfo &RI = En.value();2931auto *RedListArrayTy =2932ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());2933// Reduce element = LocalReduceList[i]2934Value *ElemPtrPtr = Builder.CreateInBoundsGEP(2935RedListArrayTy, LocalReduceList,2936{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});2937// elemptr = ((CopyType*)(elemptrptr)) + I2938Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);29392940// Global = Buffer.VD[Idx];2941Value *BufferVD =2942Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferArgVal, Idxs);2943Value *GlobVal = Builder.CreateConstInBoundsGEP2_32(2944ReductionsBufferTy, BufferVD, 0, En.index());29452946switch (RI.EvaluationKind) {2947case EvalKind::Scalar: {2948Value *TargetElement = Builder.CreateLoad(RI.ElementType, ElemPtr);2949Builder.CreateStore(TargetElement, GlobVal);2950break;2951}2952case EvalKind::Complex: {2953Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(2954RI.ElementType, ElemPtr, 0, 0, ".realp");2955Value *SrcReal = Builder.CreateLoad(2956RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");2957Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(2958RI.ElementType, ElemPtr, 0, 1, ".imagp");2959Value *SrcImg = Builder.CreateLoad(2960RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");29612962Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(2963RI.ElementType, GlobVal, 0, 0, ".realp");2964Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(2965RI.ElementType, GlobVal, 0, 1, ".imagp");2966Builder.CreateStore(SrcReal, DestRealPtr);2967Builder.CreateStore(SrcImg, DestImgPtr);2968break;2969}2970case EvalKind::Aggregate: {2971Value *SizeVal =2972Builder.getInt64(M.getDataLayout().getTypeStoreSize(RI.ElementType));2973Builder.CreateMemCpy(2974GlobVal, M.getDataLayout().getPrefTypeAlign(RI.ElementType), ElemPtr,2975M.getDataLayout().getPrefTypeAlign(RI.ElementType), SizeVal, false);2976break;2977}2978}2979}29802981Builder.CreateRetVoid();2982Builder.restoreIP(OldIP);2983return LtGCFunc;2984}29852986Function *OpenMPIRBuilder::emitListToGlobalReduceFunction(2987ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,2988Type *ReductionsBufferTy, AttributeList FuncAttrs) {2989OpenMPIRBuilder::InsertPointTy OldIP = Builder.saveIP();2990LLVMContext &Ctx = M.getContext();2991FunctionType *FuncTy = FunctionType::get(2992Builder.getVoidTy(),2993{Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},2994/* IsVarArg */ false);2995Function *LtGRFunc =2996Function::Create(FuncTy, GlobalVariable::InternalLinkage,2997"_omp_reduction_list_to_global_reduce_func", &M);2998LtGRFunc->setAttributes(FuncAttrs);2999LtGRFunc->addParamAttr(0, Attribute::NoUndef);3000LtGRFunc->addParamAttr(1, Attribute::NoUndef);3001LtGRFunc->addParamAttr(2, Attribute::NoUndef);30023003BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", LtGRFunc);3004Builder.SetInsertPoint(EntryBlock);30053006// Buffer: global reduction buffer.3007Argument *BufferArg = LtGRFunc->getArg(0);3008// Idx: index of the buffer.3009Argument *IdxArg = LtGRFunc->getArg(1);3010// ReduceList: thread local Reduce list.3011Argument *ReduceListArg = LtGRFunc->getArg(2);30123013Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,3014BufferArg->getName() + ".addr");3015Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,3016IdxArg->getName() + ".addr");3017Value *ReduceListArgAlloca = Builder.CreateAlloca(3018Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");3019auto *RedListArrayTy =3020ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());30213022// 1. Build a list of reduction variables.3023// void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};3024Value *LocalReduceList =3025Builder.CreateAlloca(RedListArrayTy, nullptr, ".omp.reduction.red_list");30263027Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3028BufferArgAlloca, Builder.getPtrTy(),3029BufferArgAlloca->getName() + ".ascast");3030Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3031IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");3032Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3033ReduceListArgAlloca, Builder.getPtrTy(),3034ReduceListArgAlloca->getName() + ".ascast");3035Value *LocalReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3036LocalReduceList, Builder.getPtrTy(),3037LocalReduceList->getName() + ".ascast");30383039Builder.CreateStore(BufferArg, BufferArgAddrCast);3040Builder.CreateStore(IdxArg, IdxArgAddrCast);3041Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);30423043Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);3044Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};3045Type *IndexTy = Builder.getIndexTy(3046M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());3047for (auto En : enumerate(ReductionInfos)) {3048Value *TargetElementPtrPtr = Builder.CreateInBoundsGEP(3049RedListArrayTy, LocalReduceListAddrCast,3050{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});3051Value *BufferVD =3052Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);3053// Global = Buffer.VD[Idx];3054Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(3055ReductionsBufferTy, BufferVD, 0, En.index());3056Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);3057}30583059// Call reduce_function(GlobalReduceList, ReduceList)3060Value *ReduceList =3061Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);3062Builder.CreateCall(ReduceFn, {LocalReduceListAddrCast, ReduceList})3063->addFnAttr(Attribute::NoUnwind);3064Builder.CreateRetVoid();3065Builder.restoreIP(OldIP);3066return LtGRFunc;3067}30683069Function *OpenMPIRBuilder::emitGlobalToListCopyFunction(3070ArrayRef<ReductionInfo> ReductionInfos, Type *ReductionsBufferTy,3071AttributeList FuncAttrs) {3072OpenMPIRBuilder::InsertPointTy OldIP = Builder.saveIP();3073LLVMContext &Ctx = M.getContext();3074FunctionType *FuncTy = FunctionType::get(3075Builder.getVoidTy(),3076{Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},3077/* IsVarArg */ false);3078Function *LtGCFunc =3079Function::Create(FuncTy, GlobalVariable::InternalLinkage,3080"_omp_reduction_global_to_list_copy_func", &M);3081LtGCFunc->setAttributes(FuncAttrs);3082LtGCFunc->addParamAttr(0, Attribute::NoUndef);3083LtGCFunc->addParamAttr(1, Attribute::NoUndef);3084LtGCFunc->addParamAttr(2, Attribute::NoUndef);30853086BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", LtGCFunc);3087Builder.SetInsertPoint(EntryBlock);30883089// Buffer: global reduction buffer.3090Argument *BufferArg = LtGCFunc->getArg(0);3091// Idx: index of the buffer.3092Argument *IdxArg = LtGCFunc->getArg(1);3093// ReduceList: thread local Reduce list.3094Argument *ReduceListArg = LtGCFunc->getArg(2);30953096Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,3097BufferArg->getName() + ".addr");3098Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,3099IdxArg->getName() + ".addr");3100Value *ReduceListArgAlloca = Builder.CreateAlloca(3101Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");3102Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3103BufferArgAlloca, Builder.getPtrTy(),3104BufferArgAlloca->getName() + ".ascast");3105Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3106IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");3107Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3108ReduceListArgAlloca, Builder.getPtrTy(),3109ReduceListArgAlloca->getName() + ".ascast");3110Builder.CreateStore(BufferArg, BufferArgAddrCast);3111Builder.CreateStore(IdxArg, IdxArgAddrCast);3112Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);31133114Value *LocalReduceList =3115Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);3116Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);3117Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};3118Type *IndexTy = Builder.getIndexTy(3119M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());3120for (auto En : enumerate(ReductionInfos)) {3121const OpenMPIRBuilder::ReductionInfo &RI = En.value();3122auto *RedListArrayTy =3123ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());3124// Reduce element = LocalReduceList[i]3125Value *ElemPtrPtr = Builder.CreateInBoundsGEP(3126RedListArrayTy, LocalReduceList,3127{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});3128// elemptr = ((CopyType*)(elemptrptr)) + I3129Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);3130// Global = Buffer.VD[Idx];3131Value *BufferVD =3132Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);3133Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(3134ReductionsBufferTy, BufferVD, 0, En.index());31353136switch (RI.EvaluationKind) {3137case EvalKind::Scalar: {3138Value *TargetElement = Builder.CreateLoad(RI.ElementType, GlobValPtr);3139Builder.CreateStore(TargetElement, ElemPtr);3140break;3141}3142case EvalKind::Complex: {3143Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(3144RI.ElementType, GlobValPtr, 0, 0, ".realp");3145Value *SrcReal = Builder.CreateLoad(3146RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");3147Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(3148RI.ElementType, GlobValPtr, 0, 1, ".imagp");3149Value *SrcImg = Builder.CreateLoad(3150RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");31513152Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(3153RI.ElementType, ElemPtr, 0, 0, ".realp");3154Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(3155RI.ElementType, ElemPtr, 0, 1, ".imagp");3156Builder.CreateStore(SrcReal, DestRealPtr);3157Builder.CreateStore(SrcImg, DestImgPtr);3158break;3159}3160case EvalKind::Aggregate: {3161Value *SizeVal =3162Builder.getInt64(M.getDataLayout().getTypeStoreSize(RI.ElementType));3163Builder.CreateMemCpy(3164ElemPtr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),3165GlobValPtr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),3166SizeVal, false);3167break;3168}3169}3170}31713172Builder.CreateRetVoid();3173Builder.restoreIP(OldIP);3174return LtGCFunc;3175}31763177Function *OpenMPIRBuilder::emitGlobalToListReduceFunction(3178ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,3179Type *ReductionsBufferTy, AttributeList FuncAttrs) {3180OpenMPIRBuilder::InsertPointTy OldIP = Builder.saveIP();3181LLVMContext &Ctx = M.getContext();3182auto *FuncTy = FunctionType::get(3183Builder.getVoidTy(),3184{Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},3185/* IsVarArg */ false);3186Function *LtGRFunc =3187Function::Create(FuncTy, GlobalVariable::InternalLinkage,3188"_omp_reduction_global_to_list_reduce_func", &M);3189LtGRFunc->setAttributes(FuncAttrs);3190LtGRFunc->addParamAttr(0, Attribute::NoUndef);3191LtGRFunc->addParamAttr(1, Attribute::NoUndef);3192LtGRFunc->addParamAttr(2, Attribute::NoUndef);31933194BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", LtGRFunc);3195Builder.SetInsertPoint(EntryBlock);31963197// Buffer: global reduction buffer.3198Argument *BufferArg = LtGRFunc->getArg(0);3199// Idx: index of the buffer.3200Argument *IdxArg = LtGRFunc->getArg(1);3201// ReduceList: thread local Reduce list.3202Argument *ReduceListArg = LtGRFunc->getArg(2);32033204Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,3205BufferArg->getName() + ".addr");3206Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,3207IdxArg->getName() + ".addr");3208Value *ReduceListArgAlloca = Builder.CreateAlloca(3209Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");3210ArrayType *RedListArrayTy =3211ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());32123213// 1. Build a list of reduction variables.3214// void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};3215Value *LocalReduceList =3216Builder.CreateAlloca(RedListArrayTy, nullptr, ".omp.reduction.red_list");32173218Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3219BufferArgAlloca, Builder.getPtrTy(),3220BufferArgAlloca->getName() + ".ascast");3221Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3222IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");3223Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3224ReduceListArgAlloca, Builder.getPtrTy(),3225ReduceListArgAlloca->getName() + ".ascast");3226Value *ReductionList = Builder.CreatePointerBitCastOrAddrSpaceCast(3227LocalReduceList, Builder.getPtrTy(),3228LocalReduceList->getName() + ".ascast");32293230Builder.CreateStore(BufferArg, BufferArgAddrCast);3231Builder.CreateStore(IdxArg, IdxArgAddrCast);3232Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);32333234Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);3235Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};3236Type *IndexTy = Builder.getIndexTy(3237M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());3238for (auto En : enumerate(ReductionInfos)) {3239Value *TargetElementPtrPtr = Builder.CreateInBoundsGEP(3240RedListArrayTy, ReductionList,3241{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});3242// Global = Buffer.VD[Idx];3243Value *BufferVD =3244Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);3245Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(3246ReductionsBufferTy, BufferVD, 0, En.index());3247Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);3248}32493250// Call reduce_function(ReduceList, GlobalReduceList)3251Value *ReduceList =3252Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);3253Builder.CreateCall(ReduceFn, {ReduceList, ReductionList})3254->addFnAttr(Attribute::NoUnwind);3255Builder.CreateRetVoid();3256Builder.restoreIP(OldIP);3257return LtGRFunc;3258}32593260std::string OpenMPIRBuilder::getReductionFuncName(StringRef Name) const {3261std::string Suffix =3262createPlatformSpecificName({"omp", "reduction", "reduction_func"});3263return (Name + Suffix).str();3264}32653266Function *OpenMPIRBuilder::createReductionFunction(3267StringRef ReducerName, ArrayRef<ReductionInfo> ReductionInfos,3268ReductionGenCBKind ReductionGenCBKind, AttributeList FuncAttrs) {3269auto *FuncTy = FunctionType::get(Builder.getVoidTy(),3270{Builder.getPtrTy(), Builder.getPtrTy()},3271/* IsVarArg */ false);3272std::string Name = getReductionFuncName(ReducerName);3273Function *ReductionFunc =3274Function::Create(FuncTy, GlobalVariable::InternalLinkage, Name, &M);3275ReductionFunc->setAttributes(FuncAttrs);3276ReductionFunc->addParamAttr(0, Attribute::NoUndef);3277ReductionFunc->addParamAttr(1, Attribute::NoUndef);3278BasicBlock *EntryBB =3279BasicBlock::Create(M.getContext(), "entry", ReductionFunc);3280Builder.SetInsertPoint(EntryBB);32813282// Need to alloca memory here and deal with the pointers before getting3283// LHS/RHS pointers out3284Value *LHSArrayPtr = nullptr;3285Value *RHSArrayPtr = nullptr;3286Argument *Arg0 = ReductionFunc->getArg(0);3287Argument *Arg1 = ReductionFunc->getArg(1);3288Type *Arg0Type = Arg0->getType();3289Type *Arg1Type = Arg1->getType();32903291Value *LHSAlloca =3292Builder.CreateAlloca(Arg0Type, nullptr, Arg0->getName() + ".addr");3293Value *RHSAlloca =3294Builder.CreateAlloca(Arg1Type, nullptr, Arg1->getName() + ".addr");3295Value *LHSAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3296LHSAlloca, Arg0Type, LHSAlloca->getName() + ".ascast");3297Value *RHSAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(3298RHSAlloca, Arg1Type, RHSAlloca->getName() + ".ascast");3299Builder.CreateStore(Arg0, LHSAddrCast);3300Builder.CreateStore(Arg1, RHSAddrCast);3301LHSArrayPtr = Builder.CreateLoad(Arg0Type, LHSAddrCast);3302RHSArrayPtr = Builder.CreateLoad(Arg1Type, RHSAddrCast);33033304Type *RedArrayTy = ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());3305Type *IndexTy = Builder.getIndexTy(3306M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());3307SmallVector<Value *> LHSPtrs, RHSPtrs;3308for (auto En : enumerate(ReductionInfos)) {3309const ReductionInfo &RI = En.value();3310Value *RHSI8PtrPtr = Builder.CreateInBoundsGEP(3311RedArrayTy, RHSArrayPtr,3312{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});3313Value *RHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), RHSI8PtrPtr);3314Value *RHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(3315RHSI8Ptr, RI.PrivateVariable->getType(),3316RHSI8Ptr->getName() + ".ascast");33173318Value *LHSI8PtrPtr = Builder.CreateInBoundsGEP(3319RedArrayTy, LHSArrayPtr,3320{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});3321Value *LHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), LHSI8PtrPtr);3322Value *LHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(3323LHSI8Ptr, RI.Variable->getType(), LHSI8Ptr->getName() + ".ascast");33243325if (ReductionGenCBKind == ReductionGenCBKind::Clang) {3326LHSPtrs.emplace_back(LHSPtr);3327RHSPtrs.emplace_back(RHSPtr);3328} else {3329Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);3330Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);3331Value *Reduced;3332RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced);3333if (!Builder.GetInsertBlock())3334return ReductionFunc;3335Builder.CreateStore(Reduced, LHSPtr);3336}3337}33383339if (ReductionGenCBKind == ReductionGenCBKind::Clang)3340for (auto En : enumerate(ReductionInfos)) {3341unsigned Index = En.index();3342const ReductionInfo &RI = En.value();3343Value *LHSFixupPtr, *RHSFixupPtr;3344Builder.restoreIP(RI.ReductionGenClang(3345Builder.saveIP(), Index, &LHSFixupPtr, &RHSFixupPtr, ReductionFunc));33463347// Fix the CallBack code genereated to use the correct Values for the LHS3348// and RHS3349LHSFixupPtr->replaceUsesWithIf(3350LHSPtrs[Index], [ReductionFunc](const Use &U) {3351return cast<Instruction>(U.getUser())->getParent()->getParent() ==3352ReductionFunc;3353});3354RHSFixupPtr->replaceUsesWithIf(3355RHSPtrs[Index], [ReductionFunc](const Use &U) {3356return cast<Instruction>(U.getUser())->getParent()->getParent() ==3357ReductionFunc;3358});3359}33603361Builder.CreateRetVoid();3362return ReductionFunc;3363}33643365static void3366checkReductionInfos(ArrayRef<OpenMPIRBuilder::ReductionInfo> ReductionInfos,3367bool IsGPU) {3368for (const OpenMPIRBuilder::ReductionInfo &RI : ReductionInfos) {3369(void)RI;3370assert(RI.Variable && "expected non-null variable");3371assert(RI.PrivateVariable && "expected non-null private variable");3372assert((RI.ReductionGen || RI.ReductionGenClang) &&3373"expected non-null reduction generator callback");3374if (!IsGPU) {3375assert(3376RI.Variable->getType() == RI.PrivateVariable->getType() &&3377"expected variables and their private equivalents to have the same "3378"type");3379}3380assert(RI.Variable->getType()->isPointerTy() &&3381"expected variables to be pointers");3382}3383}33843385OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createReductionsGPU(3386const LocationDescription &Loc, InsertPointTy AllocaIP,3387InsertPointTy CodeGenIP, ArrayRef<ReductionInfo> ReductionInfos,3388bool IsNoWait, bool IsTeamsReduction, bool HasDistribute,3389ReductionGenCBKind ReductionGenCBKind, std::optional<omp::GV> GridValue,3390unsigned ReductionBufNum, Value *SrcLocInfo) {3391if (!updateToLocation(Loc))3392return InsertPointTy();3393Builder.restoreIP(CodeGenIP);3394checkReductionInfos(ReductionInfos, /*IsGPU*/ true);3395LLVMContext &Ctx = M.getContext();33963397// Source location for the ident struct3398if (!SrcLocInfo) {3399uint32_t SrcLocStrSize;3400Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);3401SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);3402}34033404if (ReductionInfos.size() == 0)3405return Builder.saveIP();34063407Function *CurFunc = Builder.GetInsertBlock()->getParent();3408AttributeList FuncAttrs;3409AttrBuilder AttrBldr(Ctx);3410for (auto Attr : CurFunc->getAttributes().getFnAttrs())3411AttrBldr.addAttribute(Attr);3412AttrBldr.removeAttribute(Attribute::OptimizeNone);3413FuncAttrs = FuncAttrs.addFnAttributes(Ctx, AttrBldr);34143415Function *ReductionFunc = nullptr;3416CodeGenIP = Builder.saveIP();3417ReductionFunc =3418createReductionFunction(Builder.GetInsertBlock()->getParent()->getName(),3419ReductionInfos, ReductionGenCBKind, FuncAttrs);3420Builder.restoreIP(CodeGenIP);34213422// Set the grid value in the config needed for lowering later on3423if (GridValue.has_value())3424Config.setGridValue(GridValue.value());3425else3426Config.setGridValue(getGridValue(T, ReductionFunc));34273428uint32_t SrcLocStrSize;3429Constant *SrcLocStr = getOrCreateDefaultSrcLocStr(SrcLocStrSize);3430Value *RTLoc =3431getOrCreateIdent(SrcLocStr, SrcLocStrSize, omp::IdentFlag(0), 0);34323433// Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),3434// RedList, shuffle_reduce_func, interwarp_copy_func);3435// or3436// Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);3437Value *Res;34383439// 1. Build a list of reduction variables.3440// void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};3441auto Size = ReductionInfos.size();3442Type *PtrTy = PointerType::getUnqual(Ctx);3443Type *RedArrayTy = ArrayType::get(PtrTy, Size);3444CodeGenIP = Builder.saveIP();3445Builder.restoreIP(AllocaIP);3446Value *ReductionListAlloca =3447Builder.CreateAlloca(RedArrayTy, nullptr, ".omp.reduction.red_list");3448Value *ReductionList = Builder.CreatePointerBitCastOrAddrSpaceCast(3449ReductionListAlloca, PtrTy, ReductionListAlloca->getName() + ".ascast");3450Builder.restoreIP(CodeGenIP);3451Type *IndexTy = Builder.getIndexTy(3452M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());3453for (auto En : enumerate(ReductionInfos)) {3454const ReductionInfo &RI = En.value();3455Value *ElemPtr = Builder.CreateInBoundsGEP(3456RedArrayTy, ReductionList,3457{ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});3458Value *CastElem =3459Builder.CreatePointerBitCastOrAddrSpaceCast(RI.PrivateVariable, PtrTy);3460Builder.CreateStore(CastElem, ElemPtr);3461}3462CodeGenIP = Builder.saveIP();3463Function *SarFunc =3464emitShuffleAndReduceFunction(ReductionInfos, ReductionFunc, FuncAttrs);3465Function *WcFunc = emitInterWarpCopyFunction(Loc, ReductionInfos, FuncAttrs);3466Builder.restoreIP(CodeGenIP);34673468Value *RL = Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList, PtrTy);34693470unsigned MaxDataSize = 0;3471SmallVector<Type *> ReductionTypeArgs;3472for (auto En : enumerate(ReductionInfos)) {3473auto Size = M.getDataLayout().getTypeStoreSize(En.value().ElementType);3474if (Size > MaxDataSize)3475MaxDataSize = Size;3476ReductionTypeArgs.emplace_back(En.value().ElementType);3477}3478Value *ReductionDataSize =3479Builder.getInt64(MaxDataSize * ReductionInfos.size());3480if (!IsTeamsReduction) {3481Value *SarFuncCast =3482Builder.CreatePointerBitCastOrAddrSpaceCast(SarFunc, PtrTy);3483Value *WcFuncCast =3484Builder.CreatePointerBitCastOrAddrSpaceCast(WcFunc, PtrTy);3485Value *Args[] = {RTLoc, ReductionDataSize, RL, SarFuncCast, WcFuncCast};3486Function *Pv2Ptr = getOrCreateRuntimeFunctionPtr(3487RuntimeFunction::OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2);3488Res = Builder.CreateCall(Pv2Ptr, Args);3489} else {3490CodeGenIP = Builder.saveIP();3491StructType *ReductionsBufferTy = StructType::create(3492Ctx, ReductionTypeArgs, "struct._globalized_locals_ty");3493Function *RedFixedBuferFn = getOrCreateRuntimeFunctionPtr(3494RuntimeFunction::OMPRTL___kmpc_reduction_get_fixed_buffer);3495Function *LtGCFunc = emitListToGlobalCopyFunction(3496ReductionInfos, ReductionsBufferTy, FuncAttrs);3497Function *LtGRFunc = emitListToGlobalReduceFunction(3498ReductionInfos, ReductionFunc, ReductionsBufferTy, FuncAttrs);3499Function *GtLCFunc = emitGlobalToListCopyFunction(3500ReductionInfos, ReductionsBufferTy, FuncAttrs);3501Function *GtLRFunc = emitGlobalToListReduceFunction(3502ReductionInfos, ReductionFunc, ReductionsBufferTy, FuncAttrs);3503Builder.restoreIP(CodeGenIP);35043505Value *KernelTeamsReductionPtr = Builder.CreateCall(3506RedFixedBuferFn, {}, "_openmp_teams_reductions_buffer_$_$ptr");35073508Value *Args3[] = {RTLoc,3509KernelTeamsReductionPtr,3510Builder.getInt32(ReductionBufNum),3511ReductionDataSize,3512RL,3513SarFunc,3514WcFunc,3515LtGCFunc,3516LtGRFunc,3517GtLCFunc,3518GtLRFunc};35193520Function *TeamsReduceFn = getOrCreateRuntimeFunctionPtr(3521RuntimeFunction::OMPRTL___kmpc_nvptx_teams_reduce_nowait_v2);3522Res = Builder.CreateCall(TeamsReduceFn, Args3);3523}35243525// 5. Build if (res == 1)3526BasicBlock *ExitBB = BasicBlock::Create(Ctx, ".omp.reduction.done");3527BasicBlock *ThenBB = BasicBlock::Create(Ctx, ".omp.reduction.then");3528Value *Cond = Builder.CreateICmpEQ(Res, Builder.getInt32(1));3529Builder.CreateCondBr(Cond, ThenBB, ExitBB);35303531// 6. Build then branch: where we have reduced values in the master3532// thread in each team.3533// __kmpc_end_reduce{_nowait}(<gtid>);3534// break;3535emitBlock(ThenBB, CurFunc);35363537// Add emission of __kmpc_end_reduce{_nowait}(<gtid>);3538for (auto En : enumerate(ReductionInfos)) {3539const ReductionInfo &RI = En.value();3540Value *LHS = RI.Variable;3541Value *RHS =3542Builder.CreatePointerBitCastOrAddrSpaceCast(RI.PrivateVariable, PtrTy);35433544if (ReductionGenCBKind == ReductionGenCBKind::Clang) {3545Value *LHSPtr, *RHSPtr;3546Builder.restoreIP(RI.ReductionGenClang(Builder.saveIP(), En.index(),3547&LHSPtr, &RHSPtr, CurFunc));35483549// Fix the CallBack code genereated to use the correct Values for the LHS3550// and RHS3551LHSPtr->replaceUsesWithIf(LHS, [ReductionFunc](const Use &U) {3552return cast<Instruction>(U.getUser())->getParent()->getParent() ==3553ReductionFunc;3554});3555RHSPtr->replaceUsesWithIf(RHS, [ReductionFunc](const Use &U) {3556return cast<Instruction>(U.getUser())->getParent()->getParent() ==3557ReductionFunc;3558});3559} else {3560assert(false && "Unhandled ReductionGenCBKind");3561}3562}3563emitBlock(ExitBB, CurFunc);35643565Config.setEmitLLVMUsed();35663567return Builder.saveIP();3568}35693570static Function *getFreshReductionFunc(Module &M) {3571Type *VoidTy = Type::getVoidTy(M.getContext());3572Type *Int8PtrTy = PointerType::getUnqual(M.getContext());3573auto *FuncTy =3574FunctionType::get(VoidTy, {Int8PtrTy, Int8PtrTy}, /* IsVarArg */ false);3575return Function::Create(FuncTy, GlobalVariable::InternalLinkage,3576".omp.reduction.func", &M);3577}35783579OpenMPIRBuilder::InsertPointTy3580OpenMPIRBuilder::createReductions(const LocationDescription &Loc,3581InsertPointTy AllocaIP,3582ArrayRef<ReductionInfo> ReductionInfos,3583ArrayRef<bool> IsByRef, bool IsNoWait) {3584assert(ReductionInfos.size() == IsByRef.size());3585for (const ReductionInfo &RI : ReductionInfos) {3586(void)RI;3587assert(RI.Variable && "expected non-null variable");3588assert(RI.PrivateVariable && "expected non-null private variable");3589assert(RI.ReductionGen && "expected non-null reduction generator callback");3590assert(RI.Variable->getType() == RI.PrivateVariable->getType() &&3591"expected variables and their private equivalents to have the same "3592"type");3593assert(RI.Variable->getType()->isPointerTy() &&3594"expected variables to be pointers");3595}35963597if (!updateToLocation(Loc))3598return InsertPointTy();35993600BasicBlock *InsertBlock = Loc.IP.getBlock();3601BasicBlock *ContinuationBlock =3602InsertBlock->splitBasicBlock(Loc.IP.getPoint(), "reduce.finalize");3603InsertBlock->getTerminator()->eraseFromParent();36043605// Create and populate array of type-erased pointers to private reduction3606// values.3607unsigned NumReductions = ReductionInfos.size();3608Type *RedArrayTy = ArrayType::get(Builder.getPtrTy(), NumReductions);3609Builder.SetInsertPoint(AllocaIP.getBlock()->getTerminator());3610Value *RedArray = Builder.CreateAlloca(RedArrayTy, nullptr, "red.array");36113612Builder.SetInsertPoint(InsertBlock, InsertBlock->end());36133614for (auto En : enumerate(ReductionInfos)) {3615unsigned Index = En.index();3616const ReductionInfo &RI = En.value();3617Value *RedArrayElemPtr = Builder.CreateConstInBoundsGEP2_64(3618RedArrayTy, RedArray, 0, Index, "red.array.elem." + Twine(Index));3619Builder.CreateStore(RI.PrivateVariable, RedArrayElemPtr);3620}36213622// Emit a call to the runtime function that orchestrates the reduction.3623// Declare the reduction function in the process.3624Function *Func = Builder.GetInsertBlock()->getParent();3625Module *Module = Func->getParent();3626uint32_t SrcLocStrSize;3627Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);3628bool CanGenerateAtomic = all_of(ReductionInfos, [](const ReductionInfo &RI) {3629return RI.AtomicReductionGen;3630});3631Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize,3632CanGenerateAtomic3633? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE3634: IdentFlag(0));3635Value *ThreadId = getOrCreateThreadID(Ident);3636Constant *NumVariables = Builder.getInt32(NumReductions);3637const DataLayout &DL = Module->getDataLayout();3638unsigned RedArrayByteSize = DL.getTypeStoreSize(RedArrayTy);3639Constant *RedArraySize = Builder.getInt64(RedArrayByteSize);3640Function *ReductionFunc = getFreshReductionFunc(*Module);3641Value *Lock = getOMPCriticalRegionLock(".reduction");3642Function *ReduceFunc = getOrCreateRuntimeFunctionPtr(3643IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait3644: RuntimeFunction::OMPRTL___kmpc_reduce);3645CallInst *ReduceCall =3646Builder.CreateCall(ReduceFunc,3647{Ident, ThreadId, NumVariables, RedArraySize, RedArray,3648ReductionFunc, Lock},3649"reduce");36503651// Create final reduction entry blocks for the atomic and non-atomic case.3652// Emit IR that dispatches control flow to one of the blocks based on the3653// reduction supporting the atomic mode.3654BasicBlock *NonAtomicRedBlock =3655BasicBlock::Create(Module->getContext(), "reduce.switch.nonatomic", Func);3656BasicBlock *AtomicRedBlock =3657BasicBlock::Create(Module->getContext(), "reduce.switch.atomic", Func);3658SwitchInst *Switch =3659Builder.CreateSwitch(ReduceCall, ContinuationBlock, /* NumCases */ 2);3660Switch->addCase(Builder.getInt32(1), NonAtomicRedBlock);3661Switch->addCase(Builder.getInt32(2), AtomicRedBlock);36623663// Populate the non-atomic reduction using the elementwise reduction function.3664// This loads the elements from the global and private variables and reduces3665// them before storing back the result to the global variable.3666Builder.SetInsertPoint(NonAtomicRedBlock);3667for (auto En : enumerate(ReductionInfos)) {3668const ReductionInfo &RI = En.value();3669Type *ValueType = RI.ElementType;3670// We have one less load for by-ref case because that load is now inside of3671// the reduction region3672Value *RedValue = nullptr;3673if (!IsByRef[En.index()]) {3674RedValue = Builder.CreateLoad(ValueType, RI.Variable,3675"red.value." + Twine(En.index()));3676}3677Value *PrivateRedValue =3678Builder.CreateLoad(ValueType, RI.PrivateVariable,3679"red.private.value." + Twine(En.index()));3680Value *Reduced;3681if (IsByRef[En.index()]) {3682Builder.restoreIP(RI.ReductionGen(Builder.saveIP(), RI.Variable,3683PrivateRedValue, Reduced));3684} else {3685Builder.restoreIP(RI.ReductionGen(Builder.saveIP(), RedValue,3686PrivateRedValue, Reduced));3687}3688if (!Builder.GetInsertBlock())3689return InsertPointTy();3690// for by-ref case, the load is inside of the reduction region3691if (!IsByRef[En.index()])3692Builder.CreateStore(Reduced, RI.Variable);3693}3694Function *EndReduceFunc = getOrCreateRuntimeFunctionPtr(3695IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait3696: RuntimeFunction::OMPRTL___kmpc_end_reduce);3697Builder.CreateCall(EndReduceFunc, {Ident, ThreadId, Lock});3698Builder.CreateBr(ContinuationBlock);36993700// Populate the atomic reduction using the atomic elementwise reduction3701// function. There are no loads/stores here because they will be happening3702// inside the atomic elementwise reduction.3703Builder.SetInsertPoint(AtomicRedBlock);3704if (CanGenerateAtomic && llvm::none_of(IsByRef, [](bool P) { return P; })) {3705for (const ReductionInfo &RI : ReductionInfos) {3706Builder.restoreIP(RI.AtomicReductionGen(Builder.saveIP(), RI.ElementType,3707RI.Variable, RI.PrivateVariable));3708if (!Builder.GetInsertBlock())3709return InsertPointTy();3710}3711Builder.CreateBr(ContinuationBlock);3712} else {3713Builder.CreateUnreachable();3714}37153716// Populate the outlined reduction function using the elementwise reduction3717// function. Partial values are extracted from the type-erased array of3718// pointers to private variables.3719BasicBlock *ReductionFuncBlock =3720BasicBlock::Create(Module->getContext(), "", ReductionFunc);3721Builder.SetInsertPoint(ReductionFuncBlock);3722Value *LHSArrayPtr = ReductionFunc->getArg(0);3723Value *RHSArrayPtr = ReductionFunc->getArg(1);37243725for (auto En : enumerate(ReductionInfos)) {3726const ReductionInfo &RI = En.value();3727Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(3728RedArrayTy, LHSArrayPtr, 0, En.index());3729Value *LHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), LHSI8PtrPtr);3730Value *LHSPtr = Builder.CreateBitCast(LHSI8Ptr, RI.Variable->getType());3731Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);3732Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(3733RedArrayTy, RHSArrayPtr, 0, En.index());3734Value *RHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), RHSI8PtrPtr);3735Value *RHSPtr =3736Builder.CreateBitCast(RHSI8Ptr, RI.PrivateVariable->getType());3737Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);3738Value *Reduced;3739Builder.restoreIP(RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced));3740if (!Builder.GetInsertBlock())3741return InsertPointTy();3742// store is inside of the reduction region when using by-ref3743if (!IsByRef[En.index()])3744Builder.CreateStore(Reduced, LHSPtr);3745}3746Builder.CreateRetVoid();37473748Builder.SetInsertPoint(ContinuationBlock);3749return Builder.saveIP();3750}37513752OpenMPIRBuilder::InsertPointTy3753OpenMPIRBuilder::createMaster(const LocationDescription &Loc,3754BodyGenCallbackTy BodyGenCB,3755FinalizeCallbackTy FiniCB) {37563757if (!updateToLocation(Loc))3758return Loc.IP;37593760Directive OMPD = Directive::OMPD_master;3761uint32_t SrcLocStrSize;3762Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);3763Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);3764Value *ThreadId = getOrCreateThreadID(Ident);3765Value *Args[] = {Ident, ThreadId};37663767Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);3768Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);37693770Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);3771Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);37723773return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,3774/*Conditional*/ true, /*hasFinalize*/ true);3775}37763777OpenMPIRBuilder::InsertPointTy3778OpenMPIRBuilder::createMasked(const LocationDescription &Loc,3779BodyGenCallbackTy BodyGenCB,3780FinalizeCallbackTy FiniCB, Value *Filter) {3781if (!updateToLocation(Loc))3782return Loc.IP;37833784Directive OMPD = Directive::OMPD_masked;3785uint32_t SrcLocStrSize;3786Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);3787Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);3788Value *ThreadId = getOrCreateThreadID(Ident);3789Value *Args[] = {Ident, ThreadId, Filter};3790Value *ArgsEnd[] = {Ident, ThreadId};37913792Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);3793Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);37943795Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);3796Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, ArgsEnd);37973798return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,3799/*Conditional*/ true, /*hasFinalize*/ true);3800}38013802CanonicalLoopInfo *OpenMPIRBuilder::createLoopSkeleton(3803DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,3804BasicBlock *PostInsertBefore, const Twine &Name) {3805Module *M = F->getParent();3806LLVMContext &Ctx = M->getContext();3807Type *IndVarTy = TripCount->getType();38083809// Create the basic block structure.3810BasicBlock *Preheader =3811BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);3812BasicBlock *Header =3813BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);3814BasicBlock *Cond =3815BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);3816BasicBlock *Body =3817BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);3818BasicBlock *Latch =3819BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);3820BasicBlock *Exit =3821BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);3822BasicBlock *After =3823BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);38243825// Use specified DebugLoc for new instructions.3826Builder.SetCurrentDebugLocation(DL);38273828Builder.SetInsertPoint(Preheader);3829Builder.CreateBr(Header);38303831Builder.SetInsertPoint(Header);3832PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");3833IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);3834Builder.CreateBr(Cond);38353836Builder.SetInsertPoint(Cond);3837Value *Cmp =3838Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");3839Builder.CreateCondBr(Cmp, Body, Exit);38403841Builder.SetInsertPoint(Body);3842Builder.CreateBr(Latch);38433844Builder.SetInsertPoint(Latch);3845Value *Next = Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),3846"omp_" + Name + ".next", /*HasNUW=*/true);3847Builder.CreateBr(Header);3848IndVarPHI->addIncoming(Next, Latch);38493850Builder.SetInsertPoint(Exit);3851Builder.CreateBr(After);38523853// Remember and return the canonical control flow.3854LoopInfos.emplace_front();3855CanonicalLoopInfo *CL = &LoopInfos.front();38563857CL->Header = Header;3858CL->Cond = Cond;3859CL->Latch = Latch;3860CL->Exit = Exit;38613862#ifndef NDEBUG3863CL->assertOK();3864#endif3865return CL;3866}38673868CanonicalLoopInfo *3869OpenMPIRBuilder::createCanonicalLoop(const LocationDescription &Loc,3870LoopBodyGenCallbackTy BodyGenCB,3871Value *TripCount, const Twine &Name) {3872BasicBlock *BB = Loc.IP.getBlock();3873BasicBlock *NextBB = BB->getNextNode();38743875CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),3876NextBB, NextBB, Name);3877BasicBlock *After = CL->getAfter();38783879// If location is not set, don't connect the loop.3880if (updateToLocation(Loc)) {3881// Split the loop at the insertion point: Branch to the preheader and move3882// every following instruction to after the loop (the After BB). Also, the3883// new successor is the loop's after block.3884spliceBB(Builder, After, /*CreateBranch=*/false);3885Builder.CreateBr(CL->getPreheader());3886}38873888// Emit the body content. We do it after connecting the loop to the CFG to3889// avoid that the callback encounters degenerate BBs.3890BodyGenCB(CL->getBodyIP(), CL->getIndVar());38913892#ifndef NDEBUG3893CL->assertOK();3894#endif3895return CL;3896}38973898CanonicalLoopInfo *OpenMPIRBuilder::createCanonicalLoop(3899const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,3900Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,3901InsertPointTy ComputeIP, const Twine &Name) {39023903// Consider the following difficulties (assuming 8-bit signed integers):3904// * Adding \p Step to the loop counter which passes \p Stop may overflow:3905// DO I = 1, 100, 503906/// * A \p Step of INT_MIN cannot not be normalized to a positive direction:3907// DO I = 100, 0, -12839083909// Start, Stop and Step must be of the same integer type.3910auto *IndVarTy = cast<IntegerType>(Start->getType());3911assert(IndVarTy == Stop->getType() && "Stop type mismatch");3912assert(IndVarTy == Step->getType() && "Step type mismatch");39133914LocationDescription ComputeLoc =3915ComputeIP.isSet() ? LocationDescription(ComputeIP, Loc.DL) : Loc;3916updateToLocation(ComputeLoc);39173918ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);3919ConstantInt *One = ConstantInt::get(IndVarTy, 1);39203921// Like Step, but always positive.3922Value *Incr = Step;39233924// Distance between Start and Stop; always positive.3925Value *Span;39263927// Condition whether there are no iterations are executed at all, e.g. because3928// UB < LB.3929Value *ZeroCmp;39303931if (IsSigned) {3932// Ensure that increment is positive. If not, negate and invert LB and UB.3933Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);3934Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);3935Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);3936Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);3937Span = Builder.CreateSub(UB, LB, "", false, true);3938ZeroCmp = Builder.CreateICmp(3939InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);3940} else {3941Span = Builder.CreateSub(Stop, Start, "", true);3942ZeroCmp = Builder.CreateICmp(3943InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);3944}39453946Value *CountIfLooping;3947if (InclusiveStop) {3948CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);3949} else {3950// Avoid incrementing past stop since it could overflow.3951Value *CountIfTwo = Builder.CreateAdd(3952Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);3953Value *OneCmp = Builder.CreateICmp(CmpInst::ICMP_ULE, Span, Incr);3954CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);3955}3956Value *TripCount = Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,3957"omp_" + Name + ".tripcount");39583959auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {3960Builder.restoreIP(CodeGenIP);3961Value *Span = Builder.CreateMul(IV, Step);3962Value *IndVar = Builder.CreateAdd(Span, Start);3963BodyGenCB(Builder.saveIP(), IndVar);3964};3965LocationDescription LoopLoc = ComputeIP.isSet() ? Loc.IP : Builder.saveIP();3966return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);3967}39683969// Returns an LLVM function to call for initializing loop bounds using OpenMP3970// static scheduling depending on `type`. Only i32 and i64 are supported by the3971// runtime. Always interpret integers as unsigned similarly to3972// CanonicalLoopInfo.3973static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M,3974OpenMPIRBuilder &OMPBuilder) {3975unsigned Bitwidth = Ty->getIntegerBitWidth();3976if (Bitwidth == 32)3977return OMPBuilder.getOrCreateRuntimeFunction(3978M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);3979if (Bitwidth == 64)3980return OMPBuilder.getOrCreateRuntimeFunction(3981M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);3982llvm_unreachable("unknown OpenMP loop iterator bitwidth");3983}39843985OpenMPIRBuilder::InsertPointTy3986OpenMPIRBuilder::applyStaticWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,3987InsertPointTy AllocaIP,3988bool NeedsBarrier) {3989assert(CLI->isValid() && "Requires a valid canonical loop");3990assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&3991"Require dedicated allocate IP");39923993// Set up the source location value for OpenMP runtime.3994Builder.restoreIP(CLI->getPreheaderIP());3995Builder.SetCurrentDebugLocation(DL);39963997uint32_t SrcLocStrSize;3998Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);3999Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);40004001// Declare useful OpenMP runtime functions.4002Value *IV = CLI->getIndVar();4003Type *IVTy = IV->getType();4004FunctionCallee StaticInit = getKmpcForStaticInitForType(IVTy, M, *this);4005FunctionCallee StaticFini =4006getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);40074008// Allocate space for computed loop bounds as expected by the "init" function.4009Builder.SetInsertPoint(AllocaIP.getBlock()->getFirstNonPHIOrDbgOrAlloca());40104011Type *I32Type = Type::getInt32Ty(M.getContext());4012Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");4013Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");4014Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");4015Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");40164017// At the end of the preheader, prepare for calling the "init" function by4018// storing the current loop bounds into the allocated space. A canonical loop4019// always iterates from 0 to trip-count with step 1. Note that "init" expects4020// and produces an inclusive upper bound.4021Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());4022Constant *Zero = ConstantInt::get(IVTy, 0);4023Constant *One = ConstantInt::get(IVTy, 1);4024Builder.CreateStore(Zero, PLowerBound);4025Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);4026Builder.CreateStore(UpperBound, PUpperBound);4027Builder.CreateStore(One, PStride);40284029Value *ThreadNum = getOrCreateThreadID(SrcLoc);40304031Constant *SchedulingType = ConstantInt::get(4032I32Type, static_cast<int>(OMPScheduleType::UnorderedStatic));40334034// Call the "init" function and update the trip count of the loop with the4035// value it produced.4036Builder.CreateCall(StaticInit,4037{SrcLoc, ThreadNum, SchedulingType, PLastIter, PLowerBound,4038PUpperBound, PStride, One, Zero});4039Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);4040Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);4041Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);4042Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);4043CLI->setTripCount(TripCount);40444045// Update all uses of the induction variable except the one in the condition4046// block that compares it with the actual upper bound, and the increment in4047// the latch block.40484049CLI->mapIndVar([&](Instruction *OldIV) -> Value * {4050Builder.SetInsertPoint(CLI->getBody(),4051CLI->getBody()->getFirstInsertionPt());4052Builder.SetCurrentDebugLocation(DL);4053return Builder.CreateAdd(OldIV, LowerBound);4054});40554056// In the "exit" block, call the "fini" function.4057Builder.SetInsertPoint(CLI->getExit(),4058CLI->getExit()->getTerminator()->getIterator());4059Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});40604061// Add the barrier if requested.4062if (NeedsBarrier)4063createBarrier(LocationDescription(Builder.saveIP(), DL),4064omp::Directive::OMPD_for, /* ForceSimpleCall */ false,4065/* CheckCancelFlag */ false);40664067InsertPointTy AfterIP = CLI->getAfterIP();4068CLI->invalidate();40694070return AfterIP;4071}40724073OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(4074DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,4075bool NeedsBarrier, Value *ChunkSize) {4076assert(CLI->isValid() && "Requires a valid canonical loop");4077assert(ChunkSize && "Chunk size is required");40784079LLVMContext &Ctx = CLI->getFunction()->getContext();4080Value *IV = CLI->getIndVar();4081Value *OrigTripCount = CLI->getTripCount();4082Type *IVTy = IV->getType();4083assert(IVTy->getIntegerBitWidth() <= 64 &&4084"Max supported tripcount bitwidth is 64 bits");4085Type *InternalIVTy = IVTy->getIntegerBitWidth() <= 32 ? Type::getInt32Ty(Ctx)4086: Type::getInt64Ty(Ctx);4087Type *I32Type = Type::getInt32Ty(M.getContext());4088Constant *Zero = ConstantInt::get(InternalIVTy, 0);4089Constant *One = ConstantInt::get(InternalIVTy, 1);40904091// Declare useful OpenMP runtime functions.4092FunctionCallee StaticInit =4093getKmpcForStaticInitForType(InternalIVTy, M, *this);4094FunctionCallee StaticFini =4095getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);40964097// Allocate space for computed loop bounds as expected by the "init" function.4098Builder.restoreIP(AllocaIP);4099Builder.SetCurrentDebugLocation(DL);4100Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");4101Value *PLowerBound =4102Builder.CreateAlloca(InternalIVTy, nullptr, "p.lowerbound");4103Value *PUpperBound =4104Builder.CreateAlloca(InternalIVTy, nullptr, "p.upperbound");4105Value *PStride = Builder.CreateAlloca(InternalIVTy, nullptr, "p.stride");41064107// Set up the source location value for the OpenMP runtime.4108Builder.restoreIP(CLI->getPreheaderIP());4109Builder.SetCurrentDebugLocation(DL);41104111// TODO: Detect overflow in ubsan or max-out with current tripcount.4112Value *CastedChunkSize =4113Builder.CreateZExtOrTrunc(ChunkSize, InternalIVTy, "chunksize");4114Value *CastedTripCount =4115Builder.CreateZExt(OrigTripCount, InternalIVTy, "tripcount");41164117Constant *SchedulingType = ConstantInt::get(4118I32Type, static_cast<int>(OMPScheduleType::UnorderedStaticChunked));4119Builder.CreateStore(Zero, PLowerBound);4120Value *OrigUpperBound = Builder.CreateSub(CastedTripCount, One);4121Builder.CreateStore(OrigUpperBound, PUpperBound);4122Builder.CreateStore(One, PStride);41234124// Call the "init" function and update the trip count of the loop with the4125// value it produced.4126uint32_t SrcLocStrSize;4127Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);4128Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);4129Value *ThreadNum = getOrCreateThreadID(SrcLoc);4130Builder.CreateCall(StaticInit,4131{/*loc=*/SrcLoc, /*global_tid=*/ThreadNum,4132/*schedtype=*/SchedulingType, /*plastiter=*/PLastIter,4133/*plower=*/PLowerBound, /*pupper=*/PUpperBound,4134/*pstride=*/PStride, /*incr=*/One,4135/*chunk=*/CastedChunkSize});41364137// Load values written by the "init" function.4138Value *FirstChunkStart =4139Builder.CreateLoad(InternalIVTy, PLowerBound, "omp_firstchunk.lb");4140Value *FirstChunkStop =4141Builder.CreateLoad(InternalIVTy, PUpperBound, "omp_firstchunk.ub");4142Value *FirstChunkEnd = Builder.CreateAdd(FirstChunkStop, One);4143Value *ChunkRange =4144Builder.CreateSub(FirstChunkEnd, FirstChunkStart, "omp_chunk.range");4145Value *NextChunkStride =4146Builder.CreateLoad(InternalIVTy, PStride, "omp_dispatch.stride");41474148// Create outer "dispatch" loop for enumerating the chunks.4149BasicBlock *DispatchEnter = splitBB(Builder, true);4150Value *DispatchCounter;4151CanonicalLoopInfo *DispatchCLI = createCanonicalLoop(4152{Builder.saveIP(), DL},4153[&](InsertPointTy BodyIP, Value *Counter) { DispatchCounter = Counter; },4154FirstChunkStart, CastedTripCount, NextChunkStride,4155/*IsSigned=*/false, /*InclusiveStop=*/false, /*ComputeIP=*/{},4156"dispatch");41574158// Remember the BasicBlocks of the dispatch loop we need, then invalidate to4159// not have to preserve the canonical invariant.4160BasicBlock *DispatchBody = DispatchCLI->getBody();4161BasicBlock *DispatchLatch = DispatchCLI->getLatch();4162BasicBlock *DispatchExit = DispatchCLI->getExit();4163BasicBlock *DispatchAfter = DispatchCLI->getAfter();4164DispatchCLI->invalidate();41654166// Rewire the original loop to become the chunk loop inside the dispatch loop.4167redirectTo(DispatchAfter, CLI->getAfter(), DL);4168redirectTo(CLI->getExit(), DispatchLatch, DL);4169redirectTo(DispatchBody, DispatchEnter, DL);41704171// Prepare the prolog of the chunk loop.4172Builder.restoreIP(CLI->getPreheaderIP());4173Builder.SetCurrentDebugLocation(DL);41744175// Compute the number of iterations of the chunk loop.4176Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());4177Value *ChunkEnd = Builder.CreateAdd(DispatchCounter, ChunkRange);4178Value *IsLastChunk =4179Builder.CreateICmpUGE(ChunkEnd, CastedTripCount, "omp_chunk.is_last");4180Value *CountUntilOrigTripCount =4181Builder.CreateSub(CastedTripCount, DispatchCounter);4182Value *ChunkTripCount = Builder.CreateSelect(4183IsLastChunk, CountUntilOrigTripCount, ChunkRange, "omp_chunk.tripcount");4184Value *BackcastedChunkTC =4185Builder.CreateTrunc(ChunkTripCount, IVTy, "omp_chunk.tripcount.trunc");4186CLI->setTripCount(BackcastedChunkTC);41874188// Update all uses of the induction variable except the one in the condition4189// block that compares it with the actual upper bound, and the increment in4190// the latch block.4191Value *BackcastedDispatchCounter =4192Builder.CreateTrunc(DispatchCounter, IVTy, "omp_dispatch.iv.trunc");4193CLI->mapIndVar([&](Instruction *) -> Value * {4194Builder.restoreIP(CLI->getBodyIP());4195return Builder.CreateAdd(IV, BackcastedDispatchCounter);4196});41974198// In the "exit" block, call the "fini" function.4199Builder.SetInsertPoint(DispatchExit, DispatchExit->getFirstInsertionPt());4200Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});42014202// Add the barrier if requested.4203if (NeedsBarrier)4204createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,4205/*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);42064207#ifndef NDEBUG4208// Even though we currently do not support applying additional methods to it,4209// the chunk loop should remain a canonical loop.4210CLI->assertOK();4211#endif42124213return {DispatchAfter, DispatchAfter->getFirstInsertionPt()};4214}42154216// Returns an LLVM function to call for executing an OpenMP static worksharing4217// for loop depending on `type`. Only i32 and i64 are supported by the runtime.4218// Always interpret integers as unsigned similarly to CanonicalLoopInfo.4219static FunctionCallee4220getKmpcForStaticLoopForType(Type *Ty, OpenMPIRBuilder *OMPBuilder,4221WorksharingLoopType LoopType) {4222unsigned Bitwidth = Ty->getIntegerBitWidth();4223Module &M = OMPBuilder->M;4224switch (LoopType) {4225case WorksharingLoopType::ForStaticLoop:4226if (Bitwidth == 32)4227return OMPBuilder->getOrCreateRuntimeFunction(4228M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_4u);4229if (Bitwidth == 64)4230return OMPBuilder->getOrCreateRuntimeFunction(4231M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_8u);4232break;4233case WorksharingLoopType::DistributeStaticLoop:4234if (Bitwidth == 32)4235return OMPBuilder->getOrCreateRuntimeFunction(4236M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_4u);4237if (Bitwidth == 64)4238return OMPBuilder->getOrCreateRuntimeFunction(4239M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_8u);4240break;4241case WorksharingLoopType::DistributeForStaticLoop:4242if (Bitwidth == 32)4243return OMPBuilder->getOrCreateRuntimeFunction(4244M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_4u);4245if (Bitwidth == 64)4246return OMPBuilder->getOrCreateRuntimeFunction(4247M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_8u);4248break;4249}4250if (Bitwidth != 32 && Bitwidth != 64) {4251llvm_unreachable("Unknown OpenMP loop iterator bitwidth");4252}4253llvm_unreachable("Unknown type of OpenMP worksharing loop");4254}42554256// Inserts a call to proper OpenMP Device RTL function which handles4257// loop worksharing.4258static void createTargetLoopWorkshareCall(4259OpenMPIRBuilder *OMPBuilder, WorksharingLoopType LoopType,4260BasicBlock *InsertBlock, Value *Ident, Value *LoopBodyArg,4261Type *ParallelTaskPtr, Value *TripCount, Function &LoopBodyFn) {4262Type *TripCountTy = TripCount->getType();4263Module &M = OMPBuilder->M;4264IRBuilder<> &Builder = OMPBuilder->Builder;4265FunctionCallee RTLFn =4266getKmpcForStaticLoopForType(TripCountTy, OMPBuilder, LoopType);4267SmallVector<Value *, 8> RealArgs;4268RealArgs.push_back(Ident);4269RealArgs.push_back(Builder.CreateBitCast(&LoopBodyFn, ParallelTaskPtr));4270RealArgs.push_back(LoopBodyArg);4271RealArgs.push_back(TripCount);4272if (LoopType == WorksharingLoopType::DistributeStaticLoop) {4273RealArgs.push_back(ConstantInt::get(TripCountTy, 0));4274Builder.CreateCall(RTLFn, RealArgs);4275return;4276}4277FunctionCallee RTLNumThreads = OMPBuilder->getOrCreateRuntimeFunction(4278M, omp::RuntimeFunction::OMPRTL_omp_get_num_threads);4279Builder.restoreIP({InsertBlock, std::prev(InsertBlock->end())});4280Value *NumThreads = Builder.CreateCall(RTLNumThreads, {});42814282RealArgs.push_back(4283Builder.CreateZExtOrTrunc(NumThreads, TripCountTy, "num.threads.cast"));4284RealArgs.push_back(ConstantInt::get(TripCountTy, 0));4285if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {4286RealArgs.push_back(ConstantInt::get(TripCountTy, 0));4287}42884289Builder.CreateCall(RTLFn, RealArgs);4290}42914292static void4293workshareLoopTargetCallback(OpenMPIRBuilder *OMPIRBuilder,4294CanonicalLoopInfo *CLI, Value *Ident,4295Function &OutlinedFn, Type *ParallelTaskPtr,4296const SmallVector<Instruction *, 4> &ToBeDeleted,4297WorksharingLoopType LoopType) {4298IRBuilder<> &Builder = OMPIRBuilder->Builder;4299BasicBlock *Preheader = CLI->getPreheader();4300Value *TripCount = CLI->getTripCount();43014302// After loop body outling, the loop body contains only set up4303// of loop body argument structure and the call to the outlined4304// loop body function. Firstly, we need to move setup of loop body args4305// into loop preheader.4306Preheader->splice(std::prev(Preheader->end()), CLI->getBody(),4307CLI->getBody()->begin(), std::prev(CLI->getBody()->end()));43084309// The next step is to remove the whole loop. We do not it need anymore.4310// That's why make an unconditional branch from loop preheader to loop4311// exit block4312Builder.restoreIP({Preheader, Preheader->end()});4313Preheader->getTerminator()->eraseFromParent();4314Builder.CreateBr(CLI->getExit());43154316// Delete dead loop blocks4317OpenMPIRBuilder::OutlineInfo CleanUpInfo;4318SmallPtrSet<BasicBlock *, 32> RegionBlockSet;4319SmallVector<BasicBlock *, 32> BlocksToBeRemoved;4320CleanUpInfo.EntryBB = CLI->getHeader();4321CleanUpInfo.ExitBB = CLI->getExit();4322CleanUpInfo.collectBlocks(RegionBlockSet, BlocksToBeRemoved);4323DeleteDeadBlocks(BlocksToBeRemoved);43244325// Find the instruction which corresponds to loop body argument structure4326// and remove the call to loop body function instruction.4327Value *LoopBodyArg;4328User *OutlinedFnUser = OutlinedFn.getUniqueUndroppableUser();4329assert(OutlinedFnUser &&4330"Expected unique undroppable user of outlined function");4331CallInst *OutlinedFnCallInstruction = dyn_cast<CallInst>(OutlinedFnUser);4332assert(OutlinedFnCallInstruction && "Expected outlined function call");4333assert((OutlinedFnCallInstruction->getParent() == Preheader) &&4334"Expected outlined function call to be located in loop preheader");4335// Check in case no argument structure has been passed.4336if (OutlinedFnCallInstruction->arg_size() > 1)4337LoopBodyArg = OutlinedFnCallInstruction->getArgOperand(1);4338else4339LoopBodyArg = Constant::getNullValue(Builder.getPtrTy());4340OutlinedFnCallInstruction->eraseFromParent();43414342createTargetLoopWorkshareCall(OMPIRBuilder, LoopType, Preheader, Ident,4343LoopBodyArg, ParallelTaskPtr, TripCount,4344OutlinedFn);43454346for (auto &ToBeDeletedItem : ToBeDeleted)4347ToBeDeletedItem->eraseFromParent();4348CLI->invalidate();4349}43504351OpenMPIRBuilder::InsertPointTy4352OpenMPIRBuilder::applyWorkshareLoopTarget(DebugLoc DL, CanonicalLoopInfo *CLI,4353InsertPointTy AllocaIP,4354WorksharingLoopType LoopType) {4355uint32_t SrcLocStrSize;4356Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);4357Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);43584359OutlineInfo OI;4360OI.OuterAllocaBB = CLI->getPreheader();4361Function *OuterFn = CLI->getPreheader()->getParent();43624363// Instructions which need to be deleted at the end of code generation4364SmallVector<Instruction *, 4> ToBeDeleted;43654366OI.OuterAllocaBB = AllocaIP.getBlock();43674368// Mark the body loop as region which needs to be extracted4369OI.EntryBB = CLI->getBody();4370OI.ExitBB = CLI->getLatch()->splitBasicBlock(CLI->getLatch()->begin(),4371"omp.prelatch", true);43724373// Prepare loop body for extraction4374Builder.restoreIP({CLI->getPreheader(), CLI->getPreheader()->begin()});43754376// Insert new loop counter variable which will be used only in loop4377// body.4378AllocaInst *NewLoopCnt = Builder.CreateAlloca(CLI->getIndVarType(), 0, "");4379Instruction *NewLoopCntLoad =4380Builder.CreateLoad(CLI->getIndVarType(), NewLoopCnt);4381// New loop counter instructions are redundant in the loop preheader when4382// code generation for workshare loop is finshed. That's why mark them as4383// ready for deletion.4384ToBeDeleted.push_back(NewLoopCntLoad);4385ToBeDeleted.push_back(NewLoopCnt);43864387// Analyse loop body region. Find all input variables which are used inside4388// loop body region.4389SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;4390SmallVector<BasicBlock *, 32> Blocks;4391OI.collectBlocks(ParallelRegionBlockSet, Blocks);4392SmallVector<BasicBlock *, 32> BlocksT(ParallelRegionBlockSet.begin(),4393ParallelRegionBlockSet.end());43944395CodeExtractorAnalysisCache CEAC(*OuterFn);4396CodeExtractor Extractor(Blocks,4397/* DominatorTree */ nullptr,4398/* AggregateArgs */ true,4399/* BlockFrequencyInfo */ nullptr,4400/* BranchProbabilityInfo */ nullptr,4401/* AssumptionCache */ nullptr,4402/* AllowVarArgs */ true,4403/* AllowAlloca */ true,4404/* AllocationBlock */ CLI->getPreheader(),4405/* Suffix */ ".omp_wsloop",4406/* AggrArgsIn0AddrSpace */ true);44074408BasicBlock *CommonExit = nullptr;4409SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;44104411// Find allocas outside the loop body region which are used inside loop4412// body4413Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);44144415// We need to model loop body region as the function f(cnt, loop_arg).4416// That's why we replace loop induction variable by the new counter4417// which will be one of loop body function argument4418SmallVector<User *> Users(CLI->getIndVar()->user_begin(),4419CLI->getIndVar()->user_end());4420for (auto Use : Users) {4421if (Instruction *Inst = dyn_cast<Instruction>(Use)) {4422if (ParallelRegionBlockSet.count(Inst->getParent())) {4423Inst->replaceUsesOfWith(CLI->getIndVar(), NewLoopCntLoad);4424}4425}4426}4427// Make sure that loop counter variable is not merged into loop body4428// function argument structure and it is passed as separate variable4429OI.ExcludeArgsFromAggregate.push_back(NewLoopCntLoad);44304431// PostOutline CB is invoked when loop body function is outlined and4432// loop body is replaced by call to outlined function. We need to add4433// call to OpenMP device rtl inside loop preheader. OpenMP device rtl4434// function will handle loop control logic.4435//4436OI.PostOutlineCB = [=, ToBeDeletedVec =4437std::move(ToBeDeleted)](Function &OutlinedFn) {4438workshareLoopTargetCallback(this, CLI, Ident, OutlinedFn, ParallelTaskPtr,4439ToBeDeletedVec, LoopType);4440};4441addOutlineInfo(std::move(OI));4442return CLI->getAfterIP();4443}44444445OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyWorkshareLoop(4446DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,4447bool NeedsBarrier, omp::ScheduleKind SchedKind, Value *ChunkSize,4448bool HasSimdModifier, bool HasMonotonicModifier,4449bool HasNonmonotonicModifier, bool HasOrderedClause,4450WorksharingLoopType LoopType) {4451if (Config.isTargetDevice())4452return applyWorkshareLoopTarget(DL, CLI, AllocaIP, LoopType);4453OMPScheduleType EffectiveScheduleType = computeOpenMPScheduleType(4454SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,4455HasNonmonotonicModifier, HasOrderedClause);44564457bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==4458OMPScheduleType::ModifierOrdered;4459switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {4460case OMPScheduleType::BaseStatic:4461assert(!ChunkSize && "No chunk size with static-chunked schedule");4462if (IsOrdered)4463return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,4464NeedsBarrier, ChunkSize);4465// FIXME: Monotonicity ignored?4466return applyStaticWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier);44674468case OMPScheduleType::BaseStaticChunked:4469if (IsOrdered)4470return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,4471NeedsBarrier, ChunkSize);4472// FIXME: Monotonicity ignored?4473return applyStaticChunkedWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier,4474ChunkSize);44754476case OMPScheduleType::BaseRuntime:4477case OMPScheduleType::BaseAuto:4478case OMPScheduleType::BaseGreedy:4479case OMPScheduleType::BaseBalanced:4480case OMPScheduleType::BaseSteal:4481case OMPScheduleType::BaseGuidedSimd:4482case OMPScheduleType::BaseRuntimeSimd:4483assert(!ChunkSize &&4484"schedule type does not support user-defined chunk sizes");4485[[fallthrough]];4486case OMPScheduleType::BaseDynamicChunked:4487case OMPScheduleType::BaseGuidedChunked:4488case OMPScheduleType::BaseGuidedIterativeChunked:4489case OMPScheduleType::BaseGuidedAnalyticalChunked:4490case OMPScheduleType::BaseStaticBalancedChunked:4491return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,4492NeedsBarrier, ChunkSize);44934494default:4495llvm_unreachable("Unknown/unimplemented schedule kind");4496}4497}44984499/// Returns an LLVM function to call for initializing loop bounds using OpenMP4500/// dynamic scheduling depending on `type`. Only i32 and i64 are supported by4501/// the runtime. Always interpret integers as unsigned similarly to4502/// CanonicalLoopInfo.4503static FunctionCallee4504getKmpcForDynamicInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {4505unsigned Bitwidth = Ty->getIntegerBitWidth();4506if (Bitwidth == 32)4507return OMPBuilder.getOrCreateRuntimeFunction(4508M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);4509if (Bitwidth == 64)4510return OMPBuilder.getOrCreateRuntimeFunction(4511M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);4512llvm_unreachable("unknown OpenMP loop iterator bitwidth");4513}45144515/// Returns an LLVM function to call for updating the next loop using OpenMP4516/// dynamic scheduling depending on `type`. Only i32 and i64 are supported by4517/// the runtime. Always interpret integers as unsigned similarly to4518/// CanonicalLoopInfo.4519static FunctionCallee4520getKmpcForDynamicNextForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {4521unsigned Bitwidth = Ty->getIntegerBitWidth();4522if (Bitwidth == 32)4523return OMPBuilder.getOrCreateRuntimeFunction(4524M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);4525if (Bitwidth == 64)4526return OMPBuilder.getOrCreateRuntimeFunction(4527M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);4528llvm_unreachable("unknown OpenMP loop iterator bitwidth");4529}45304531/// Returns an LLVM function to call for finalizing the dynamic loop using4532/// depending on `type`. Only i32 and i64 are supported by the runtime. Always4533/// interpret integers as unsigned similarly to CanonicalLoopInfo.4534static FunctionCallee4535getKmpcForDynamicFiniForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {4536unsigned Bitwidth = Ty->getIntegerBitWidth();4537if (Bitwidth == 32)4538return OMPBuilder.getOrCreateRuntimeFunction(4539M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);4540if (Bitwidth == 64)4541return OMPBuilder.getOrCreateRuntimeFunction(4542M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);4543llvm_unreachable("unknown OpenMP loop iterator bitwidth");4544}45454546OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyDynamicWorkshareLoop(4547DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,4548OMPScheduleType SchedType, bool NeedsBarrier, Value *Chunk) {4549assert(CLI->isValid() && "Requires a valid canonical loop");4550assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&4551"Require dedicated allocate IP");4552assert(isValidWorkshareLoopScheduleType(SchedType) &&4553"Require valid schedule type");45544555bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==4556OMPScheduleType::ModifierOrdered;45574558// Set up the source location value for OpenMP runtime.4559Builder.SetCurrentDebugLocation(DL);45604561uint32_t SrcLocStrSize;4562Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);4563Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);45644565// Declare useful OpenMP runtime functions.4566Value *IV = CLI->getIndVar();4567Type *IVTy = IV->getType();4568FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);4569FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);45704571// Allocate space for computed loop bounds as expected by the "init" function.4572Builder.SetInsertPoint(AllocaIP.getBlock()->getFirstNonPHIOrDbgOrAlloca());4573Type *I32Type = Type::getInt32Ty(M.getContext());4574Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");4575Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");4576Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");4577Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");45784579// At the end of the preheader, prepare for calling the "init" function by4580// storing the current loop bounds into the allocated space. A canonical loop4581// always iterates from 0 to trip-count with step 1. Note that "init" expects4582// and produces an inclusive upper bound.4583BasicBlock *PreHeader = CLI->getPreheader();4584Builder.SetInsertPoint(PreHeader->getTerminator());4585Constant *One = ConstantInt::get(IVTy, 1);4586Builder.CreateStore(One, PLowerBound);4587Value *UpperBound = CLI->getTripCount();4588Builder.CreateStore(UpperBound, PUpperBound);4589Builder.CreateStore(One, PStride);45904591BasicBlock *Header = CLI->getHeader();4592BasicBlock *Exit = CLI->getExit();4593BasicBlock *Cond = CLI->getCond();4594BasicBlock *Latch = CLI->getLatch();4595InsertPointTy AfterIP = CLI->getAfterIP();45964597// The CLI will be "broken" in the code below, as the loop is no longer4598// a valid canonical loop.45994600if (!Chunk)4601Chunk = One;46024603Value *ThreadNum = getOrCreateThreadID(SrcLoc);46044605Constant *SchedulingType =4606ConstantInt::get(I32Type, static_cast<int>(SchedType));46074608// Call the "init" function.4609Builder.CreateCall(DynamicInit,4610{SrcLoc, ThreadNum, SchedulingType, /* LowerBound */ One,4611UpperBound, /* step */ One, Chunk});46124613// An outer loop around the existing one.4614BasicBlock *OuterCond = BasicBlock::Create(4615PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",4616PreHeader->getParent());4617// This needs to be 32-bit always, so can't use the IVTy Zero above.4618Builder.SetInsertPoint(OuterCond, OuterCond->getFirstInsertionPt());4619Value *Res =4620Builder.CreateCall(DynamicNext, {SrcLoc, ThreadNum, PLastIter,4621PLowerBound, PUpperBound, PStride});4622Constant *Zero32 = ConstantInt::get(I32Type, 0);4623Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);4624Value *LowerBound =4625Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");4626Builder.CreateCondBr(MoreWork, Header, Exit);46274628// Change PHI-node in loop header to use outer cond rather than preheader,4629// and set IV to the LowerBound.4630Instruction *Phi = &Header->front();4631auto *PI = cast<PHINode>(Phi);4632PI->setIncomingBlock(0, OuterCond);4633PI->setIncomingValue(0, LowerBound);46344635// Then set the pre-header to jump to the OuterCond4636Instruction *Term = PreHeader->getTerminator();4637auto *Br = cast<BranchInst>(Term);4638Br->setSuccessor(0, OuterCond);46394640// Modify the inner condition:4641// * Use the UpperBound returned from the DynamicNext call.4642// * jump to the loop outer loop when done with one of the inner loops.4643Builder.SetInsertPoint(Cond, Cond->getFirstInsertionPt());4644UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");4645Instruction *Comp = &*Builder.GetInsertPoint();4646auto *CI = cast<CmpInst>(Comp);4647CI->setOperand(1, UpperBound);4648// Redirect the inner exit to branch to outer condition.4649Instruction *Branch = &Cond->back();4650auto *BI = cast<BranchInst>(Branch);4651assert(BI->getSuccessor(1) == Exit);4652BI->setSuccessor(1, OuterCond);46534654// Call the "fini" function if "ordered" is present in wsloop directive.4655if (Ordered) {4656Builder.SetInsertPoint(&Latch->back());4657FunctionCallee DynamicFini = getKmpcForDynamicFiniForType(IVTy, M, *this);4658Builder.CreateCall(DynamicFini, {SrcLoc, ThreadNum});4659}46604661// Add the barrier if requested.4662if (NeedsBarrier) {4663Builder.SetInsertPoint(&Exit->back());4664createBarrier(LocationDescription(Builder.saveIP(), DL),4665omp::Directive::OMPD_for, /* ForceSimpleCall */ false,4666/* CheckCancelFlag */ false);4667}46684669CLI->invalidate();4670return AfterIP;4671}46724673/// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,4674/// after this \p OldTarget will be orphaned.4675static void redirectAllPredecessorsTo(BasicBlock *OldTarget,4676BasicBlock *NewTarget, DebugLoc DL) {4677for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))4678redirectTo(Pred, NewTarget, DL);4679}46804681/// Determine which blocks in \p BBs are reachable from outside and remove the4682/// ones that are not reachable from the function.4683static void removeUnusedBlocksFromParent(ArrayRef<BasicBlock *> BBs) {4684SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};4685auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {4686for (Use &U : BB->uses()) {4687auto *UseInst = dyn_cast<Instruction>(U.getUser());4688if (!UseInst)4689continue;4690if (BBsToErase.count(UseInst->getParent()))4691continue;4692return true;4693}4694return false;4695};46964697while (BBsToErase.remove_if(HasRemainingUses)) {4698// Try again if anything was removed.4699}47004701SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());4702DeleteDeadBlocks(BBVec);4703}47044705CanonicalLoopInfo *4706OpenMPIRBuilder::collapseLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,4707InsertPointTy ComputeIP) {4708assert(Loops.size() >= 1 && "At least one loop required");4709size_t NumLoops = Loops.size();47104711// Nothing to do if there is already just one loop.4712if (NumLoops == 1)4713return Loops.front();47144715CanonicalLoopInfo *Outermost = Loops.front();4716CanonicalLoopInfo *Innermost = Loops.back();4717BasicBlock *OrigPreheader = Outermost->getPreheader();4718BasicBlock *OrigAfter = Outermost->getAfter();4719Function *F = OrigPreheader->getParent();47204721// Loop control blocks that may become orphaned later.4722SmallVector<BasicBlock *, 12> OldControlBBs;4723OldControlBBs.reserve(6 * Loops.size());4724for (CanonicalLoopInfo *Loop : Loops)4725Loop->collectControlBlocks(OldControlBBs);47264727// Setup the IRBuilder for inserting the trip count computation.4728Builder.SetCurrentDebugLocation(DL);4729if (ComputeIP.isSet())4730Builder.restoreIP(ComputeIP);4731else4732Builder.restoreIP(Outermost->getPreheaderIP());47334734// Derive the collapsed' loop trip count.4735// TODO: Find common/largest indvar type.4736Value *CollapsedTripCount = nullptr;4737for (CanonicalLoopInfo *L : Loops) {4738assert(L->isValid() &&4739"All loops to collapse must be valid canonical loops");4740Value *OrigTripCount = L->getTripCount();4741if (!CollapsedTripCount) {4742CollapsedTripCount = OrigTripCount;4743continue;4744}47454746// TODO: Enable UndefinedSanitizer to diagnose an overflow here.4747CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,4748{}, /*HasNUW=*/true);4749}47504751// Create the collapsed loop control flow.4752CanonicalLoopInfo *Result =4753createLoopSkeleton(DL, CollapsedTripCount, F,4754OrigPreheader->getNextNode(), OrigAfter, "collapsed");47554756// Build the collapsed loop body code.4757// Start with deriving the input loop induction variables from the collapsed4758// one, using a divmod scheme. To preserve the original loops' order, the4759// innermost loop use the least significant bits.4760Builder.restoreIP(Result->getBodyIP());47614762Value *Leftover = Result->getIndVar();4763SmallVector<Value *> NewIndVars;4764NewIndVars.resize(NumLoops);4765for (int i = NumLoops - 1; i >= 1; --i) {4766Value *OrigTripCount = Loops[i]->getTripCount();47674768Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);4769NewIndVars[i] = NewIndVar;47704771Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);4772}4773// Outermost loop gets all the remaining bits.4774NewIndVars[0] = Leftover;47754776// Construct the loop body control flow.4777// We progressively construct the branch structure following in direction of4778// the control flow, from the leading in-between code, the loop nest body, the4779// trailing in-between code, and rejoining the collapsed loop's latch.4780// ContinueBlock and ContinuePred keep track of the source(s) of next edge. If4781// the ContinueBlock is set, continue with that block. If ContinuePred, use4782// its predecessors as sources.4783BasicBlock *ContinueBlock = Result->getBody();4784BasicBlock *ContinuePred = nullptr;4785auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,4786BasicBlock *NextSrc) {4787if (ContinueBlock)4788redirectTo(ContinueBlock, Dest, DL);4789else4790redirectAllPredecessorsTo(ContinuePred, Dest, DL);47914792ContinueBlock = nullptr;4793ContinuePred = NextSrc;4794};47954796// The code before the nested loop of each level.4797// Because we are sinking it into the nest, it will be executed more often4798// that the original loop. More sophisticated schemes could keep track of what4799// the in-between code is and instantiate it only once per thread.4800for (size_t i = 0; i < NumLoops - 1; ++i)4801ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());48024803// Connect the loop nest body.4804ContinueWith(Innermost->getBody(), Innermost->getLatch());48054806// The code after the nested loop at each level.4807for (size_t i = NumLoops - 1; i > 0; --i)4808ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());48094810// Connect the finished loop to the collapsed loop latch.4811ContinueWith(Result->getLatch(), nullptr);48124813// Replace the input loops with the new collapsed loop.4814redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);4815redirectTo(Result->getAfter(), Outermost->getAfter(), DL);48164817// Replace the input loop indvars with the derived ones.4818for (size_t i = 0; i < NumLoops; ++i)4819Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);48204821// Remove unused parts of the input loops.4822removeUnusedBlocksFromParent(OldControlBBs);48234824for (CanonicalLoopInfo *L : Loops)4825L->invalidate();48264827#ifndef NDEBUG4828Result->assertOK();4829#endif4830return Result;4831}48324833std::vector<CanonicalLoopInfo *>4834OpenMPIRBuilder::tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,4835ArrayRef<Value *> TileSizes) {4836assert(TileSizes.size() == Loops.size() &&4837"Must pass as many tile sizes as there are loops");4838int NumLoops = Loops.size();4839assert(NumLoops >= 1 && "At least one loop to tile required");48404841CanonicalLoopInfo *OutermostLoop = Loops.front();4842CanonicalLoopInfo *InnermostLoop = Loops.back();4843Function *F = OutermostLoop->getBody()->getParent();4844BasicBlock *InnerEnter = InnermostLoop->getBody();4845BasicBlock *InnerLatch = InnermostLoop->getLatch();48464847// Loop control blocks that may become orphaned later.4848SmallVector<BasicBlock *, 12> OldControlBBs;4849OldControlBBs.reserve(6 * Loops.size());4850for (CanonicalLoopInfo *Loop : Loops)4851Loop->collectControlBlocks(OldControlBBs);48524853// Collect original trip counts and induction variable to be accessible by4854// index. Also, the structure of the original loops is not preserved during4855// the construction of the tiled loops, so do it before we scavenge the BBs of4856// any original CanonicalLoopInfo.4857SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;4858for (CanonicalLoopInfo *L : Loops) {4859assert(L->isValid() && "All input loops must be valid canonical loops");4860OrigTripCounts.push_back(L->getTripCount());4861OrigIndVars.push_back(L->getIndVar());4862}48634864// Collect the code between loop headers. These may contain SSA definitions4865// that are used in the loop nest body. To be usable with in the innermost4866// body, these BasicBlocks will be sunk into the loop nest body. That is,4867// these instructions may be executed more often than before the tiling.4868// TODO: It would be sufficient to only sink them into body of the4869// corresponding tile loop.4870SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> InbetweenCode;4871for (int i = 0; i < NumLoops - 1; ++i) {4872CanonicalLoopInfo *Surrounding = Loops[i];4873CanonicalLoopInfo *Nested = Loops[i + 1];48744875BasicBlock *EnterBB = Surrounding->getBody();4876BasicBlock *ExitBB = Nested->getHeader();4877InbetweenCode.emplace_back(EnterBB, ExitBB);4878}48794880// Compute the trip counts of the floor loops.4881Builder.SetCurrentDebugLocation(DL);4882Builder.restoreIP(OutermostLoop->getPreheaderIP());4883SmallVector<Value *, 4> FloorCount, FloorRems;4884for (int i = 0; i < NumLoops; ++i) {4885Value *TileSize = TileSizes[i];4886Value *OrigTripCount = OrigTripCounts[i];4887Type *IVType = OrigTripCount->getType();48884889Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);4890Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);48914892// 0 if tripcount divides the tilesize, 1 otherwise.4893// 1 means we need an additional iteration for a partial tile.4894//4895// Unfortunately we cannot just use the roundup-formula4896// (tripcount + tilesize - 1)/tilesize4897// because the summation might overflow. We do not want introduce undefined4898// behavior when the untiled loop nest did not.4899Value *FloorTripOverflow =4900Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));49014902FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);4903FloorTripCount =4904Builder.CreateAdd(FloorTripCount, FloorTripOverflow,4905"omp_floor" + Twine(i) + ".tripcount", true);49064907// Remember some values for later use.4908FloorCount.push_back(FloorTripCount);4909FloorRems.push_back(FloorTripRem);4910}49114912// Generate the new loop nest, from the outermost to the innermost.4913std::vector<CanonicalLoopInfo *> Result;4914Result.reserve(NumLoops * 2);49154916// The basic block of the surrounding loop that enters the nest generated4917// loop.4918BasicBlock *Enter = OutermostLoop->getPreheader();49194920// The basic block of the surrounding loop where the inner code should4921// continue.4922BasicBlock *Continue = OutermostLoop->getAfter();49234924// Where the next loop basic block should be inserted.4925BasicBlock *OutroInsertBefore = InnermostLoop->getExit();49264927auto EmbeddNewLoop =4928[this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](4929Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {4930CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(4931DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);4932redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);4933redirectTo(EmbeddedLoop->getAfter(), Continue, DL);49344935// Setup the position where the next embedded loop connects to this loop.4936Enter = EmbeddedLoop->getBody();4937Continue = EmbeddedLoop->getLatch();4938OutroInsertBefore = EmbeddedLoop->getLatch();4939return EmbeddedLoop;4940};49414942auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,4943const Twine &NameBase) {4944for (auto P : enumerate(TripCounts)) {4945CanonicalLoopInfo *EmbeddedLoop =4946EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));4947Result.push_back(EmbeddedLoop);4948}4949};49504951EmbeddNewLoops(FloorCount, "floor");49524953// Within the innermost floor loop, emit the code that computes the tile4954// sizes.4955Builder.SetInsertPoint(Enter->getTerminator());4956SmallVector<Value *, 4> TileCounts;4957for (int i = 0; i < NumLoops; ++i) {4958CanonicalLoopInfo *FloorLoop = Result[i];4959Value *TileSize = TileSizes[i];49604961Value *FloorIsEpilogue =4962Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);4963Value *TileTripCount =4964Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);49654966TileCounts.push_back(TileTripCount);4967}49684969// Create the tile loops.4970EmbeddNewLoops(TileCounts, "tile");49714972// Insert the inbetween code into the body.4973BasicBlock *BodyEnter = Enter;4974BasicBlock *BodyEntered = nullptr;4975for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {4976BasicBlock *EnterBB = P.first;4977BasicBlock *ExitBB = P.second;49784979if (BodyEnter)4980redirectTo(BodyEnter, EnterBB, DL);4981else4982redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);49834984BodyEnter = nullptr;4985BodyEntered = ExitBB;4986}49874988// Append the original loop nest body into the generated loop nest body.4989if (BodyEnter)4990redirectTo(BodyEnter, InnerEnter, DL);4991else4992redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);4993redirectAllPredecessorsTo(InnerLatch, Continue, DL);49944995// Replace the original induction variable with an induction variable computed4996// from the tile and floor induction variables.4997Builder.restoreIP(Result.back()->getBodyIP());4998for (int i = 0; i < NumLoops; ++i) {4999CanonicalLoopInfo *FloorLoop = Result[i];5000CanonicalLoopInfo *TileLoop = Result[NumLoops + i];5001Value *OrigIndVar = OrigIndVars[i];5002Value *Size = TileSizes[i];50035004Value *Scale =5005Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);5006Value *Shift =5007Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);5008OrigIndVar->replaceAllUsesWith(Shift);5009}50105011// Remove unused parts of the original loops.5012removeUnusedBlocksFromParent(OldControlBBs);50135014for (CanonicalLoopInfo *L : Loops)5015L->invalidate();50165017#ifndef NDEBUG5018for (CanonicalLoopInfo *GenL : Result)5019GenL->assertOK();5020#endif5021return Result;5022}50235024/// Attach metadata \p Properties to the basic block described by \p BB. If the5025/// basic block already has metadata, the basic block properties are appended.5026static void addBasicBlockMetadata(BasicBlock *BB,5027ArrayRef<Metadata *> Properties) {5028// Nothing to do if no property to attach.5029if (Properties.empty())5030return;50315032LLVMContext &Ctx = BB->getContext();5033SmallVector<Metadata *> NewProperties;5034NewProperties.push_back(nullptr);50355036// If the basic block already has metadata, prepend it to the new metadata.5037MDNode *Existing = BB->getTerminator()->getMetadata(LLVMContext::MD_loop);5038if (Existing)5039append_range(NewProperties, drop_begin(Existing->operands(), 1));50405041append_range(NewProperties, Properties);5042MDNode *BasicBlockID = MDNode::getDistinct(Ctx, NewProperties);5043BasicBlockID->replaceOperandWith(0, BasicBlockID);50445045BB->getTerminator()->setMetadata(LLVMContext::MD_loop, BasicBlockID);5046}50475048/// Attach loop metadata \p Properties to the loop described by \p Loop. If the5049/// loop already has metadata, the loop properties are appended.5050static void addLoopMetadata(CanonicalLoopInfo *Loop,5051ArrayRef<Metadata *> Properties) {5052assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");50535054// Attach metadata to the loop's latch5055BasicBlock *Latch = Loop->getLatch();5056assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");5057addBasicBlockMetadata(Latch, Properties);5058}50595060/// Attach llvm.access.group metadata to the memref instructions of \p Block5061static void addSimdMetadata(BasicBlock *Block, MDNode *AccessGroup,5062LoopInfo &LI) {5063for (Instruction &I : *Block) {5064if (I.mayReadOrWriteMemory()) {5065// TODO: This instruction may already have access group from5066// other pragmas e.g. #pragma clang loop vectorize. Append5067// so that the existing metadata is not overwritten.5068I.setMetadata(LLVMContext::MD_access_group, AccessGroup);5069}5070}5071}50725073void OpenMPIRBuilder::unrollLoopFull(DebugLoc, CanonicalLoopInfo *Loop) {5074LLVMContext &Ctx = Builder.getContext();5075addLoopMetadata(5076Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),5077MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});5078}50795080void OpenMPIRBuilder::unrollLoopHeuristic(DebugLoc, CanonicalLoopInfo *Loop) {5081LLVMContext &Ctx = Builder.getContext();5082addLoopMetadata(5083Loop, {5084MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),5085});5086}50875088void OpenMPIRBuilder::createIfVersion(CanonicalLoopInfo *CanonicalLoop,5089Value *IfCond, ValueToValueMapTy &VMap,5090const Twine &NamePrefix) {5091Function *F = CanonicalLoop->getFunction();50925093// Define where if branch should be inserted5094Instruction *SplitBefore;5095if (Instruction::classof(IfCond)) {5096SplitBefore = dyn_cast<Instruction>(IfCond);5097} else {5098SplitBefore = CanonicalLoop->getPreheader()->getTerminator();5099}51005101// TODO: We should not rely on pass manager. Currently we use pass manager5102// only for getting llvm::Loop which corresponds to given CanonicalLoopInfo5103// object. We should have a method which returns all blocks between5104// CanonicalLoopInfo::getHeader() and CanonicalLoopInfo::getAfter()5105FunctionAnalysisManager FAM;5106FAM.registerPass([]() { return DominatorTreeAnalysis(); });5107FAM.registerPass([]() { return LoopAnalysis(); });5108FAM.registerPass([]() { return PassInstrumentationAnalysis(); });51095110// Get the loop which needs to be cloned5111LoopAnalysis LIA;5112LoopInfo &&LI = LIA.run(*F, FAM);5113Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());51145115// Create additional blocks for the if statement5116BasicBlock *Head = SplitBefore->getParent();5117Instruction *HeadOldTerm = Head->getTerminator();5118llvm::LLVMContext &C = Head->getContext();5119llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create(5120C, NamePrefix + ".if.then", Head->getParent(), Head->getNextNode());5121llvm::BasicBlock *ElseBlock = llvm::BasicBlock::Create(5122C, NamePrefix + ".if.else", Head->getParent(), CanonicalLoop->getExit());51235124// Create if condition branch.5125Builder.SetInsertPoint(HeadOldTerm);5126Instruction *BrInstr =5127Builder.CreateCondBr(IfCond, ThenBlock, /*ifFalse*/ ElseBlock);5128InsertPointTy IP{BrInstr->getParent(), ++BrInstr->getIterator()};5129// Then block contains branch to omp loop which needs to be vectorized5130spliceBB(IP, ThenBlock, false);5131ThenBlock->replaceSuccessorsPhiUsesWith(Head, ThenBlock);51325133Builder.SetInsertPoint(ElseBlock);51345135// Clone loop for the else branch5136SmallVector<BasicBlock *, 8> NewBlocks;51375138VMap[CanonicalLoop->getPreheader()] = ElseBlock;5139for (BasicBlock *Block : L->getBlocks()) {5140BasicBlock *NewBB = CloneBasicBlock(Block, VMap, "", F);5141NewBB->moveBefore(CanonicalLoop->getExit());5142VMap[Block] = NewBB;5143NewBlocks.push_back(NewBB);5144}5145remapInstructionsInBlocks(NewBlocks, VMap);5146Builder.CreateBr(NewBlocks.front());5147}51485149unsigned5150OpenMPIRBuilder::getOpenMPDefaultSimdAlign(const Triple &TargetTriple,5151const StringMap<bool> &Features) {5152if (TargetTriple.isX86()) {5153if (Features.lookup("avx512f"))5154return 512;5155else if (Features.lookup("avx"))5156return 256;5157return 128;5158}5159if (TargetTriple.isPPC())5160return 128;5161if (TargetTriple.isWasm())5162return 128;5163return 0;5164}51655166void OpenMPIRBuilder::applySimd(CanonicalLoopInfo *CanonicalLoop,5167MapVector<Value *, Value *> AlignedVars,5168Value *IfCond, OrderKind Order,5169ConstantInt *Simdlen, ConstantInt *Safelen) {5170LLVMContext &Ctx = Builder.getContext();51715172Function *F = CanonicalLoop->getFunction();51735174// TODO: We should not rely on pass manager. Currently we use pass manager5175// only for getting llvm::Loop which corresponds to given CanonicalLoopInfo5176// object. We should have a method which returns all blocks between5177// CanonicalLoopInfo::getHeader() and CanonicalLoopInfo::getAfter()5178FunctionAnalysisManager FAM;5179FAM.registerPass([]() { return DominatorTreeAnalysis(); });5180FAM.registerPass([]() { return LoopAnalysis(); });5181FAM.registerPass([]() { return PassInstrumentationAnalysis(); });51825183LoopAnalysis LIA;5184LoopInfo &&LI = LIA.run(*F, FAM);51855186Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());5187if (AlignedVars.size()) {5188InsertPointTy IP = Builder.saveIP();5189Builder.SetInsertPoint(CanonicalLoop->getPreheader()->getTerminator());5190for (auto &AlignedItem : AlignedVars) {5191Value *AlignedPtr = AlignedItem.first;5192Value *Alignment = AlignedItem.second;5193Builder.CreateAlignmentAssumption(F->getDataLayout(),5194AlignedPtr, Alignment);5195}5196Builder.restoreIP(IP);5197}51985199if (IfCond) {5200ValueToValueMapTy VMap;5201createIfVersion(CanonicalLoop, IfCond, VMap, "simd");5202// Add metadata to the cloned loop which disables vectorization5203Value *MappedLatch = VMap.lookup(CanonicalLoop->getLatch());5204assert(MappedLatch &&5205"Cannot find value which corresponds to original loop latch");5206assert(isa<BasicBlock>(MappedLatch) &&5207"Cannot cast mapped latch block value to BasicBlock");5208BasicBlock *NewLatchBlock = dyn_cast<BasicBlock>(MappedLatch);5209ConstantAsMetadata *BoolConst =5210ConstantAsMetadata::get(ConstantInt::getFalse(Type::getInt1Ty(Ctx)));5211addBasicBlockMetadata(5212NewLatchBlock,5213{MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"),5214BoolConst})});5215}52165217SmallSet<BasicBlock *, 8> Reachable;52185219// Get the basic blocks from the loop in which memref instructions5220// can be found.5221// TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,5222// preferably without running any passes.5223for (BasicBlock *Block : L->getBlocks()) {5224if (Block == CanonicalLoop->getCond() ||5225Block == CanonicalLoop->getHeader())5226continue;5227Reachable.insert(Block);5228}52295230SmallVector<Metadata *> LoopMDList;52315232// In presence of finite 'safelen', it may be unsafe to mark all5233// the memory instructions parallel, because loop-carried5234// dependences of 'safelen' iterations are possible.5235// If clause order(concurrent) is specified then the memory instructions5236// are marked parallel even if 'safelen' is finite.5237if ((Safelen == nullptr) || (Order == OrderKind::OMP_ORDER_concurrent)) {5238// Add access group metadata to memory-access instructions.5239MDNode *AccessGroup = MDNode::getDistinct(Ctx, {});5240for (BasicBlock *BB : Reachable)5241addSimdMetadata(BB, AccessGroup, LI);5242// TODO: If the loop has existing parallel access metadata, have5243// to combine two lists.5244LoopMDList.push_back(MDNode::get(5245Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"), AccessGroup}));5246}52475248// Use the above access group metadata to create loop level5249// metadata, which should be distinct for each loop.5250ConstantAsMetadata *BoolConst =5251ConstantAsMetadata::get(ConstantInt::getTrue(Type::getInt1Ty(Ctx)));5252LoopMDList.push_back(MDNode::get(5253Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"), BoolConst}));52545255if (Simdlen || Safelen) {5256// If both simdlen and safelen clauses are specified, the value of the5257// simdlen parameter must be less than or equal to the value of the safelen5258// parameter. Therefore, use safelen only in the absence of simdlen.5259ConstantInt *VectorizeWidth = Simdlen == nullptr ? Safelen : Simdlen;5260LoopMDList.push_back(5261MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.width"),5262ConstantAsMetadata::get(VectorizeWidth)}));5263}52645265addLoopMetadata(CanonicalLoop, LoopMDList);5266}52675268/// Create the TargetMachine object to query the backend for optimization5269/// preferences.5270///5271/// Ideally, this would be passed from the front-end to the OpenMPBuilder, but5272/// e.g. Clang does not pass it to its CodeGen layer and creates it only when5273/// needed for the LLVM pass pipline. We use some default options to avoid5274/// having to pass too many settings from the frontend that probably do not5275/// matter.5276///5277/// Currently, TargetMachine is only used sometimes by the unrollLoopPartial5278/// method. If we are going to use TargetMachine for more purposes, especially5279/// those that are sensitive to TargetOptions, RelocModel and CodeModel, it5280/// might become be worth requiring front-ends to pass on their TargetMachine,5281/// or at least cache it between methods. Note that while fontends such as Clang5282/// have just a single main TargetMachine per translation unit, "target-cpu" and5283/// "target-features" that determine the TargetMachine are per-function and can5284/// be overrided using __attribute__((target("OPTIONS"))).5285static std::unique_ptr<TargetMachine>5286createTargetMachine(Function *F, CodeGenOptLevel OptLevel) {5287Module *M = F->getParent();52885289StringRef CPU = F->getFnAttribute("target-cpu").getValueAsString();5290StringRef Features = F->getFnAttribute("target-features").getValueAsString();5291const std::string &Triple = M->getTargetTriple();52925293std::string Error;5294const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);5295if (!TheTarget)5296return {};52975298llvm::TargetOptions Options;5299return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(5300Triple, CPU, Features, Options, /*RelocModel=*/std::nullopt,5301/*CodeModel=*/std::nullopt, OptLevel));5302}53035304/// Heuristically determine the best-performant unroll factor for \p CLI. This5305/// depends on the target processor. We are re-using the same heuristics as the5306/// LoopUnrollPass.5307static int32_t computeHeuristicUnrollFactor(CanonicalLoopInfo *CLI) {5308Function *F = CLI->getFunction();53095310// Assume the user requests the most aggressive unrolling, even if the rest of5311// the code is optimized using a lower setting.5312CodeGenOptLevel OptLevel = CodeGenOptLevel::Aggressive;5313std::unique_ptr<TargetMachine> TM = createTargetMachine(F, OptLevel);53145315FunctionAnalysisManager FAM;5316FAM.registerPass([]() { return TargetLibraryAnalysis(); });5317FAM.registerPass([]() { return AssumptionAnalysis(); });5318FAM.registerPass([]() { return DominatorTreeAnalysis(); });5319FAM.registerPass([]() { return LoopAnalysis(); });5320FAM.registerPass([]() { return ScalarEvolutionAnalysis(); });5321FAM.registerPass([]() { return PassInstrumentationAnalysis(); });5322TargetIRAnalysis TIRA;5323if (TM)5324TIRA = TargetIRAnalysis(5325[&](const Function &F) { return TM->getTargetTransformInfo(F); });5326FAM.registerPass([&]() { return TIRA; });53275328TargetIRAnalysis::Result &&TTI = TIRA.run(*F, FAM);5329ScalarEvolutionAnalysis SEA;5330ScalarEvolution &&SE = SEA.run(*F, FAM);5331DominatorTreeAnalysis DTA;5332DominatorTree &&DT = DTA.run(*F, FAM);5333LoopAnalysis LIA;5334LoopInfo &&LI = LIA.run(*F, FAM);5335AssumptionAnalysis ACT;5336AssumptionCache &&AC = ACT.run(*F, FAM);5337OptimizationRemarkEmitter ORE{F};53385339Loop *L = LI.getLoopFor(CLI->getHeader());5340assert(L && "Expecting CanonicalLoopInfo to be recognized as a loop");53415342TargetTransformInfo::UnrollingPreferences UP =5343gatherUnrollingPreferences(L, SE, TTI,5344/*BlockFrequencyInfo=*/nullptr,5345/*ProfileSummaryInfo=*/nullptr, ORE, static_cast<int>(OptLevel),5346/*UserThreshold=*/std::nullopt,5347/*UserCount=*/std::nullopt,5348/*UserAllowPartial=*/true,5349/*UserAllowRuntime=*/true,5350/*UserUpperBound=*/std::nullopt,5351/*UserFullUnrollMaxCount=*/std::nullopt);53525353UP.Force = true;53545355// Account for additional optimizations taking place before the LoopUnrollPass5356// would unroll the loop.5357UP.Threshold *= UnrollThresholdFactor;5358UP.PartialThreshold *= UnrollThresholdFactor;53595360// Use normal unroll factors even if the rest of the code is optimized for5361// size.5362UP.OptSizeThreshold = UP.Threshold;5363UP.PartialOptSizeThreshold = UP.PartialThreshold;53645365LLVM_DEBUG(dbgs() << "Unroll heuristic thresholds:\n"5366<< " Threshold=" << UP.Threshold << "\n"5367<< " PartialThreshold=" << UP.PartialThreshold << "\n"5368<< " OptSizeThreshold=" << UP.OptSizeThreshold << "\n"5369<< " PartialOptSizeThreshold="5370<< UP.PartialOptSizeThreshold << "\n");53715372// Disable peeling.5373TargetTransformInfo::PeelingPreferences PP =5374gatherPeelingPreferences(L, SE, TTI,5375/*UserAllowPeeling=*/false,5376/*UserAllowProfileBasedPeeling=*/false,5377/*UnrollingSpecficValues=*/false);53785379SmallPtrSet<const Value *, 32> EphValues;5380CodeMetrics::collectEphemeralValues(L, &AC, EphValues);53815382// Assume that reads and writes to stack variables can be eliminated by5383// Mem2Reg, SROA or LICM. That is, don't count them towards the loop body's5384// size.5385for (BasicBlock *BB : L->blocks()) {5386for (Instruction &I : *BB) {5387Value *Ptr;5388if (auto *Load = dyn_cast<LoadInst>(&I)) {5389Ptr = Load->getPointerOperand();5390} else if (auto *Store = dyn_cast<StoreInst>(&I)) {5391Ptr = Store->getPointerOperand();5392} else5393continue;53945395Ptr = Ptr->stripPointerCasts();53965397if (auto *Alloca = dyn_cast<AllocaInst>(Ptr)) {5398if (Alloca->getParent() == &F->getEntryBlock())5399EphValues.insert(&I);5400}5401}5402}54035404UnrollCostEstimator UCE(L, TTI, EphValues, UP.BEInsns);54055406// Loop is not unrollable if the loop contains certain instructions.5407if (!UCE.canUnroll()) {5408LLVM_DEBUG(dbgs() << "Loop not considered unrollable\n");5409return 1;5410}54115412LLVM_DEBUG(dbgs() << "Estimated loop size is " << UCE.getRolledLoopSize()5413<< "\n");54145415// TODO: Determine trip count of \p CLI if constant, computeUnrollCount might5416// be able to use it.5417int TripCount = 0;5418int MaxTripCount = 0;5419bool MaxOrZero = false;5420unsigned TripMultiple = 0;54215422bool UseUpperBound = false;5423computeUnrollCount(L, TTI, DT, &LI, &AC, SE, EphValues, &ORE, TripCount,5424MaxTripCount, MaxOrZero, TripMultiple, UCE, UP, PP,5425UseUpperBound);5426unsigned Factor = UP.Count;5427LLVM_DEBUG(dbgs() << "Suggesting unroll factor of " << Factor << "\n");54285429// This function returns 1 to signal to not unroll a loop.5430if (Factor == 0)5431return 1;5432return Factor;5433}54345435void OpenMPIRBuilder::unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop,5436int32_t Factor,5437CanonicalLoopInfo **UnrolledCLI) {5438assert(Factor >= 0 && "Unroll factor must not be negative");54395440Function *F = Loop->getFunction();5441LLVMContext &Ctx = F->getContext();54425443// If the unrolled loop is not used for another loop-associated directive, it5444// is sufficient to add metadata for the LoopUnrollPass.5445if (!UnrolledCLI) {5446SmallVector<Metadata *, 2> LoopMetadata;5447LoopMetadata.push_back(5448MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));54495450if (Factor >= 1) {5451ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(5452ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));5453LoopMetadata.push_back(MDNode::get(5454Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));5455}54565457addLoopMetadata(Loop, LoopMetadata);5458return;5459}54605461// Heuristically determine the unroll factor.5462if (Factor == 0)5463Factor = computeHeuristicUnrollFactor(Loop);54645465// No change required with unroll factor 1.5466if (Factor == 1) {5467*UnrolledCLI = Loop;5468return;5469}54705471assert(Factor >= 2 &&5472"unrolling only makes sense with a factor of 2 or larger");54735474Type *IndVarTy = Loop->getIndVarType();54755476// Apply partial unrolling by tiling the loop by the unroll-factor, then fully5477// unroll the inner loop.5478Value *FactorVal =5479ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,5480/*isSigned=*/false));5481std::vector<CanonicalLoopInfo *> LoopNest =5482tileLoops(DL, {Loop}, {FactorVal});5483assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");5484*UnrolledCLI = LoopNest[0];5485CanonicalLoopInfo *InnerLoop = LoopNest[1];54865487// LoopUnrollPass can only fully unroll loops with constant trip count.5488// Unroll by the unroll factor with a fallback epilog for the remainder5489// iterations if necessary.5490ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(5491ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));5492addLoopMetadata(5493InnerLoop,5494{MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),5495MDNode::get(5496Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});54975498#ifndef NDEBUG5499(*UnrolledCLI)->assertOK();5500#endif5501}55025503OpenMPIRBuilder::InsertPointTy5504OpenMPIRBuilder::createCopyPrivate(const LocationDescription &Loc,5505llvm::Value *BufSize, llvm::Value *CpyBuf,5506llvm::Value *CpyFn, llvm::Value *DidIt) {5507if (!updateToLocation(Loc))5508return Loc.IP;55095510uint32_t SrcLocStrSize;5511Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5512Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5513Value *ThreadId = getOrCreateThreadID(Ident);55145515llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);55165517Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};55185519Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);5520Builder.CreateCall(Fn, Args);55215522return Builder.saveIP();5523}55245525OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSingle(5526const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,5527FinalizeCallbackTy FiniCB, bool IsNowait, ArrayRef<llvm::Value *> CPVars,5528ArrayRef<llvm::Function *> CPFuncs) {55295530if (!updateToLocation(Loc))5531return Loc.IP;55325533// If needed allocate and initialize `DidIt` with 0.5534// DidIt: flag variable: 1=single thread; 0=not single thread.5535llvm::Value *DidIt = nullptr;5536if (!CPVars.empty()) {5537DidIt = Builder.CreateAlloca(llvm::Type::getInt32Ty(Builder.getContext()));5538Builder.CreateStore(Builder.getInt32(0), DidIt);5539}55405541Directive OMPD = Directive::OMPD_single;5542uint32_t SrcLocStrSize;5543Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5544Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5545Value *ThreadId = getOrCreateThreadID(Ident);5546Value *Args[] = {Ident, ThreadId};55475548Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);5549Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);55505551Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);5552Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);55535554auto FiniCBWrapper = [&](InsertPointTy IP) {5555FiniCB(IP);55565557// The thread that executes the single region must set `DidIt` to 1.5558// This is used by __kmpc_copyprivate, to know if the caller is the5559// single thread or not.5560if (DidIt)5561Builder.CreateStore(Builder.getInt32(1), DidIt);5562};55635564// generates the following:5565// if (__kmpc_single()) {5566// .... single region ...5567// __kmpc_end_single5568// }5569// __kmpc_copyprivate5570// __kmpc_barrier55715572EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCBWrapper,5573/*Conditional*/ true,5574/*hasFinalize*/ true);55755576if (DidIt) {5577for (size_t I = 0, E = CPVars.size(); I < E; ++I)5578// NOTE BufSize is currently unused, so just pass 0.5579createCopyPrivate(LocationDescription(Builder.saveIP(), Loc.DL),5580/*BufSize=*/ConstantInt::get(Int64, 0), CPVars[I],5581CPFuncs[I], DidIt);5582// NOTE __kmpc_copyprivate already inserts a barrier5583} else if (!IsNowait)5584createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),5585omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,5586/* CheckCancelFlag */ false);5587return Builder.saveIP();5588}55895590OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCritical(5591const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,5592FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {55935594if (!updateToLocation(Loc))5595return Loc.IP;55965597Directive OMPD = Directive::OMPD_critical;5598uint32_t SrcLocStrSize;5599Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5600Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5601Value *ThreadId = getOrCreateThreadID(Ident);5602Value *LockVar = getOMPCriticalRegionLock(CriticalName);5603Value *Args[] = {Ident, ThreadId, LockVar};56045605SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));5606Function *RTFn = nullptr;5607if (HintInst) {5608// Add Hint to entry Args and create call5609EnterArgs.push_back(HintInst);5610RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);5611} else {5612RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);5613}5614Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);56155616Function *ExitRTLFn =5617getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);5618Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);56195620return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,5621/*Conditional*/ false, /*hasFinalize*/ true);5622}56235624OpenMPIRBuilder::InsertPointTy5625OpenMPIRBuilder::createOrderedDepend(const LocationDescription &Loc,5626InsertPointTy AllocaIP, unsigned NumLoops,5627ArrayRef<llvm::Value *> StoreValues,5628const Twine &Name, bool IsDependSource) {5629assert(5630llvm::all_of(StoreValues,5631[](Value *SV) { return SV->getType()->isIntegerTy(64); }) &&5632"OpenMP runtime requires depend vec with i64 type");56335634if (!updateToLocation(Loc))5635return Loc.IP;56365637// Allocate space for vector and generate alloc instruction.5638auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);5639Builder.restoreIP(AllocaIP);5640AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);5641ArgsBase->setAlignment(Align(8));5642Builder.restoreIP(Loc.IP);56435644// Store the index value with offset in depend vector.5645for (unsigned I = 0; I < NumLoops; ++I) {5646Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(5647ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});5648StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);5649STInst->setAlignment(Align(8));5650}56515652Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(5653ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});56545655uint32_t SrcLocStrSize;5656Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5657Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5658Value *ThreadId = getOrCreateThreadID(Ident);5659Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};56605661Function *RTLFn = nullptr;5662if (IsDependSource)5663RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);5664else5665RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);5666Builder.CreateCall(RTLFn, Args);56675668return Builder.saveIP();5669}56705671OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createOrderedThreadsSimd(5672const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,5673FinalizeCallbackTy FiniCB, bool IsThreads) {5674if (!updateToLocation(Loc))5675return Loc.IP;56765677Directive OMPD = Directive::OMPD_ordered;5678Instruction *EntryCall = nullptr;5679Instruction *ExitCall = nullptr;56805681if (IsThreads) {5682uint32_t SrcLocStrSize;5683Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5684Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5685Value *ThreadId = getOrCreateThreadID(Ident);5686Value *Args[] = {Ident, ThreadId};56875688Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);5689EntryCall = Builder.CreateCall(EntryRTLFn, Args);56905691Function *ExitRTLFn =5692getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);5693ExitCall = Builder.CreateCall(ExitRTLFn, Args);5694}56955696return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,5697/*Conditional*/ false, /*hasFinalize*/ true);5698}56995700OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(5701Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,5702BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,5703bool HasFinalize, bool IsCancellable) {57045705if (HasFinalize)5706FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});57075708// Create inlined region's entry and body blocks, in preparation5709// for conditional creation5710BasicBlock *EntryBB = Builder.GetInsertBlock();5711Instruction *SplitPos = EntryBB->getTerminator();5712if (!isa_and_nonnull<BranchInst>(SplitPos))5713SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);5714BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");5715BasicBlock *FiniBB =5716EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");57175718Builder.SetInsertPoint(EntryBB->getTerminator());5719emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);57205721// generate body5722BodyGenCB(/* AllocaIP */ InsertPointTy(),5723/* CodeGenIP */ Builder.saveIP());57245725// emit exit call and do any needed finalization.5726auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());5727assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&5728FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&5729"Unexpected control flow graph state!!");5730emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);5731assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&5732"Unexpected Control Flow State!");5733MergeBlockIntoPredecessor(FiniBB);57345735// If we are skipping the region of a non conditional, remove the exit5736// block, and clear the builder's insertion point.5737assert(SplitPos->getParent() == ExitBB &&5738"Unexpected Insertion point location!");5739auto merged = MergeBlockIntoPredecessor(ExitBB);5740BasicBlock *ExitPredBB = SplitPos->getParent();5741auto InsertBB = merged ? ExitPredBB : ExitBB;5742if (!isa_and_nonnull<BranchInst>(SplitPos))5743SplitPos->eraseFromParent();5744Builder.SetInsertPoint(InsertBB);57455746return Builder.saveIP();5747}57485749OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(5750Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {5751// if nothing to do, Return current insertion point.5752if (!Conditional || !EntryCall)5753return Builder.saveIP();57545755BasicBlock *EntryBB = Builder.GetInsertBlock();5756Value *CallBool = Builder.CreateIsNotNull(EntryCall);5757auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");5758auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);57595760// Emit thenBB and set the Builder's insertion point there for5761// body generation next. Place the block after the current block.5762Function *CurFn = EntryBB->getParent();5763CurFn->insert(std::next(EntryBB->getIterator()), ThenBB);57645765// Move Entry branch to end of ThenBB, and replace with conditional5766// branch (If-stmt)5767Instruction *EntryBBTI = EntryBB->getTerminator();5768Builder.CreateCondBr(CallBool, ThenBB, ExitBB);5769EntryBBTI->removeFromParent();5770Builder.SetInsertPoint(UI);5771Builder.Insert(EntryBBTI);5772UI->eraseFromParent();5773Builder.SetInsertPoint(ThenBB->getTerminator());57745775// return an insertion point to ExitBB.5776return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());5777}57785779OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(5780omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,5781bool HasFinalize) {57825783Builder.restoreIP(FinIP);57845785// If there is finalization to do, emit it before the exit call5786if (HasFinalize) {5787assert(!FinalizationStack.empty() &&5788"Unexpected finalization stack state!");57895790FinalizationInfo Fi = FinalizationStack.pop_back_val();5791assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");57925793Fi.FiniCB(FinIP);57945795BasicBlock *FiniBB = FinIP.getBlock();5796Instruction *FiniBBTI = FiniBB->getTerminator();57975798// set Builder IP for call creation5799Builder.SetInsertPoint(FiniBBTI);5800}58015802if (!ExitCall)5803return Builder.saveIP();58045805// place the Exitcall as last instruction before Finalization block terminator5806ExitCall->removeFromParent();5807Builder.Insert(ExitCall);58085809return IRBuilder<>::InsertPoint(ExitCall->getParent(),5810ExitCall->getIterator());5811}58125813OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCopyinClauseBlocks(5814InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,5815llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {5816if (!IP.isSet())5817return IP;58185819IRBuilder<>::InsertPointGuard IPG(Builder);58205821// creates the following CFG structure5822// OMP_Entry : (MasterAddr != PrivateAddr)?5823// F T5824// | \5825// | copin.not.master5826// | /5827// v /5828// copyin.not.master.end5829// |5830// v5831// OMP.Entry.Next58325833BasicBlock *OMP_Entry = IP.getBlock();5834Function *CurFn = OMP_Entry->getParent();5835BasicBlock *CopyBegin =5836BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);5837BasicBlock *CopyEnd = nullptr;58385839// If entry block is terminated, split to preserve the branch to following5840// basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.5841if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {5842CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),5843"copyin.not.master.end");5844OMP_Entry->getTerminator()->eraseFromParent();5845} else {5846CopyEnd =5847BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);5848}58495850Builder.SetInsertPoint(OMP_Entry);5851Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);5852Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);5853Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);5854Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);58555856Builder.SetInsertPoint(CopyBegin);5857if (BranchtoEnd)5858Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));58595860return Builder.saveIP();5861}58625863CallInst *OpenMPIRBuilder::createOMPAlloc(const LocationDescription &Loc,5864Value *Size, Value *Allocator,5865std::string Name) {5866IRBuilder<>::InsertPointGuard IPG(Builder);5867updateToLocation(Loc);58685869uint32_t SrcLocStrSize;5870Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5871Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5872Value *ThreadId = getOrCreateThreadID(Ident);5873Value *Args[] = {ThreadId, Size, Allocator};58745875Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);58765877return Builder.CreateCall(Fn, Args, Name);5878}58795880CallInst *OpenMPIRBuilder::createOMPFree(const LocationDescription &Loc,5881Value *Addr, Value *Allocator,5882std::string Name) {5883IRBuilder<>::InsertPointGuard IPG(Builder);5884updateToLocation(Loc);58855886uint32_t SrcLocStrSize;5887Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5888Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5889Value *ThreadId = getOrCreateThreadID(Ident);5890Value *Args[] = {ThreadId, Addr, Allocator};5891Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);5892return Builder.CreateCall(Fn, Args, Name);5893}58945895CallInst *OpenMPIRBuilder::createOMPInteropInit(5896const LocationDescription &Loc, Value *InteropVar,5897omp::OMPInteropType InteropType, Value *Device, Value *NumDependences,5898Value *DependenceAddress, bool HaveNowaitClause) {5899IRBuilder<>::InsertPointGuard IPG(Builder);5900updateToLocation(Loc);59015902uint32_t SrcLocStrSize;5903Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5904Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5905Value *ThreadId = getOrCreateThreadID(Ident);5906if (Device == nullptr)5907Device = ConstantInt::get(Int32, -1);5908Constant *InteropTypeVal = ConstantInt::get(Int32, (int)InteropType);5909if (NumDependences == nullptr) {5910NumDependences = ConstantInt::get(Int32, 0);5911PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());5912DependenceAddress = ConstantPointerNull::get(PointerTypeVar);5913}5914Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);5915Value *Args[] = {5916Ident, ThreadId, InteropVar, InteropTypeVal,5917Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};59185919Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);59205921return Builder.CreateCall(Fn, Args);5922}59235924CallInst *OpenMPIRBuilder::createOMPInteropDestroy(5925const LocationDescription &Loc, Value *InteropVar, Value *Device,5926Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {5927IRBuilder<>::InsertPointGuard IPG(Builder);5928updateToLocation(Loc);59295930uint32_t SrcLocStrSize;5931Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5932Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5933Value *ThreadId = getOrCreateThreadID(Ident);5934if (Device == nullptr)5935Device = ConstantInt::get(Int32, -1);5936if (NumDependences == nullptr) {5937NumDependences = ConstantInt::get(Int32, 0);5938PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());5939DependenceAddress = ConstantPointerNull::get(PointerTypeVar);5940}5941Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);5942Value *Args[] = {5943Ident, ThreadId, InteropVar, Device,5944NumDependences, DependenceAddress, HaveNowaitClauseVal};59455946Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);59475948return Builder.CreateCall(Fn, Args);5949}59505951CallInst *OpenMPIRBuilder::createOMPInteropUse(const LocationDescription &Loc,5952Value *InteropVar, Value *Device,5953Value *NumDependences,5954Value *DependenceAddress,5955bool HaveNowaitClause) {5956IRBuilder<>::InsertPointGuard IPG(Builder);5957updateToLocation(Loc);5958uint32_t SrcLocStrSize;5959Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5960Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5961Value *ThreadId = getOrCreateThreadID(Ident);5962if (Device == nullptr)5963Device = ConstantInt::get(Int32, -1);5964if (NumDependences == nullptr) {5965NumDependences = ConstantInt::get(Int32, 0);5966PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());5967DependenceAddress = ConstantPointerNull::get(PointerTypeVar);5968}5969Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);5970Value *Args[] = {5971Ident, ThreadId, InteropVar, Device,5972NumDependences, DependenceAddress, HaveNowaitClauseVal};59735974Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);59755976return Builder.CreateCall(Fn, Args);5977}59785979CallInst *OpenMPIRBuilder::createCachedThreadPrivate(5980const LocationDescription &Loc, llvm::Value *Pointer,5981llvm::ConstantInt *Size, const llvm::Twine &Name) {5982IRBuilder<>::InsertPointGuard IPG(Builder);5983updateToLocation(Loc);59845985uint32_t SrcLocStrSize;5986Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);5987Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);5988Value *ThreadId = getOrCreateThreadID(Ident);5989Constant *ThreadPrivateCache =5990getOrCreateInternalVariable(Int8PtrPtr, Name.str());5991llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};59925993Function *Fn =5994getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);59955996return Builder.CreateCall(Fn, Args);5997}59985999OpenMPIRBuilder::InsertPointTy6000OpenMPIRBuilder::createTargetInit(const LocationDescription &Loc, bool IsSPMD,6001int32_t MinThreadsVal, int32_t MaxThreadsVal,6002int32_t MinTeamsVal, int32_t MaxTeamsVal) {6003if (!updateToLocation(Loc))6004return Loc.IP;60056006uint32_t SrcLocStrSize;6007Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);6008Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);6009Constant *IsSPMDVal = ConstantInt::getSigned(6010Int8, IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);6011Constant *UseGenericStateMachineVal = ConstantInt::getSigned(Int8, !IsSPMD);6012Constant *MayUseNestedParallelismVal = ConstantInt::getSigned(Int8, true);6013Constant *DebugIndentionLevelVal = ConstantInt::getSigned(Int16, 0);60146015Function *Kernel = Builder.GetInsertBlock()->getParent();60166017// Manifest the launch configuration in the metadata matching the kernel6018// environment.6019if (MinTeamsVal > 1 || MaxTeamsVal > 0)6020writeTeamsForKernel(T, *Kernel, MinTeamsVal, MaxTeamsVal);60216022// For max values, < 0 means unset, == 0 means set but unknown.6023if (MaxThreadsVal < 0)6024MaxThreadsVal = std::max(6025int32_t(getGridValue(T, Kernel).GV_Default_WG_Size), MinThreadsVal);60266027if (MaxThreadsVal > 0)6028writeThreadBoundsForKernel(T, *Kernel, MinThreadsVal, MaxThreadsVal);60296030Constant *MinThreads = ConstantInt::getSigned(Int32, MinThreadsVal);6031Constant *MaxThreads = ConstantInt::getSigned(Int32, MaxThreadsVal);6032Constant *MinTeams = ConstantInt::getSigned(Int32, MinTeamsVal);6033Constant *MaxTeams = ConstantInt::getSigned(Int32, MaxTeamsVal);6034Constant *ReductionDataSize = ConstantInt::getSigned(Int32, 0);6035Constant *ReductionBufferLength = ConstantInt::getSigned(Int32, 0);60366037// We need to strip the debug prefix to get the correct kernel name.6038StringRef KernelName = Kernel->getName();6039const std::string DebugPrefix = "_debug__";6040if (KernelName.ends_with(DebugPrefix))6041KernelName = KernelName.drop_back(DebugPrefix.length());60426043Function *Fn = getOrCreateRuntimeFunctionPtr(6044omp::RuntimeFunction::OMPRTL___kmpc_target_init);6045const DataLayout &DL = Fn->getDataLayout();60466047Twine DynamicEnvironmentName = KernelName + "_dynamic_environment";6048Constant *DynamicEnvironmentInitializer =6049ConstantStruct::get(DynamicEnvironment, {DebugIndentionLevelVal});6050GlobalVariable *DynamicEnvironmentGV = new GlobalVariable(6051M, DynamicEnvironment, /*IsConstant=*/false, GlobalValue::WeakODRLinkage,6052DynamicEnvironmentInitializer, DynamicEnvironmentName,6053/*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,6054DL.getDefaultGlobalsAddressSpace());6055DynamicEnvironmentGV->setVisibility(GlobalValue::ProtectedVisibility);60566057Constant *DynamicEnvironment =6058DynamicEnvironmentGV->getType() == DynamicEnvironmentPtr6059? DynamicEnvironmentGV6060: ConstantExpr::getAddrSpaceCast(DynamicEnvironmentGV,6061DynamicEnvironmentPtr);60626063Constant *ConfigurationEnvironmentInitializer = ConstantStruct::get(6064ConfigurationEnvironment, {6065UseGenericStateMachineVal,6066MayUseNestedParallelismVal,6067IsSPMDVal,6068MinThreads,6069MaxThreads,6070MinTeams,6071MaxTeams,6072ReductionDataSize,6073ReductionBufferLength,6074});6075Constant *KernelEnvironmentInitializer = ConstantStruct::get(6076KernelEnvironment, {6077ConfigurationEnvironmentInitializer,6078Ident,6079DynamicEnvironment,6080});6081std::string KernelEnvironmentName =6082(KernelName + "_kernel_environment").str();6083GlobalVariable *KernelEnvironmentGV = new GlobalVariable(6084M, KernelEnvironment, /*IsConstant=*/true, GlobalValue::WeakODRLinkage,6085KernelEnvironmentInitializer, KernelEnvironmentName,6086/*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,6087DL.getDefaultGlobalsAddressSpace());6088KernelEnvironmentGV->setVisibility(GlobalValue::ProtectedVisibility);60896090Constant *KernelEnvironment =6091KernelEnvironmentGV->getType() == KernelEnvironmentPtr6092? KernelEnvironmentGV6093: ConstantExpr::getAddrSpaceCast(KernelEnvironmentGV,6094KernelEnvironmentPtr);6095Value *KernelLaunchEnvironment = Kernel->getArg(0);6096CallInst *ThreadKind =6097Builder.CreateCall(Fn, {KernelEnvironment, KernelLaunchEnvironment});60986099Value *ExecUserCode = Builder.CreateICmpEQ(6100ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),6101"exec_user_code");61026103// ThreadKind = __kmpc_target_init(...)6104// if (ThreadKind == -1)6105// user_code6106// else6107// return;61086109auto *UI = Builder.CreateUnreachable();6110BasicBlock *CheckBB = UI->getParent();6111BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");61126113BasicBlock *WorkerExitBB = BasicBlock::Create(6114CheckBB->getContext(), "worker.exit", CheckBB->getParent());6115Builder.SetInsertPoint(WorkerExitBB);6116Builder.CreateRetVoid();61176118auto *CheckBBTI = CheckBB->getTerminator();6119Builder.SetInsertPoint(CheckBBTI);6120Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);61216122CheckBBTI->eraseFromParent();6123UI->eraseFromParent();61246125// Continue in the "user_code" block, see diagram above and in6126// openmp/libomptarget/deviceRTLs/common/include/target.h .6127return InsertPointTy(UserCodeEntryBB, UserCodeEntryBB->getFirstInsertionPt());6128}61296130void OpenMPIRBuilder::createTargetDeinit(const LocationDescription &Loc,6131int32_t TeamsReductionDataSize,6132int32_t TeamsReductionBufferLength) {6133if (!updateToLocation(Loc))6134return;61356136Function *Fn = getOrCreateRuntimeFunctionPtr(6137omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);61386139Builder.CreateCall(Fn, {});61406141if (!TeamsReductionBufferLength || !TeamsReductionDataSize)6142return;61436144Function *Kernel = Builder.GetInsertBlock()->getParent();6145// We need to strip the debug prefix to get the correct kernel name.6146StringRef KernelName = Kernel->getName();6147const std::string DebugPrefix = "_debug__";6148if (KernelName.ends_with(DebugPrefix))6149KernelName = KernelName.drop_back(DebugPrefix.length());6150auto *KernelEnvironmentGV =6151M.getNamedGlobal((KernelName + "_kernel_environment").str());6152assert(KernelEnvironmentGV && "Expected kernel environment global\n");6153auto *KernelEnvironmentInitializer = KernelEnvironmentGV->getInitializer();6154auto *NewInitializer = ConstantFoldInsertValueInstruction(6155KernelEnvironmentInitializer,6156ConstantInt::get(Int32, TeamsReductionDataSize), {0, 7});6157NewInitializer = ConstantFoldInsertValueInstruction(6158NewInitializer, ConstantInt::get(Int32, TeamsReductionBufferLength),6159{0, 8});6160KernelEnvironmentGV->setInitializer(NewInitializer);6161}61626163static MDNode *getNVPTXMDNode(Function &Kernel, StringRef Name) {6164Module &M = *Kernel.getParent();6165NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");6166for (auto *Op : MD->operands()) {6167if (Op->getNumOperands() != 3)6168continue;6169auto *KernelOp = dyn_cast<ConstantAsMetadata>(Op->getOperand(0));6170if (!KernelOp || KernelOp->getValue() != &Kernel)6171continue;6172auto *Prop = dyn_cast<MDString>(Op->getOperand(1));6173if (!Prop || Prop->getString() != Name)6174continue;6175return Op;6176}6177return nullptr;6178}61796180static void updateNVPTXMetadata(Function &Kernel, StringRef Name, int32_t Value,6181bool Min) {6182// Update the "maxntidx" metadata for NVIDIA, or add it.6183MDNode *ExistingOp = getNVPTXMDNode(Kernel, Name);6184if (ExistingOp) {6185auto *OldVal = cast<ConstantAsMetadata>(ExistingOp->getOperand(2));6186int32_t OldLimit = cast<ConstantInt>(OldVal->getValue())->getZExtValue();6187ExistingOp->replaceOperandWith(61882, ConstantAsMetadata::get(ConstantInt::get(6189OldVal->getValue()->getType(),6190Min ? std::min(OldLimit, Value) : std::max(OldLimit, Value))));6191} else {6192LLVMContext &Ctx = Kernel.getContext();6193Metadata *MDVals[] = {ConstantAsMetadata::get(&Kernel),6194MDString::get(Ctx, Name),6195ConstantAsMetadata::get(6196ConstantInt::get(Type::getInt32Ty(Ctx), Value))};6197// Append metadata to nvvm.annotations6198Module &M = *Kernel.getParent();6199NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");6200MD->addOperand(MDNode::get(Ctx, MDVals));6201}6202}62036204std::pair<int32_t, int32_t>6205OpenMPIRBuilder::readThreadBoundsForKernel(const Triple &T, Function &Kernel) {6206int32_t ThreadLimit =6207Kernel.getFnAttributeAsParsedInteger("omp_target_thread_limit");62086209if (T.isAMDGPU()) {6210const auto &Attr = Kernel.getFnAttribute("amdgpu-flat-work-group-size");6211if (!Attr.isValid() || !Attr.isStringAttribute())6212return {0, ThreadLimit};6213auto [LBStr, UBStr] = Attr.getValueAsString().split(',');6214int32_t LB, UB;6215if (!llvm::to_integer(UBStr, UB, 10))6216return {0, ThreadLimit};6217UB = ThreadLimit ? std::min(ThreadLimit, UB) : UB;6218if (!llvm::to_integer(LBStr, LB, 10))6219return {0, UB};6220return {LB, UB};6221}62226223if (MDNode *ExistingOp = getNVPTXMDNode(Kernel, "maxntidx")) {6224auto *OldVal = cast<ConstantAsMetadata>(ExistingOp->getOperand(2));6225int32_t UB = cast<ConstantInt>(OldVal->getValue())->getZExtValue();6226return {0, ThreadLimit ? std::min(ThreadLimit, UB) : UB};6227}6228return {0, ThreadLimit};6229}62306231void OpenMPIRBuilder::writeThreadBoundsForKernel(const Triple &T,6232Function &Kernel, int32_t LB,6233int32_t UB) {6234Kernel.addFnAttr("omp_target_thread_limit", std::to_string(UB));62356236if (T.isAMDGPU()) {6237Kernel.addFnAttr("amdgpu-flat-work-group-size",6238llvm::utostr(LB) + "," + llvm::utostr(UB));6239return;6240}62416242updateNVPTXMetadata(Kernel, "maxntidx", UB, true);6243}62446245std::pair<int32_t, int32_t>6246OpenMPIRBuilder::readTeamBoundsForKernel(const Triple &, Function &Kernel) {6247// TODO: Read from backend annotations if available.6248return {0, Kernel.getFnAttributeAsParsedInteger("omp_target_num_teams")};6249}62506251void OpenMPIRBuilder::writeTeamsForKernel(const Triple &T, Function &Kernel,6252int32_t LB, int32_t UB) {6253if (T.isNVPTX())6254if (UB > 0)6255updateNVPTXMetadata(Kernel, "maxclusterrank", UB, true);6256if (T.isAMDGPU())6257Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(LB) + ",1,1");62586259Kernel.addFnAttr("omp_target_num_teams", std::to_string(LB));6260}62616262void OpenMPIRBuilder::setOutlinedTargetRegionFunctionAttributes(6263Function *OutlinedFn) {6264if (Config.isTargetDevice()) {6265OutlinedFn->setLinkage(GlobalValue::WeakODRLinkage);6266// TODO: Determine if DSO local can be set to true.6267OutlinedFn->setDSOLocal(false);6268OutlinedFn->setVisibility(GlobalValue::ProtectedVisibility);6269if (T.isAMDGCN())6270OutlinedFn->setCallingConv(CallingConv::AMDGPU_KERNEL);6271}6272}62736274Constant *OpenMPIRBuilder::createOutlinedFunctionID(Function *OutlinedFn,6275StringRef EntryFnIDName) {6276if (Config.isTargetDevice()) {6277assert(OutlinedFn && "The outlined function must exist if embedded");6278return OutlinedFn;6279}62806281return new GlobalVariable(6282M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::WeakAnyLinkage,6283Constant::getNullValue(Builder.getInt8Ty()), EntryFnIDName);6284}62856286Constant *OpenMPIRBuilder::createTargetRegionEntryAddr(Function *OutlinedFn,6287StringRef EntryFnName) {6288if (OutlinedFn)6289return OutlinedFn;62906291assert(!M.getGlobalVariable(EntryFnName, true) &&6292"Named kernel already exists?");6293return new GlobalVariable(6294M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::InternalLinkage,6295Constant::getNullValue(Builder.getInt8Ty()), EntryFnName);6296}62976298void OpenMPIRBuilder::emitTargetRegionFunction(6299TargetRegionEntryInfo &EntryInfo,6300FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry,6301Function *&OutlinedFn, Constant *&OutlinedFnID) {63026303SmallString<64> EntryFnName;6304OffloadInfoManager.getTargetRegionEntryFnName(EntryFnName, EntryInfo);63056306OutlinedFn = Config.isTargetDevice() || !Config.openMPOffloadMandatory()6307? GenerateFunctionCallback(EntryFnName)6308: nullptr;63096310// If this target outline function is not an offload entry, we don't need to6311// register it. This may be in the case of a false if clause, or if there are6312// no OpenMP targets.6313if (!IsOffloadEntry)6314return;63156316std::string EntryFnIDName =6317Config.isTargetDevice()6318? std::string(EntryFnName)6319: createPlatformSpecificName({EntryFnName, "region_id"});63206321OutlinedFnID = registerTargetRegionFunction(EntryInfo, OutlinedFn,6322EntryFnName, EntryFnIDName);6323}63246325Constant *OpenMPIRBuilder::registerTargetRegionFunction(6326TargetRegionEntryInfo &EntryInfo, Function *OutlinedFn,6327StringRef EntryFnName, StringRef EntryFnIDName) {6328if (OutlinedFn)6329setOutlinedTargetRegionFunctionAttributes(OutlinedFn);6330auto OutlinedFnID = createOutlinedFunctionID(OutlinedFn, EntryFnIDName);6331auto EntryAddr = createTargetRegionEntryAddr(OutlinedFn, EntryFnName);6332OffloadInfoManager.registerTargetRegionEntryInfo(6333EntryInfo, EntryAddr, OutlinedFnID,6334OffloadEntriesInfoManager::OMPTargetRegionEntryTargetRegion);6335return OutlinedFnID;6336}63376338OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createTargetData(6339const LocationDescription &Loc, InsertPointTy AllocaIP,6340InsertPointTy CodeGenIP, Value *DeviceID, Value *IfCond,6341TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB,6342omp::RuntimeFunction *MapperFunc,6343function_ref<InsertPointTy(InsertPointTy CodeGenIP, BodyGenTy BodyGenType)>6344BodyGenCB,6345function_ref<void(unsigned int, Value *)> DeviceAddrCB,6346function_ref<Value *(unsigned int)> CustomMapperCB, Value *SrcLocInfo) {6347if (!updateToLocation(Loc))6348return InsertPointTy();63496350// Disable TargetData CodeGen on Device pass.6351if (Config.IsTargetDevice.value_or(false)) {6352if (BodyGenCB)6353Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));6354return Builder.saveIP();6355}63566357Builder.restoreIP(CodeGenIP);6358bool IsStandAlone = !BodyGenCB;6359MapInfosTy *MapInfo;6360// Generate the code for the opening of the data environment. Capture all the6361// arguments of the runtime call by reference because they are used in the6362// closing of the region.6363auto BeginThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {6364MapInfo = &GenMapInfoCB(Builder.saveIP());6365emitOffloadingArrays(AllocaIP, Builder.saveIP(), *MapInfo, Info,6366/*IsNonContiguous=*/true, DeviceAddrCB,6367CustomMapperCB);63686369TargetDataRTArgs RTArgs;6370emitOffloadingArraysArgument(Builder, RTArgs, Info,6371!MapInfo->Names.empty());63726373// Emit the number of elements in the offloading arrays.6374Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);63756376// Source location for the ident struct6377if (!SrcLocInfo) {6378uint32_t SrcLocStrSize;6379Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);6380SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);6381}63826383Value *OffloadingArgs[] = {SrcLocInfo, DeviceID,6384PointerNum, RTArgs.BasePointersArray,6385RTArgs.PointersArray, RTArgs.SizesArray,6386RTArgs.MapTypesArray, RTArgs.MapNamesArray,6387RTArgs.MappersArray};63886389if (IsStandAlone) {6390assert(MapperFunc && "MapperFunc missing for standalone target data");6391Builder.CreateCall(getOrCreateRuntimeFunctionPtr(*MapperFunc),6392OffloadingArgs);6393} else {6394Function *BeginMapperFunc = getOrCreateRuntimeFunctionPtr(6395omp::OMPRTL___tgt_target_data_begin_mapper);63966397Builder.CreateCall(BeginMapperFunc, OffloadingArgs);63986399for (auto DeviceMap : Info.DevicePtrInfoMap) {6400if (isa<AllocaInst>(DeviceMap.second.second)) {6401auto *LI =6402Builder.CreateLoad(Builder.getPtrTy(), DeviceMap.second.first);6403Builder.CreateStore(LI, DeviceMap.second.second);6404}6405}64066407// If device pointer privatization is required, emit the body of the6408// region here. It will have to be duplicated: with and without6409// privatization.6410Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::Priv));6411}6412};64136414// If we need device pointer privatization, we need to emit the body of the6415// region with no privatization in the 'else' branch of the conditional.6416// Otherwise, we don't have to do anything.6417auto BeginElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {6418Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::DupNoPriv));6419};64206421// Generate code for the closing of the data region.6422auto EndThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {6423TargetDataRTArgs RTArgs;6424emitOffloadingArraysArgument(Builder, RTArgs, Info, !MapInfo->Names.empty(),6425/*ForEndCall=*/true);64266427// Emit the number of elements in the offloading arrays.6428Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);64296430// Source location for the ident struct6431if (!SrcLocInfo) {6432uint32_t SrcLocStrSize;6433Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);6434SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);6435}64366437Value *OffloadingArgs[] = {SrcLocInfo, DeviceID,6438PointerNum, RTArgs.BasePointersArray,6439RTArgs.PointersArray, RTArgs.SizesArray,6440RTArgs.MapTypesArray, RTArgs.MapNamesArray,6441RTArgs.MappersArray};6442Function *EndMapperFunc =6443getOrCreateRuntimeFunctionPtr(omp::OMPRTL___tgt_target_data_end_mapper);64446445Builder.CreateCall(EndMapperFunc, OffloadingArgs);6446};64476448// We don't have to do anything to close the region if the if clause evaluates6449// to false.6450auto EndElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {};64516452if (BodyGenCB) {6453if (IfCond) {6454emitIfClause(IfCond, BeginThenGen, BeginElseGen, AllocaIP);6455} else {6456BeginThenGen(AllocaIP, Builder.saveIP());6457}64586459// If we don't require privatization of device pointers, we emit the body in6460// between the runtime calls. This avoids duplicating the body code.6461Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));64626463if (IfCond) {6464emitIfClause(IfCond, EndThenGen, EndElseGen, AllocaIP);6465} else {6466EndThenGen(AllocaIP, Builder.saveIP());6467}6468} else {6469if (IfCond) {6470emitIfClause(IfCond, BeginThenGen, EndElseGen, AllocaIP);6471} else {6472BeginThenGen(AllocaIP, Builder.saveIP());6473}6474}64756476return Builder.saveIP();6477}64786479FunctionCallee6480OpenMPIRBuilder::createForStaticInitFunction(unsigned IVSize, bool IVSigned,6481bool IsGPUDistribute) {6482assert((IVSize == 32 || IVSize == 64) &&6483"IV size is not compatible with the omp runtime");6484RuntimeFunction Name;6485if (IsGPUDistribute)6486Name = IVSize == 326487? (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_46488: omp::OMPRTL___kmpc_distribute_static_init_4u)6489: (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_86490: omp::OMPRTL___kmpc_distribute_static_init_8u);6491else6492Name = IVSize == 32 ? (IVSigned ? omp::OMPRTL___kmpc_for_static_init_46493: omp::OMPRTL___kmpc_for_static_init_4u)6494: (IVSigned ? omp::OMPRTL___kmpc_for_static_init_86495: omp::OMPRTL___kmpc_for_static_init_8u);64966497return getOrCreateRuntimeFunction(M, Name);6498}64996500FunctionCallee OpenMPIRBuilder::createDispatchInitFunction(unsigned IVSize,6501bool IVSigned) {6502assert((IVSize == 32 || IVSize == 64) &&6503"IV size is not compatible with the omp runtime");6504RuntimeFunction Name = IVSize == 326505? (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_46506: omp::OMPRTL___kmpc_dispatch_init_4u)6507: (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_86508: omp::OMPRTL___kmpc_dispatch_init_8u);65096510return getOrCreateRuntimeFunction(M, Name);6511}65126513FunctionCallee OpenMPIRBuilder::createDispatchNextFunction(unsigned IVSize,6514bool IVSigned) {6515assert((IVSize == 32 || IVSize == 64) &&6516"IV size is not compatible with the omp runtime");6517RuntimeFunction Name = IVSize == 326518? (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_46519: omp::OMPRTL___kmpc_dispatch_next_4u)6520: (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_86521: omp::OMPRTL___kmpc_dispatch_next_8u);65226523return getOrCreateRuntimeFunction(M, Name);6524}65256526FunctionCallee OpenMPIRBuilder::createDispatchFiniFunction(unsigned IVSize,6527bool IVSigned) {6528assert((IVSize == 32 || IVSize == 64) &&6529"IV size is not compatible with the omp runtime");6530RuntimeFunction Name = IVSize == 326531? (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_46532: omp::OMPRTL___kmpc_dispatch_fini_4u)6533: (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_86534: omp::OMPRTL___kmpc_dispatch_fini_8u);65356536return getOrCreateRuntimeFunction(M, Name);6537}65386539FunctionCallee OpenMPIRBuilder::createDispatchDeinitFunction() {6540return getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_dispatch_deinit);6541}65426543static Function *createOutlinedFunction(6544OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, StringRef FuncName,6545SmallVectorImpl<Value *> &Inputs,6546OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc,6547OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB) {6548SmallVector<Type *> ParameterTypes;6549if (OMPBuilder.Config.isTargetDevice()) {6550// Add the "implicit" runtime argument we use to provide launch specific6551// information for target devices.6552auto *Int8PtrTy = PointerType::getUnqual(Builder.getContext());6553ParameterTypes.push_back(Int8PtrTy);65546555// All parameters to target devices are passed as pointers6556// or i64. This assumes 64-bit address spaces/pointers.6557for (auto &Arg : Inputs)6558ParameterTypes.push_back(Arg->getType()->isPointerTy()6559? Arg->getType()6560: Type::getInt64Ty(Builder.getContext()));6561} else {6562for (auto &Arg : Inputs)6563ParameterTypes.push_back(Arg->getType());6564}65656566auto FuncType = FunctionType::get(Builder.getVoidTy(), ParameterTypes,6567/*isVarArg*/ false);6568auto Func = Function::Create(FuncType, GlobalValue::InternalLinkage, FuncName,6569Builder.GetInsertBlock()->getModule());65706571// Save insert point.6572auto OldInsertPoint = Builder.saveIP();65736574// Generate the region into the function.6575BasicBlock *EntryBB = BasicBlock::Create(Builder.getContext(), "entry", Func);6576Builder.SetInsertPoint(EntryBB);65776578// Insert target init call in the device compilation pass.6579if (OMPBuilder.Config.isTargetDevice())6580Builder.restoreIP(OMPBuilder.createTargetInit(Builder, /*IsSPMD*/ false));65816582BasicBlock *UserCodeEntryBB = Builder.GetInsertBlock();65836584// As we embed the user code in the middle of our target region after we6585// generate entry code, we must move what allocas we can into the entry6586// block to avoid possible breaking optimisations for device6587if (OMPBuilder.Config.isTargetDevice())6588OMPBuilder.ConstantAllocaRaiseCandidates.emplace_back(Func);65896590// Insert target deinit call in the device compilation pass.6591Builder.restoreIP(CBFunc(Builder.saveIP(), Builder.saveIP()));6592if (OMPBuilder.Config.isTargetDevice())6593OMPBuilder.createTargetDeinit(Builder);65946595// Insert return instruction.6596Builder.CreateRetVoid();65976598// New Alloca IP at entry point of created device function.6599Builder.SetInsertPoint(EntryBB->getFirstNonPHI());6600auto AllocaIP = Builder.saveIP();66016602Builder.SetInsertPoint(UserCodeEntryBB->getFirstNonPHIOrDbg());66036604// Skip the artificial dyn_ptr on the device.6605const auto &ArgRange =6606OMPBuilder.Config.isTargetDevice()6607? make_range(Func->arg_begin() + 1, Func->arg_end())6608: Func->args();66096610auto ReplaceValue = [](Value *Input, Value *InputCopy, Function *Func) {6611// Things like GEP's can come in the form of Constants. Constants and6612// ConstantExpr's do not have access to the knowledge of what they're6613// contained in, so we must dig a little to find an instruction so we6614// can tell if they're used inside of the function we're outlining. We6615// also replace the original constant expression with a new instruction6616// equivalent; an instruction as it allows easy modification in the6617// following loop, as we can now know the constant (instruction) is6618// owned by our target function and replaceUsesOfWith can now be invoked6619// on it (cannot do this with constants it seems). A brand new one also6620// allows us to be cautious as it is perhaps possible the old expression6621// was used inside of the function but exists and is used externally6622// (unlikely by the nature of a Constant, but still).6623// NOTE: We cannot remove dead constants that have been rewritten to6624// instructions at this stage, we run the risk of breaking later lowering6625// by doing so as we could still be in the process of lowering the module6626// from MLIR to LLVM-IR and the MLIR lowering may still require the original6627// constants we have created rewritten versions of.6628if (auto *Const = dyn_cast<Constant>(Input))6629convertUsersOfConstantsToInstructions(Const, Func, false);66306631// Collect all the instructions6632for (User *User : make_early_inc_range(Input->users()))6633if (auto *Instr = dyn_cast<Instruction>(User))6634if (Instr->getFunction() == Func)6635Instr->replaceUsesOfWith(Input, InputCopy);6636};66376638SmallVector<std::pair<Value *, Value *>> DeferredReplacement;66396640// Rewrite uses of input valus to parameters.6641for (auto InArg : zip(Inputs, ArgRange)) {6642Value *Input = std::get<0>(InArg);6643Argument &Arg = std::get<1>(InArg);6644Value *InputCopy = nullptr;66456646Builder.restoreIP(6647ArgAccessorFuncCB(Arg, Input, InputCopy, AllocaIP, Builder.saveIP()));66486649// In certain cases a Global may be set up for replacement, however, this6650// Global may be used in multiple arguments to the kernel, just segmented6651// apart, for example, if we have a global array, that is sectioned into6652// multiple mappings (technically not legal in OpenMP, but there is a case6653// in Fortran for Common Blocks where this is neccesary), we will end up6654// with GEP's into this array inside the kernel, that refer to the Global6655// but are technically seperate arguments to the kernel for all intents and6656// purposes. If we have mapped a segment that requires a GEP into the 0-th6657// index, it will fold into an referal to the Global, if we then encounter6658// this folded GEP during replacement all of the references to the6659// Global in the kernel will be replaced with the argument we have generated6660// that corresponds to it, including any other GEP's that refer to the6661// Global that may be other arguments. This will invalidate all of the other6662// preceding mapped arguments that refer to the same global that may be6663// seperate segments. To prevent this, we defer global processing until all6664// other processing has been performed.6665if (llvm::isa<llvm::GlobalValue>(std::get<0>(InArg)) ||6666llvm::isa<llvm::GlobalObject>(std::get<0>(InArg)) ||6667llvm::isa<llvm::GlobalVariable>(std::get<0>(InArg))) {6668DeferredReplacement.push_back(std::make_pair(Input, InputCopy));6669continue;6670}66716672ReplaceValue(Input, InputCopy, Func);6673}66746675// Replace all of our deferred Input values, currently just Globals.6676for (auto Deferred : DeferredReplacement)6677ReplaceValue(std::get<0>(Deferred), std::get<1>(Deferred), Func);66786679// Restore insert point.6680Builder.restoreIP(OldInsertPoint);66816682return Func;6683}66846685/// Create an entry point for a target task with the following.6686/// It'll have the following signature6687/// void @.omp_target_task_proxy_func(i32 %thread.id, ptr %task)6688/// This function is called from emitTargetTask once the6689/// code to launch the target kernel has been outlined already.6690static Function *emitTargetTaskProxyFunction(OpenMPIRBuilder &OMPBuilder,6691IRBuilderBase &Builder,6692CallInst *StaleCI) {6693Module &M = OMPBuilder.M;6694// KernelLaunchFunction is the target launch function, i.e.6695// the function that sets up kernel arguments and calls6696// __tgt_target_kernel to launch the kernel on the device.6697//6698Function *KernelLaunchFunction = StaleCI->getCalledFunction();66996700// StaleCI is the CallInst which is the call to the outlined6701// target kernel launch function. If there are values that the6702// outlined function uses then these are aggregated into a structure6703// which is passed as the second argument. If not, then there's6704// only one argument, the threadID. So, StaleCI can be6705//6706// %structArg = alloca { ptr, ptr }, align 86707// %gep_ = getelementptr { ptr, ptr }, ptr %structArg, i32 0, i32 06708// store ptr %20, ptr %gep_, align 86709// %gep_8 = getelementptr { ptr, ptr }, ptr %structArg, i32 0, i32 16710// store ptr %21, ptr %gep_8, align 86711// call void @_QQmain..omp_par.1(i32 %global.tid.val6, ptr %structArg)6712//6713// OR6714//6715// call void @_QQmain..omp_par.1(i32 %global.tid.val6)6716OpenMPIRBuilder::InsertPointTy IP(StaleCI->getParent(),6717StaleCI->getIterator());6718LLVMContext &Ctx = StaleCI->getParent()->getContext();6719Type *ThreadIDTy = Type::getInt32Ty(Ctx);6720Type *TaskPtrTy = OMPBuilder.TaskPtr;6721Type *TaskTy = OMPBuilder.Task;6722auto ProxyFnTy =6723FunctionType::get(Builder.getVoidTy(), {ThreadIDTy, TaskPtrTy},6724/* isVarArg */ false);6725auto ProxyFn = Function::Create(ProxyFnTy, GlobalValue::InternalLinkage,6726".omp_target_task_proxy_func",6727Builder.GetInsertBlock()->getModule());6728ProxyFn->getArg(0)->setName("thread.id");6729ProxyFn->getArg(1)->setName("task");67306731BasicBlock *EntryBB =6732BasicBlock::Create(Builder.getContext(), "entry", ProxyFn);6733Builder.SetInsertPoint(EntryBB);67346735bool HasShareds = StaleCI->arg_size() > 1;6736// TODO: This is a temporary assert to prove to ourselves that6737// the outlined target launch function is always going to have6738// atmost two arguments if there is any data shared between6739// host and device.6740assert((!HasShareds || (StaleCI->arg_size() == 2)) &&6741"StaleCI with shareds should have exactly two arguments.");6742if (HasShareds) {6743auto *ArgStructAlloca = dyn_cast<AllocaInst>(StaleCI->getArgOperand(1));6744assert(ArgStructAlloca &&6745"Unable to find the alloca instruction corresponding to arguments "6746"for extracted function");6747auto *ArgStructType =6748dyn_cast<StructType>(ArgStructAlloca->getAllocatedType());67496750AllocaInst *NewArgStructAlloca =6751Builder.CreateAlloca(ArgStructType, nullptr, "structArg");6752Value *TaskT = ProxyFn->getArg(1);6753Value *ThreadId = ProxyFn->getArg(0);6754Value *SharedsSize =6755Builder.getInt64(M.getDataLayout().getTypeStoreSize(ArgStructType));67566757Value *Shareds = Builder.CreateStructGEP(TaskTy, TaskT, 0);6758LoadInst *LoadShared =6759Builder.CreateLoad(PointerType::getUnqual(Ctx), Shareds);67606761Builder.CreateMemCpy(6762NewArgStructAlloca, NewArgStructAlloca->getAlign(), LoadShared,6763LoadShared->getPointerAlignment(M.getDataLayout()), SharedsSize);67646765Builder.CreateCall(KernelLaunchFunction, {ThreadId, NewArgStructAlloca});6766}6767Builder.CreateRetVoid();6768return ProxyFn;6769}6770static void emitTargetOutlinedFunction(6771OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder,6772TargetRegionEntryInfo &EntryInfo, Function *&OutlinedFn,6773Constant *&OutlinedFnID, SmallVectorImpl<Value *> &Inputs,6774OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc,6775OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB) {67766777OpenMPIRBuilder::FunctionGenCallback &&GenerateOutlinedFunction =6778[&OMPBuilder, &Builder, &Inputs, &CBFunc,6779&ArgAccessorFuncCB](StringRef EntryFnName) {6780return createOutlinedFunction(OMPBuilder, Builder, EntryFnName, Inputs,6781CBFunc, ArgAccessorFuncCB);6782};67836784OMPBuilder.emitTargetRegionFunction(EntryInfo, GenerateOutlinedFunction, true,6785OutlinedFn, OutlinedFnID);6786}6787OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitTargetTask(6788Function *OutlinedFn, Value *OutlinedFnID,6789EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args,6790Value *DeviceID, Value *RTLoc, OpenMPIRBuilder::InsertPointTy AllocaIP,6791SmallVector<llvm::OpenMPIRBuilder::DependData> &Dependencies,6792bool HasNoWait) {67936794// When we arrive at this function, the target region itself has been6795// outlined into the function OutlinedFn.6796// So at ths point, for6797// --------------------------------------------------6798// void user_code_that_offloads(...) {6799// omp target depend(..) map(from:a) map(to:b, c)6800// a = b + c6801// }6802//6803// --------------------------------------------------6804//6805// we have6806//6807// --------------------------------------------------6808//6809// void user_code_that_offloads(...) {6810// %.offload_baseptrs = alloca [3 x ptr], align 86811// %.offload_ptrs = alloca [3 x ptr], align 86812// %.offload_mappers = alloca [3 x ptr], align 86813// ;; target region has been outlined and now we need to6814// ;; offload to it via a target task.6815// }6816// void outlined_device_function(ptr a, ptr b, ptr c) {6817// *a = *b + *c6818// }6819//6820// We have to now do the following6821// (i) Make an offloading call to outlined_device_function using the OpenMP6822// RTL. See 'kernel_launch_function' in the pseudo code below. This is6823// emitted by emitKernelLaunch6824// (ii) Create a task entry point function that calls kernel_launch_function6825// and is the entry point for the target task. See6826// '@.omp_target_task_proxy_func in the pseudocode below.6827// (iii) Create a task with the task entry point created in (ii)6828//6829// That is we create the following6830//6831// void user_code_that_offloads(...) {6832// %.offload_baseptrs = alloca [3 x ptr], align 86833// %.offload_ptrs = alloca [3 x ptr], align 86834// %.offload_mappers = alloca [3 x ptr], align 86835//6836// %structArg = alloca { ptr, ptr, ptr }, align 86837// %strucArg[0] = %.offload_baseptrs6838// %strucArg[1] = %.offload_ptrs6839// %strucArg[2] = %.offload_mappers6840// proxy_target_task = @__kmpc_omp_task_alloc(...,6841// @.omp_target_task_proxy_func)6842// memcpy(proxy_target_task->shareds, %structArg, sizeof(structArg))6843// dependencies_array = ...6844// ;; if nowait not present6845// call @__kmpc_omp_wait_deps(..., dependencies_array)6846// call @__kmpc_omp_task_begin_if0(...)6847// call @ @.omp_target_task_proxy_func(i32 thread_id, ptr6848// %proxy_target_task) call @__kmpc_omp_task_complete_if0(...)6849// }6850//6851// define internal void @.omp_target_task_proxy_func(i32 %thread.id,6852// ptr %task) {6853// %structArg = alloca {ptr, ptr, ptr}6854// %shared_data = load (getelementptr %task, 0, 0)6855// mempcy(%structArg, %shared_data, sizeof(structArg))6856// kernel_launch_function(%thread.id, %structArg)6857// }6858//6859// We need the proxy function because the signature of the task entry point6860// expected by kmpc_omp_task is always the same and will be different from6861// that of the kernel_launch function.6862//6863// kernel_launch_function is generated by emitKernelLaunch and has the6864// always_inline attribute.6865// void kernel_launch_function(thread_id,6866// structArg) alwaysinline {6867// %kernel_args = alloca %struct.__tgt_kernel_arguments, align 86868// offload_baseptrs = load(getelementptr structArg, 0, 0)6869// offload_ptrs = load(getelementptr structArg, 0, 1)6870// offload_mappers = load(getelementptr structArg, 0, 2)6871// ; setup kernel_args using offload_baseptrs, offload_ptrs and6872// ; offload_mappers6873// call i32 @__tgt_target_kernel(...,6874// outlined_device_function,6875// ptr %kernel_args)6876// }6877// void outlined_device_function(ptr a, ptr b, ptr c) {6878// *a = *b + *c6879// }6880//6881BasicBlock *TargetTaskBodyBB =6882splitBB(Builder, /*CreateBranch=*/true, "target.task.body");6883BasicBlock *TargetTaskAllocaBB =6884splitBB(Builder, /*CreateBranch=*/true, "target.task.alloca");68856886InsertPointTy TargetTaskAllocaIP(TargetTaskAllocaBB,6887TargetTaskAllocaBB->begin());6888InsertPointTy TargetTaskBodyIP(TargetTaskBodyBB, TargetTaskBodyBB->begin());68896890OutlineInfo OI;6891OI.EntryBB = TargetTaskAllocaBB;6892OI.OuterAllocaBB = AllocaIP.getBlock();68936894// Add the thread ID argument.6895SmallVector<Instruction *, 4> ToBeDeleted;6896OI.ExcludeArgsFromAggregate.push_back(createFakeIntVal(6897Builder, AllocaIP, ToBeDeleted, TargetTaskAllocaIP, "global.tid", false));68986899Builder.restoreIP(TargetTaskBodyIP);69006901// emitKernelLaunch makes the necessary runtime call to offload the kernel.6902// We then outline all that code into a separate function6903// ('kernel_launch_function' in the pseudo code above). This function is then6904// called by the target task proxy function (see6905// '@.omp_target_task_proxy_func' in the pseudo code above)6906// "@.omp_target_task_proxy_func' is generated by emitTargetTaskProxyFunction6907Builder.restoreIP(emitKernelLaunch(Builder, OutlinedFn, OutlinedFnID,6908EmitTargetCallFallbackCB, Args, DeviceID,6909RTLoc, TargetTaskAllocaIP));69106911OI.ExitBB = Builder.saveIP().getBlock();6912OI.PostOutlineCB = [this, ToBeDeleted, Dependencies,6913HasNoWait](Function &OutlinedFn) mutable {6914assert(OutlinedFn.getNumUses() == 1 &&6915"there must be a single user for the outlined function");69166917CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());6918bool HasShareds = StaleCI->arg_size() > 1;69196920Function *ProxyFn = emitTargetTaskProxyFunction(*this, Builder, StaleCI);69216922LLVM_DEBUG(dbgs() << "Proxy task entry function created: " << *ProxyFn6923<< "\n");69246925Builder.SetInsertPoint(StaleCI);69266927// Gather the arguments for emitting the runtime call.6928uint32_t SrcLocStrSize;6929Constant *SrcLocStr =6930getOrCreateSrcLocStr(LocationDescription(Builder), SrcLocStrSize);6931Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);69326933// @__kmpc_omp_task_alloc6934Function *TaskAllocFn =6935getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);69366937// Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)6938// call.6939Value *ThreadID = getOrCreateThreadID(Ident);69406941// Argument - `sizeof_kmp_task_t` (TaskSize)6942// Tasksize refers to the size in bytes of kmp_task_t data structure6943// including private vars accessed in task.6944// TODO: add kmp_task_t_with_privates (privates)6945Value *TaskSize =6946Builder.getInt64(M.getDataLayout().getTypeStoreSize(Task));69476948// Argument - `sizeof_shareds` (SharedsSize)6949// SharedsSize refers to the shareds array size in the kmp_task_t data6950// structure.6951Value *SharedsSize = Builder.getInt64(0);6952if (HasShareds) {6953auto *ArgStructAlloca = dyn_cast<AllocaInst>(StaleCI->getArgOperand(1));6954assert(ArgStructAlloca &&6955"Unable to find the alloca instruction corresponding to arguments "6956"for extracted function");6957auto *ArgStructType =6958dyn_cast<StructType>(ArgStructAlloca->getAllocatedType());6959assert(ArgStructType && "Unable to find struct type corresponding to "6960"arguments for extracted function");6961SharedsSize =6962Builder.getInt64(M.getDataLayout().getTypeStoreSize(ArgStructType));6963}69646965// Argument - `flags`6966// Task is tied iff (Flags & 1) == 1.6967// Task is untied iff (Flags & 1) == 0.6968// Task is final iff (Flags & 2) == 2.6969// Task is not final iff (Flags & 2) == 0.6970// A target task is not final and is untied.6971Value *Flags = Builder.getInt32(0);69726973// Emit the @__kmpc_omp_task_alloc runtime call6974// The runtime call returns a pointer to an area where the task captured6975// variables must be copied before the task is run (TaskData)6976CallInst *TaskData = Builder.CreateCall(6977TaskAllocFn, {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,6978/*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,6979/*task_func=*/ProxyFn});69806981if (HasShareds) {6982Value *Shareds = StaleCI->getArgOperand(1);6983Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());6984Value *TaskShareds = Builder.CreateLoad(VoidPtr, TaskData);6985Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,6986SharedsSize);6987}69886989Value *DepArray = emitTaskDependencies(*this, Dependencies);69906991// ---------------------------------------------------------------6992// V5.2 13.8 target construct6993// If the nowait clause is present, execution of the target task6994// may be deferred. If the nowait clause is not present, the target task is6995// an included task.6996// ---------------------------------------------------------------6997// The above means that the lack of a nowait on the target construct6998// translates to '#pragma omp task if(0)'6999if (!HasNoWait) {7000if (DepArray) {7001Function *TaskWaitFn =7002getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_wait_deps);7003Builder.CreateCall(7004TaskWaitFn,7005{/*loc_ref=*/Ident, /*gtid=*/ThreadID,7006/*ndeps=*/Builder.getInt32(Dependencies.size()),7007/*dep_list=*/DepArray,7008/*ndeps_noalias=*/ConstantInt::get(Builder.getInt32Ty(), 0),7009/*noalias_dep_list=*/7010ConstantPointerNull::get(PointerType::getUnqual(M.getContext()))});7011}7012// Included task.7013Function *TaskBeginFn =7014getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_begin_if0);7015Function *TaskCompleteFn =7016getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_complete_if0);7017Builder.CreateCall(TaskBeginFn, {Ident, ThreadID, TaskData});7018CallInst *CI = nullptr;7019if (HasShareds)7020CI = Builder.CreateCall(ProxyFn, {ThreadID, TaskData});7021else7022CI = Builder.CreateCall(ProxyFn, {ThreadID});7023CI->setDebugLoc(StaleCI->getDebugLoc());7024Builder.CreateCall(TaskCompleteFn, {Ident, ThreadID, TaskData});7025} else if (DepArray) {7026// HasNoWait - meaning the task may be deferred. Call7027// __kmpc_omp_task_with_deps if there are dependencies,7028// else call __kmpc_omp_task7029Function *TaskFn =7030getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps);7031Builder.CreateCall(7032TaskFn,7033{Ident, ThreadID, TaskData, Builder.getInt32(Dependencies.size()),7034DepArray, ConstantInt::get(Builder.getInt32Ty(), 0),7035ConstantPointerNull::get(PointerType::getUnqual(M.getContext()))});7036} else {7037// Emit the @__kmpc_omp_task runtime call to spawn the task7038Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);7039Builder.CreateCall(TaskFn, {Ident, ThreadID, TaskData});7040}70417042StaleCI->eraseFromParent();7043llvm::for_each(llvm::reverse(ToBeDeleted),7044[](Instruction *I) { I->eraseFromParent(); });7045};7046addOutlineInfo(std::move(OI));70477048LLVM_DEBUG(dbgs() << "Insert block after emitKernelLaunch = \n"7049<< *(Builder.GetInsertBlock()) << "\n");7050LLVM_DEBUG(dbgs() << "Module after emitKernelLaunch = \n"7051<< *(Builder.GetInsertBlock()->getParent()->getParent())7052<< "\n");7053return Builder.saveIP();7054}7055static void emitTargetCall(7056OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder,7057OpenMPIRBuilder::InsertPointTy AllocaIP, Function *OutlinedFn,7058Constant *OutlinedFnID, int32_t NumTeams, int32_t NumThreads,7059SmallVectorImpl<Value *> &Args,7060OpenMPIRBuilder::GenMapInfoCallbackTy GenMapInfoCB,7061SmallVector<llvm::OpenMPIRBuilder::DependData> Dependencies = {}) {70627063OpenMPIRBuilder::TargetDataInfo Info(7064/*RequiresDevicePointerInfo=*/false,7065/*SeparateBeginEndCalls=*/true);70667067OpenMPIRBuilder::MapInfosTy &MapInfo = GenMapInfoCB(Builder.saveIP());7068OMPBuilder.emitOffloadingArrays(AllocaIP, Builder.saveIP(), MapInfo, Info,7069/*IsNonContiguous=*/true);70707071OpenMPIRBuilder::TargetDataRTArgs RTArgs;7072OMPBuilder.emitOffloadingArraysArgument(Builder, RTArgs, Info,7073!MapInfo.Names.empty());70747075// emitKernelLaunch7076auto &&EmitTargetCallFallbackCB =7077[&](OpenMPIRBuilder::InsertPointTy IP) -> OpenMPIRBuilder::InsertPointTy {7078Builder.restoreIP(IP);7079Builder.CreateCall(OutlinedFn, Args);7080return Builder.saveIP();7081};70827083unsigned NumTargetItems = MapInfo.BasePointers.size();7084// TODO: Use correct device ID7085Value *DeviceID = Builder.getInt64(OMP_DEVICEID_UNDEF);7086Value *NumTeamsVal = Builder.getInt32(NumTeams);7087Value *NumThreadsVal = Builder.getInt32(NumThreads);7088uint32_t SrcLocStrSize;7089Constant *SrcLocStr = OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize);7090Value *RTLoc = OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize,7091llvm::omp::IdentFlag(0), 0);7092// TODO: Use correct NumIterations7093Value *NumIterations = Builder.getInt64(0);7094// TODO: Use correct DynCGGroupMem7095Value *DynCGGroupMem = Builder.getInt32(0);70967097bool HasNoWait = false;7098bool HasDependencies = Dependencies.size() > 0;7099bool RequiresOuterTargetTask = HasNoWait || HasDependencies;71007101OpenMPIRBuilder::TargetKernelArgs KArgs(NumTargetItems, RTArgs, NumIterations,7102NumTeamsVal, NumThreadsVal,7103DynCGGroupMem, HasNoWait);71047105// The presence of certain clauses on the target directive require the7106// explicit generation of the target task.7107if (RequiresOuterTargetTask) {7108Builder.restoreIP(OMPBuilder.emitTargetTask(7109OutlinedFn, OutlinedFnID, EmitTargetCallFallbackCB, KArgs, DeviceID,7110RTLoc, AllocaIP, Dependencies, HasNoWait));7111} else {7112Builder.restoreIP(OMPBuilder.emitKernelLaunch(7113Builder, OutlinedFn, OutlinedFnID, EmitTargetCallFallbackCB, KArgs,7114DeviceID, RTLoc, AllocaIP));7115}7116}7117OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createTarget(7118const LocationDescription &Loc, InsertPointTy AllocaIP,7119InsertPointTy CodeGenIP, TargetRegionEntryInfo &EntryInfo, int32_t NumTeams,7120int32_t NumThreads, SmallVectorImpl<Value *> &Args,7121GenMapInfoCallbackTy GenMapInfoCB,7122OpenMPIRBuilder::TargetBodyGenCallbackTy CBFunc,7123OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy ArgAccessorFuncCB,7124SmallVector<DependData> Dependencies) {71257126if (!updateToLocation(Loc))7127return InsertPointTy();71287129Builder.restoreIP(CodeGenIP);71307131Function *OutlinedFn;7132Constant *OutlinedFnID;7133// The target region is outlined into its own function. The LLVM IR for7134// the target region itself is generated using the callbacks CBFunc7135// and ArgAccessorFuncCB7136emitTargetOutlinedFunction(*this, Builder, EntryInfo, OutlinedFn,7137OutlinedFnID, Args, CBFunc, ArgAccessorFuncCB);71387139// If we are not on the target device, then we need to generate code7140// to make a remote call (offload) to the previously outlined function7141// that represents the target region. Do that now.7142if (!Config.isTargetDevice())7143emitTargetCall(*this, Builder, AllocaIP, OutlinedFn, OutlinedFnID, NumTeams,7144NumThreads, Args, GenMapInfoCB, Dependencies);7145return Builder.saveIP();7146}71477148std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,7149StringRef FirstSeparator,7150StringRef Separator) {7151SmallString<128> Buffer;7152llvm::raw_svector_ostream OS(Buffer);7153StringRef Sep = FirstSeparator;7154for (StringRef Part : Parts) {7155OS << Sep << Part;7156Sep = Separator;7157}7158return OS.str().str();7159}71607161std::string7162OpenMPIRBuilder::createPlatformSpecificName(ArrayRef<StringRef> Parts) const {7163return OpenMPIRBuilder::getNameWithSeparators(Parts, Config.firstSeparator(),7164Config.separator());7165}71667167GlobalVariable *7168OpenMPIRBuilder::getOrCreateInternalVariable(Type *Ty, const StringRef &Name,7169unsigned AddressSpace) {7170auto &Elem = *InternalVars.try_emplace(Name, nullptr).first;7171if (Elem.second) {7172assert(Elem.second->getValueType() == Ty &&7173"OMP internal variable has different type than requested");7174} else {7175// TODO: investigate the appropriate linkage type used for the global7176// variable for possibly changing that to internal or private, or maybe7177// create different versions of the function for different OMP internal7178// variables.7179auto Linkage = this->M.getTargetTriple().rfind("wasm32") == 07180? GlobalValue::ExternalLinkage7181: GlobalValue::CommonLinkage;7182auto *GV = new GlobalVariable(M, Ty, /*IsConstant=*/false, Linkage,7183Constant::getNullValue(Ty), Elem.first(),7184/*InsertBefore=*/nullptr,7185GlobalValue::NotThreadLocal, AddressSpace);7186const DataLayout &DL = M.getDataLayout();7187const llvm::Align TypeAlign = DL.getABITypeAlign(Ty);7188const llvm::Align PtrAlign = DL.getPointerABIAlignment(AddressSpace);7189GV->setAlignment(std::max(TypeAlign, PtrAlign));7190Elem.second = GV;7191}71927193return Elem.second;7194}71957196Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {7197std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();7198std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");7199return getOrCreateInternalVariable(KmpCriticalNameTy, Name);7200}72017202Value *OpenMPIRBuilder::getSizeInBytes(Value *BasePtr) {7203LLVMContext &Ctx = Builder.getContext();7204Value *Null =7205Constant::getNullValue(PointerType::getUnqual(BasePtr->getContext()));7206Value *SizeGep =7207Builder.CreateGEP(BasePtr->getType(), Null, Builder.getInt32(1));7208Value *SizePtrToInt = Builder.CreatePtrToInt(SizeGep, Type::getInt64Ty(Ctx));7209return SizePtrToInt;7210}72117212GlobalVariable *7213OpenMPIRBuilder::createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,7214std::string VarName) {7215llvm::Constant *MaptypesArrayInit =7216llvm::ConstantDataArray::get(M.getContext(), Mappings);7217auto *MaptypesArrayGlobal = new llvm::GlobalVariable(7218M, MaptypesArrayInit->getType(),7219/*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MaptypesArrayInit,7220VarName);7221MaptypesArrayGlobal->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);7222return MaptypesArrayGlobal;7223}72247225void OpenMPIRBuilder::createMapperAllocas(const LocationDescription &Loc,7226InsertPointTy AllocaIP,7227unsigned NumOperands,7228struct MapperAllocas &MapperAllocas) {7229if (!updateToLocation(Loc))7230return;72317232auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);7233auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);7234Builder.restoreIP(AllocaIP);7235AllocaInst *ArgsBase = Builder.CreateAlloca(7236ArrI8PtrTy, /* ArraySize = */ nullptr, ".offload_baseptrs");7237AllocaInst *Args = Builder.CreateAlloca(ArrI8PtrTy, /* ArraySize = */ nullptr,7238".offload_ptrs");7239AllocaInst *ArgSizes = Builder.CreateAlloca(7240ArrI64Ty, /* ArraySize = */ nullptr, ".offload_sizes");7241Builder.restoreIP(Loc.IP);7242MapperAllocas.ArgsBase = ArgsBase;7243MapperAllocas.Args = Args;7244MapperAllocas.ArgSizes = ArgSizes;7245}72467247void OpenMPIRBuilder::emitMapperCall(const LocationDescription &Loc,7248Function *MapperFunc, Value *SrcLocInfo,7249Value *MaptypesArg, Value *MapnamesArg,7250struct MapperAllocas &MapperAllocas,7251int64_t DeviceID, unsigned NumOperands) {7252if (!updateToLocation(Loc))7253return;72547255auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);7256auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);7257Value *ArgsBaseGEP =7258Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.ArgsBase,7259{Builder.getInt32(0), Builder.getInt32(0)});7260Value *ArgsGEP =7261Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.Args,7262{Builder.getInt32(0), Builder.getInt32(0)});7263Value *ArgSizesGEP =7264Builder.CreateInBoundsGEP(ArrI64Ty, MapperAllocas.ArgSizes,7265{Builder.getInt32(0), Builder.getInt32(0)});7266Value *NullPtr =7267Constant::getNullValue(PointerType::getUnqual(Int8Ptr->getContext()));7268Builder.CreateCall(MapperFunc,7269{SrcLocInfo, Builder.getInt64(DeviceID),7270Builder.getInt32(NumOperands), ArgsBaseGEP, ArgsGEP,7271ArgSizesGEP, MaptypesArg, MapnamesArg, NullPtr});7272}72737274void OpenMPIRBuilder::emitOffloadingArraysArgument(IRBuilderBase &Builder,7275TargetDataRTArgs &RTArgs,7276TargetDataInfo &Info,7277bool EmitDebug,7278bool ForEndCall) {7279assert((!ForEndCall || Info.separateBeginEndCalls()) &&7280"expected region end call to runtime only when end call is separate");7281auto UnqualPtrTy = PointerType::getUnqual(M.getContext());7282auto VoidPtrTy = UnqualPtrTy;7283auto VoidPtrPtrTy = UnqualPtrTy;7284auto Int64Ty = Type::getInt64Ty(M.getContext());7285auto Int64PtrTy = UnqualPtrTy;72867287if (!Info.NumberOfPtrs) {7288RTArgs.BasePointersArray = ConstantPointerNull::get(VoidPtrPtrTy);7289RTArgs.PointersArray = ConstantPointerNull::get(VoidPtrPtrTy);7290RTArgs.SizesArray = ConstantPointerNull::get(Int64PtrTy);7291RTArgs.MapTypesArray = ConstantPointerNull::get(Int64PtrTy);7292RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);7293RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);7294return;7295}72967297RTArgs.BasePointersArray = Builder.CreateConstInBoundsGEP2_32(7298ArrayType::get(VoidPtrTy, Info.NumberOfPtrs),7299Info.RTArgs.BasePointersArray,7300/*Idx0=*/0, /*Idx1=*/0);7301RTArgs.PointersArray = Builder.CreateConstInBoundsGEP2_32(7302ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray,7303/*Idx0=*/0,7304/*Idx1=*/0);7305RTArgs.SizesArray = Builder.CreateConstInBoundsGEP2_32(7306ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,7307/*Idx0=*/0, /*Idx1=*/0);7308RTArgs.MapTypesArray = Builder.CreateConstInBoundsGEP2_32(7309ArrayType::get(Int64Ty, Info.NumberOfPtrs),7310ForEndCall && Info.RTArgs.MapTypesArrayEnd ? Info.RTArgs.MapTypesArrayEnd7311: Info.RTArgs.MapTypesArray,7312/*Idx0=*/0,7313/*Idx1=*/0);73147315// Only emit the mapper information arrays if debug information is7316// requested.7317if (!EmitDebug)7318RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);7319else7320RTArgs.MapNamesArray = Builder.CreateConstInBoundsGEP2_32(7321ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.MapNamesArray,7322/*Idx0=*/0,7323/*Idx1=*/0);7324// If there is no user-defined mapper, set the mapper array to nullptr to7325// avoid an unnecessary data privatization7326if (!Info.HasMapper)7327RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);7328else7329RTArgs.MappersArray =7330Builder.CreatePointerCast(Info.RTArgs.MappersArray, VoidPtrPtrTy);7331}73327333void OpenMPIRBuilder::emitNonContiguousDescriptor(InsertPointTy AllocaIP,7334InsertPointTy CodeGenIP,7335MapInfosTy &CombinedInfo,7336TargetDataInfo &Info) {7337MapInfosTy::StructNonContiguousInfo &NonContigInfo =7338CombinedInfo.NonContigInfo;73397340// Build an array of struct descriptor_dim and then assign it to7341// offload_args.7342//7343// struct descriptor_dim {7344// uint64_t offset;7345// uint64_t count;7346// uint64_t stride7347// };7348Type *Int64Ty = Builder.getInt64Ty();7349StructType *DimTy = StructType::create(7350M.getContext(), ArrayRef<Type *>({Int64Ty, Int64Ty, Int64Ty}),7351"struct.descriptor_dim");73527353enum { OffsetFD = 0, CountFD, StrideFD };7354// We need two index variable here since the size of "Dims" is the same as7355// the size of Components, however, the size of offset, count, and stride is7356// equal to the size of base declaration that is non-contiguous.7357for (unsigned I = 0, L = 0, E = NonContigInfo.Dims.size(); I < E; ++I) {7358// Skip emitting ir if dimension size is 1 since it cannot be7359// non-contiguous.7360if (NonContigInfo.Dims[I] == 1)7361continue;7362Builder.restoreIP(AllocaIP);7363ArrayType *ArrayTy = ArrayType::get(DimTy, NonContigInfo.Dims[I]);7364AllocaInst *DimsAddr =7365Builder.CreateAlloca(ArrayTy, /* ArraySize = */ nullptr, "dims");7366Builder.restoreIP(CodeGenIP);7367for (unsigned II = 0, EE = NonContigInfo.Dims[I]; II < EE; ++II) {7368unsigned RevIdx = EE - II - 1;7369Value *DimsLVal = Builder.CreateInBoundsGEP(7370DimsAddr->getAllocatedType(), DimsAddr,7371{Builder.getInt64(0), Builder.getInt64(II)});7372// Offset7373Value *OffsetLVal = Builder.CreateStructGEP(DimTy, DimsLVal, OffsetFD);7374Builder.CreateAlignedStore(7375NonContigInfo.Offsets[L][RevIdx], OffsetLVal,7376M.getDataLayout().getPrefTypeAlign(OffsetLVal->getType()));7377// Count7378Value *CountLVal = Builder.CreateStructGEP(DimTy, DimsLVal, CountFD);7379Builder.CreateAlignedStore(7380NonContigInfo.Counts[L][RevIdx], CountLVal,7381M.getDataLayout().getPrefTypeAlign(CountLVal->getType()));7382// Stride7383Value *StrideLVal = Builder.CreateStructGEP(DimTy, DimsLVal, StrideFD);7384Builder.CreateAlignedStore(7385NonContigInfo.Strides[L][RevIdx], StrideLVal,7386M.getDataLayout().getPrefTypeAlign(CountLVal->getType()));7387}7388// args[I] = &dims7389Builder.restoreIP(CodeGenIP);7390Value *DAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(7391DimsAddr, Builder.getPtrTy());7392Value *P = Builder.CreateConstInBoundsGEP2_32(7393ArrayType::get(Builder.getPtrTy(), Info.NumberOfPtrs),7394Info.RTArgs.PointersArray, 0, I);7395Builder.CreateAlignedStore(7396DAddr, P, M.getDataLayout().getPrefTypeAlign(Builder.getPtrTy()));7397++L;7398}7399}74007401void OpenMPIRBuilder::emitOffloadingArrays(7402InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo,7403TargetDataInfo &Info, bool IsNonContiguous,7404function_ref<void(unsigned int, Value *)> DeviceAddrCB,7405function_ref<Value *(unsigned int)> CustomMapperCB) {74067407// Reset the array information.7408Info.clearArrayInfo();7409Info.NumberOfPtrs = CombinedInfo.BasePointers.size();74107411if (Info.NumberOfPtrs == 0)7412return;74137414Builder.restoreIP(AllocaIP);7415// Detect if we have any capture size requiring runtime evaluation of the7416// size so that a constant array could be eventually used.7417ArrayType *PointerArrayType =7418ArrayType::get(Builder.getPtrTy(), Info.NumberOfPtrs);74197420Info.RTArgs.BasePointersArray = Builder.CreateAlloca(7421PointerArrayType, /* ArraySize = */ nullptr, ".offload_baseptrs");74227423Info.RTArgs.PointersArray = Builder.CreateAlloca(7424PointerArrayType, /* ArraySize = */ nullptr, ".offload_ptrs");7425AllocaInst *MappersArray = Builder.CreateAlloca(7426PointerArrayType, /* ArraySize = */ nullptr, ".offload_mappers");7427Info.RTArgs.MappersArray = MappersArray;74287429// If we don't have any VLA types or other types that require runtime7430// evaluation, we can use a constant array for the map sizes, otherwise we7431// need to fill up the arrays as we do for the pointers.7432Type *Int64Ty = Builder.getInt64Ty();7433SmallVector<Constant *> ConstSizes(CombinedInfo.Sizes.size(),7434ConstantInt::get(Int64Ty, 0));7435SmallBitVector RuntimeSizes(CombinedInfo.Sizes.size());7436for (unsigned I = 0, E = CombinedInfo.Sizes.size(); I < E; ++I) {7437if (auto *CI = dyn_cast<Constant>(CombinedInfo.Sizes[I])) {7438if (!isa<ConstantExpr>(CI) && !isa<GlobalValue>(CI)) {7439if (IsNonContiguous &&7440static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(7441CombinedInfo.Types[I] &7442OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG))7443ConstSizes[I] =7444ConstantInt::get(Int64Ty, CombinedInfo.NonContigInfo.Dims[I]);7445else7446ConstSizes[I] = CI;7447continue;7448}7449}7450RuntimeSizes.set(I);7451}74527453if (RuntimeSizes.all()) {7454ArrayType *SizeArrayType = ArrayType::get(Int64Ty, Info.NumberOfPtrs);7455Info.RTArgs.SizesArray = Builder.CreateAlloca(7456SizeArrayType, /* ArraySize = */ nullptr, ".offload_sizes");7457Builder.restoreIP(CodeGenIP);7458} else {7459auto *SizesArrayInit = ConstantArray::get(7460ArrayType::get(Int64Ty, ConstSizes.size()), ConstSizes);7461std::string Name = createPlatformSpecificName({"offload_sizes"});7462auto *SizesArrayGbl =7463new GlobalVariable(M, SizesArrayInit->getType(), /*isConstant=*/true,7464GlobalValue::PrivateLinkage, SizesArrayInit, Name);7465SizesArrayGbl->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);74667467if (!RuntimeSizes.any()) {7468Info.RTArgs.SizesArray = SizesArrayGbl;7469} else {7470unsigned IndexSize = M.getDataLayout().getIndexSizeInBits(0);7471Align OffloadSizeAlign = M.getDataLayout().getABIIntegerTypeAlignment(64);7472ArrayType *SizeArrayType = ArrayType::get(Int64Ty, Info.NumberOfPtrs);7473AllocaInst *Buffer = Builder.CreateAlloca(7474SizeArrayType, /* ArraySize = */ nullptr, ".offload_sizes");7475Buffer->setAlignment(OffloadSizeAlign);7476Builder.restoreIP(CodeGenIP);7477Builder.CreateMemCpy(7478Buffer, M.getDataLayout().getPrefTypeAlign(Buffer->getType()),7479SizesArrayGbl, OffloadSizeAlign,7480Builder.getIntN(7481IndexSize,7482Buffer->getAllocationSize(M.getDataLayout())->getFixedValue()));74837484Info.RTArgs.SizesArray = Buffer;7485}7486Builder.restoreIP(CodeGenIP);7487}74887489// The map types are always constant so we don't need to generate code to7490// fill arrays. Instead, we create an array constant.7491SmallVector<uint64_t, 4> Mapping;7492for (auto mapFlag : CombinedInfo.Types)7493Mapping.push_back(7494static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(7495mapFlag));7496std::string MaptypesName = createPlatformSpecificName({"offload_maptypes"});7497auto *MapTypesArrayGbl = createOffloadMaptypes(Mapping, MaptypesName);7498Info.RTArgs.MapTypesArray = MapTypesArrayGbl;74997500// The information types are only built if provided.7501if (!CombinedInfo.Names.empty()) {7502std::string MapnamesName = createPlatformSpecificName({"offload_mapnames"});7503auto *MapNamesArrayGbl =7504createOffloadMapnames(CombinedInfo.Names, MapnamesName);7505Info.RTArgs.MapNamesArray = MapNamesArrayGbl;7506} else {7507Info.RTArgs.MapNamesArray =7508Constant::getNullValue(PointerType::getUnqual(Builder.getContext()));7509}75107511// If there's a present map type modifier, it must not be applied to the end7512// of a region, so generate a separate map type array in that case.7513if (Info.separateBeginEndCalls()) {7514bool EndMapTypesDiffer = false;7515for (uint64_t &Type : Mapping) {7516if (Type & static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(7517OpenMPOffloadMappingFlags::OMP_MAP_PRESENT)) {7518Type &= ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(7519OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);7520EndMapTypesDiffer = true;7521}7522}7523if (EndMapTypesDiffer) {7524MapTypesArrayGbl = createOffloadMaptypes(Mapping, MaptypesName);7525Info.RTArgs.MapTypesArrayEnd = MapTypesArrayGbl;7526}7527}75287529PointerType *PtrTy = Builder.getPtrTy();7530for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {7531Value *BPVal = CombinedInfo.BasePointers[I];7532Value *BP = Builder.CreateConstInBoundsGEP2_32(7533ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.BasePointersArray,75340, I);7535Builder.CreateAlignedStore(BPVal, BP,7536M.getDataLayout().getPrefTypeAlign(PtrTy));75377538if (Info.requiresDevicePointerInfo()) {7539if (CombinedInfo.DevicePointers[I] == DeviceInfoTy::Pointer) {7540CodeGenIP = Builder.saveIP();7541Builder.restoreIP(AllocaIP);7542Info.DevicePtrInfoMap[BPVal] = {BP, Builder.CreateAlloca(PtrTy)};7543Builder.restoreIP(CodeGenIP);7544if (DeviceAddrCB)7545DeviceAddrCB(I, Info.DevicePtrInfoMap[BPVal].second);7546} else if (CombinedInfo.DevicePointers[I] == DeviceInfoTy::Address) {7547Info.DevicePtrInfoMap[BPVal] = {BP, BP};7548if (DeviceAddrCB)7549DeviceAddrCB(I, BP);7550}7551}75527553Value *PVal = CombinedInfo.Pointers[I];7554Value *P = Builder.CreateConstInBoundsGEP2_32(7555ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray, 0,7556I);7557// TODO: Check alignment correct.7558Builder.CreateAlignedStore(PVal, P,7559M.getDataLayout().getPrefTypeAlign(PtrTy));75607561if (RuntimeSizes.test(I)) {7562Value *S = Builder.CreateConstInBoundsGEP2_32(7563ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,7564/*Idx0=*/0,7565/*Idx1=*/I);7566Builder.CreateAlignedStore(Builder.CreateIntCast(CombinedInfo.Sizes[I],7567Int64Ty,7568/*isSigned=*/true),7569S, M.getDataLayout().getPrefTypeAlign(PtrTy));7570}7571// Fill up the mapper array.7572unsigned IndexSize = M.getDataLayout().getIndexSizeInBits(0);7573Value *MFunc = ConstantPointerNull::get(PtrTy);7574if (CustomMapperCB)7575if (Value *CustomMFunc = CustomMapperCB(I))7576MFunc = Builder.CreatePointerCast(CustomMFunc, PtrTy);7577Value *MAddr = Builder.CreateInBoundsGEP(7578MappersArray->getAllocatedType(), MappersArray,7579{Builder.getIntN(IndexSize, 0), Builder.getIntN(IndexSize, I)});7580Builder.CreateAlignedStore(7581MFunc, MAddr, M.getDataLayout().getPrefTypeAlign(MAddr->getType()));7582}75837584if (!IsNonContiguous || CombinedInfo.NonContigInfo.Offsets.empty() ||7585Info.NumberOfPtrs == 0)7586return;7587emitNonContiguousDescriptor(AllocaIP, CodeGenIP, CombinedInfo, Info);7588}75897590void OpenMPIRBuilder::emitBranch(BasicBlock *Target) {7591BasicBlock *CurBB = Builder.GetInsertBlock();75927593if (!CurBB || CurBB->getTerminator()) {7594// If there is no insert point or the previous block is already7595// terminated, don't touch it.7596} else {7597// Otherwise, create a fall-through branch.7598Builder.CreateBr(Target);7599}76007601Builder.ClearInsertionPoint();7602}76037604void OpenMPIRBuilder::emitBlock(BasicBlock *BB, Function *CurFn,7605bool IsFinished) {7606BasicBlock *CurBB = Builder.GetInsertBlock();76077608// Fall out of the current block (if necessary).7609emitBranch(BB);76107611if (IsFinished && BB->use_empty()) {7612BB->eraseFromParent();7613return;7614}76157616// Place the block after the current block, if possible, or else at7617// the end of the function.7618if (CurBB && CurBB->getParent())7619CurFn->insert(std::next(CurBB->getIterator()), BB);7620else7621CurFn->insert(CurFn->end(), BB);7622Builder.SetInsertPoint(BB);7623}76247625void OpenMPIRBuilder::emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen,7626BodyGenCallbackTy ElseGen,7627InsertPointTy AllocaIP) {7628// If the condition constant folds and can be elided, try to avoid emitting7629// the condition and the dead arm of the if/else.7630if (auto *CI = dyn_cast<ConstantInt>(Cond)) {7631auto CondConstant = CI->getSExtValue();7632if (CondConstant)7633ThenGen(AllocaIP, Builder.saveIP());7634else7635ElseGen(AllocaIP, Builder.saveIP());7636return;7637}76387639Function *CurFn = Builder.GetInsertBlock()->getParent();76407641// Otherwise, the condition did not fold, or we couldn't elide it. Just7642// emit the conditional branch.7643BasicBlock *ThenBlock = BasicBlock::Create(M.getContext(), "omp_if.then");7644BasicBlock *ElseBlock = BasicBlock::Create(M.getContext(), "omp_if.else");7645BasicBlock *ContBlock = BasicBlock::Create(M.getContext(), "omp_if.end");7646Builder.CreateCondBr(Cond, ThenBlock, ElseBlock);7647// Emit the 'then' code.7648emitBlock(ThenBlock, CurFn);7649ThenGen(AllocaIP, Builder.saveIP());7650emitBranch(ContBlock);7651// Emit the 'else' code if present.7652// There is no need to emit line number for unconditional branch.7653emitBlock(ElseBlock, CurFn);7654ElseGen(AllocaIP, Builder.saveIP());7655// There is no need to emit line number for unconditional branch.7656emitBranch(ContBlock);7657// Emit the continuation block for code after the if.7658emitBlock(ContBlock, CurFn, /*IsFinished=*/true);7659}76607661bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(7662const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {7663assert(!(AO == AtomicOrdering::NotAtomic ||7664AO == llvm::AtomicOrdering::Unordered) &&7665"Unexpected Atomic Ordering.");76667667bool Flush = false;7668llvm::AtomicOrdering FlushAO = AtomicOrdering::Monotonic;76697670switch (AK) {7671case Read:7672if (AO == AtomicOrdering::Acquire || AO == AtomicOrdering::AcquireRelease ||7673AO == AtomicOrdering::SequentiallyConsistent) {7674FlushAO = AtomicOrdering::Acquire;7675Flush = true;7676}7677break;7678case Write:7679case Compare:7680case Update:7681if (AO == AtomicOrdering::Release || AO == AtomicOrdering::AcquireRelease ||7682AO == AtomicOrdering::SequentiallyConsistent) {7683FlushAO = AtomicOrdering::Release;7684Flush = true;7685}7686break;7687case Capture:7688switch (AO) {7689case AtomicOrdering::Acquire:7690FlushAO = AtomicOrdering::Acquire;7691Flush = true;7692break;7693case AtomicOrdering::Release:7694FlushAO = AtomicOrdering::Release;7695Flush = true;7696break;7697case AtomicOrdering::AcquireRelease:7698case AtomicOrdering::SequentiallyConsistent:7699FlushAO = AtomicOrdering::AcquireRelease;7700Flush = true;7701break;7702default:7703// do nothing - leave silently.7704break;7705}7706}77077708if (Flush) {7709// Currently Flush RT call still doesn't take memory_ordering, so for when7710// that happens, this tries to do the resolution of which atomic ordering7711// to use with but issue the flush call7712// TODO: pass `FlushAO` after memory ordering support is added7713(void)FlushAO;7714emitFlush(Loc);7715}77167717// for AO == AtomicOrdering::Monotonic and all other case combinations7718// do nothing7719return Flush;7720}77217722OpenMPIRBuilder::InsertPointTy7723OpenMPIRBuilder::createAtomicRead(const LocationDescription &Loc,7724AtomicOpValue &X, AtomicOpValue &V,7725AtomicOrdering AO) {7726if (!updateToLocation(Loc))7727return Loc.IP;77287729assert(X.Var->getType()->isPointerTy() &&7730"OMP Atomic expects a pointer to target memory");7731Type *XElemTy = X.ElemTy;7732assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||7733XElemTy->isPointerTy()) &&7734"OMP atomic read expected a scalar type");77357736Value *XRead = nullptr;77377738if (XElemTy->isIntegerTy()) {7739LoadInst *XLD =7740Builder.CreateLoad(XElemTy, X.Var, X.IsVolatile, "omp.atomic.read");7741XLD->setAtomic(AO);7742XRead = cast<Value>(XLD);7743} else {7744// We need to perform atomic op as integer7745IntegerType *IntCastTy =7746IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());7747LoadInst *XLoad =7748Builder.CreateLoad(IntCastTy, X.Var, X.IsVolatile, "omp.atomic.load");7749XLoad->setAtomic(AO);7750if (XElemTy->isFloatingPointTy()) {7751XRead = Builder.CreateBitCast(XLoad, XElemTy, "atomic.flt.cast");7752} else {7753XRead = Builder.CreateIntToPtr(XLoad, XElemTy, "atomic.ptr.cast");7754}7755}7756checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Read);7757Builder.CreateStore(XRead, V.Var, V.IsVolatile);7758return Builder.saveIP();7759}77607761OpenMPIRBuilder::InsertPointTy7762OpenMPIRBuilder::createAtomicWrite(const LocationDescription &Loc,7763AtomicOpValue &X, Value *Expr,7764AtomicOrdering AO) {7765if (!updateToLocation(Loc))7766return Loc.IP;77677768assert(X.Var->getType()->isPointerTy() &&7769"OMP Atomic expects a pointer to target memory");7770Type *XElemTy = X.ElemTy;7771assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||7772XElemTy->isPointerTy()) &&7773"OMP atomic write expected a scalar type");77747775if (XElemTy->isIntegerTy()) {7776StoreInst *XSt = Builder.CreateStore(Expr, X.Var, X.IsVolatile);7777XSt->setAtomic(AO);7778} else {7779// We need to bitcast and perform atomic op as integers7780IntegerType *IntCastTy =7781IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());7782Value *ExprCast =7783Builder.CreateBitCast(Expr, IntCastTy, "atomic.src.int.cast");7784StoreInst *XSt = Builder.CreateStore(ExprCast, X.Var, X.IsVolatile);7785XSt->setAtomic(AO);7786}77877788checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Write);7789return Builder.saveIP();7790}77917792OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicUpdate(7793const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,7794Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,7795AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr) {7796assert(!isConflictIP(Loc.IP, AllocaIP) && "IPs must not be ambiguous");7797if (!updateToLocation(Loc))7798return Loc.IP;77997800LLVM_DEBUG({7801Type *XTy = X.Var->getType();7802assert(XTy->isPointerTy() &&7803"OMP Atomic expects a pointer to target memory");7804Type *XElemTy = X.ElemTy;7805assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||7806XElemTy->isPointerTy()) &&7807"OMP atomic update expected a scalar type");7808assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&7809(RMWOp != AtomicRMWInst::UMax) && (RMWOp != AtomicRMWInst::UMin) &&7810"OpenMP atomic does not support LT or GT operations");7811});78127813emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, RMWOp, UpdateOp,7814X.IsVolatile, IsXBinopExpr);7815checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Update);7816return Builder.saveIP();7817}78187819// FIXME: Duplicating AtomicExpand7820Value *OpenMPIRBuilder::emitRMWOpAsInstruction(Value *Src1, Value *Src2,7821AtomicRMWInst::BinOp RMWOp) {7822switch (RMWOp) {7823case AtomicRMWInst::Add:7824return Builder.CreateAdd(Src1, Src2);7825case AtomicRMWInst::Sub:7826return Builder.CreateSub(Src1, Src2);7827case AtomicRMWInst::And:7828return Builder.CreateAnd(Src1, Src2);7829case AtomicRMWInst::Nand:7830return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));7831case AtomicRMWInst::Or:7832return Builder.CreateOr(Src1, Src2);7833case AtomicRMWInst::Xor:7834return Builder.CreateXor(Src1, Src2);7835case AtomicRMWInst::Xchg:7836case AtomicRMWInst::FAdd:7837case AtomicRMWInst::FSub:7838case AtomicRMWInst::BAD_BINOP:7839case AtomicRMWInst::Max:7840case AtomicRMWInst::Min:7841case AtomicRMWInst::UMax:7842case AtomicRMWInst::UMin:7843case AtomicRMWInst::FMax:7844case AtomicRMWInst::FMin:7845case AtomicRMWInst::UIncWrap:7846case AtomicRMWInst::UDecWrap:7847llvm_unreachable("Unsupported atomic update operation");7848}7849llvm_unreachable("Unsupported atomic update operation");7850}78517852std::pair<Value *, Value *> OpenMPIRBuilder::emitAtomicUpdate(7853InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,7854AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,7855AtomicUpdateCallbackTy &UpdateOp, bool VolatileX, bool IsXBinopExpr) {7856// TODO: handle the case where XElemTy is not byte-sized or not a power of 27857// or a complex datatype.7858bool emitRMWOp = false;7859switch (RMWOp) {7860case AtomicRMWInst::Add:7861case AtomicRMWInst::And:7862case AtomicRMWInst::Nand:7863case AtomicRMWInst::Or:7864case AtomicRMWInst::Xor:7865case AtomicRMWInst::Xchg:7866emitRMWOp = XElemTy;7867break;7868case AtomicRMWInst::Sub:7869emitRMWOp = (IsXBinopExpr && XElemTy);7870break;7871default:7872emitRMWOp = false;7873}7874emitRMWOp &= XElemTy->isIntegerTy();78757876std::pair<Value *, Value *> Res;7877if (emitRMWOp) {7878Res.first = Builder.CreateAtomicRMW(RMWOp, X, Expr, llvm::MaybeAlign(), AO);7879// not needed except in case of postfix captures. Generate anyway for7880// consistency with the else part. Will be removed with any DCE pass.7881// AtomicRMWInst::Xchg does not have a coressponding instruction.7882if (RMWOp == AtomicRMWInst::Xchg)7883Res.second = Res.first;7884else7885Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);7886} else {7887IntegerType *IntCastTy =7888IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());7889LoadInst *OldVal =7890Builder.CreateLoad(IntCastTy, X, X->getName() + ".atomic.load");7891OldVal->setAtomic(AO);7892// CurBB7893// | /---\7894// ContBB |7895// | \---/7896// ExitBB7897BasicBlock *CurBB = Builder.GetInsertBlock();7898Instruction *CurBBTI = CurBB->getTerminator();7899CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();7900BasicBlock *ExitBB =7901CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");7902BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),7903X->getName() + ".atomic.cont");7904ContBB->getTerminator()->eraseFromParent();7905Builder.restoreIP(AllocaIP);7906AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);7907NewAtomicAddr->setName(X->getName() + "x.new.val");7908Builder.SetInsertPoint(ContBB);7909llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);7910PHI->addIncoming(OldVal, CurBB);7911bool IsIntTy = XElemTy->isIntegerTy();7912Value *OldExprVal = PHI;7913if (!IsIntTy) {7914if (XElemTy->isFloatingPointTy()) {7915OldExprVal = Builder.CreateBitCast(PHI, XElemTy,7916X->getName() + ".atomic.fltCast");7917} else {7918OldExprVal = Builder.CreateIntToPtr(PHI, XElemTy,7919X->getName() + ".atomic.ptrCast");7920}7921}79227923Value *Upd = UpdateOp(OldExprVal, Builder);7924Builder.CreateStore(Upd, NewAtomicAddr);7925LoadInst *DesiredVal = Builder.CreateLoad(IntCastTy, NewAtomicAddr);7926AtomicOrdering Failure =7927llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);7928AtomicCmpXchgInst *Result = Builder.CreateAtomicCmpXchg(7929X, PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);7930Result->setVolatile(VolatileX);7931Value *PreviousVal = Builder.CreateExtractValue(Result, /*Idxs=*/0);7932Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);7933PHI->addIncoming(PreviousVal, Builder.GetInsertBlock());7934Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);79357936Res.first = OldExprVal;7937Res.second = Upd;79387939// set Insertion point in exit block7940if (UnreachableInst *ExitTI =7941dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {7942CurBBTI->eraseFromParent();7943Builder.SetInsertPoint(ExitBB);7944} else {7945Builder.SetInsertPoint(ExitTI);7946}7947}79487949return Res;7950}79517952OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCapture(7953const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,7954AtomicOpValue &V, Value *Expr, AtomicOrdering AO,7955AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,7956bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr) {7957if (!updateToLocation(Loc))7958return Loc.IP;79597960LLVM_DEBUG({7961Type *XTy = X.Var->getType();7962assert(XTy->isPointerTy() &&7963"OMP Atomic expects a pointer to target memory");7964Type *XElemTy = X.ElemTy;7965assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||7966XElemTy->isPointerTy()) &&7967"OMP atomic capture expected a scalar type");7968assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&7969"OpenMP atomic does not support LT or GT operations");7970});79717972// If UpdateExpr is 'x' updated with some `expr` not based on 'x',7973// 'x' is simply atomically rewritten with 'expr'.7974AtomicRMWInst::BinOp AtomicOp = (UpdateExpr ? RMWOp : AtomicRMWInst::Xchg);7975std::pair<Value *, Value *> Result =7976emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, AtomicOp, UpdateOp,7977X.IsVolatile, IsXBinopExpr);79787979Value *CapturedVal = (IsPostfixUpdate ? Result.first : Result.second);7980Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);79817982checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Capture);7983return Builder.saveIP();7984}79857986OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCompare(7987const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,7988AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,7989omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,7990bool IsFailOnly) {79917992AtomicOrdering Failure = AtomicCmpXchgInst::getStrongestFailureOrdering(AO);7993return createAtomicCompare(Loc, X, V, R, E, D, AO, Op, IsXBinopExpr,7994IsPostfixUpdate, IsFailOnly, Failure);7995}79967997OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCompare(7998const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,7999AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,8000omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,8001bool IsFailOnly, AtomicOrdering Failure) {80028003if (!updateToLocation(Loc))8004return Loc.IP;80058006assert(X.Var->getType()->isPointerTy() &&8007"OMP atomic expects a pointer to target memory");8008// compare capture8009if (V.Var) {8010assert(V.Var->getType()->isPointerTy() && "v.var must be of pointer type");8011assert(V.ElemTy == X.ElemTy && "x and v must be of same type");8012}80138014bool IsInteger = E->getType()->isIntegerTy();80158016if (Op == OMPAtomicCompareOp::EQ) {8017AtomicCmpXchgInst *Result = nullptr;8018if (!IsInteger) {8019IntegerType *IntCastTy =8020IntegerType::get(M.getContext(), X.ElemTy->getScalarSizeInBits());8021Value *EBCast = Builder.CreateBitCast(E, IntCastTy);8022Value *DBCast = Builder.CreateBitCast(D, IntCastTy);8023Result = Builder.CreateAtomicCmpXchg(X.Var, EBCast, DBCast, MaybeAlign(),8024AO, Failure);8025} else {8026Result =8027Builder.CreateAtomicCmpXchg(X.Var, E, D, MaybeAlign(), AO, Failure);8028}80298030if (V.Var) {8031Value *OldValue = Builder.CreateExtractValue(Result, /*Idxs=*/0);8032if (!IsInteger)8033OldValue = Builder.CreateBitCast(OldValue, X.ElemTy);8034assert(OldValue->getType() == V.ElemTy &&8035"OldValue and V must be of same type");8036if (IsPostfixUpdate) {8037Builder.CreateStore(OldValue, V.Var, V.IsVolatile);8038} else {8039Value *SuccessOrFail = Builder.CreateExtractValue(Result, /*Idxs=*/1);8040if (IsFailOnly) {8041// CurBB----8042// | |8043// v |8044// ContBB |8045// | |8046// v |8047// ExitBB <-8048//8049// where ContBB only contains the store of old value to 'v'.8050BasicBlock *CurBB = Builder.GetInsertBlock();8051Instruction *CurBBTI = CurBB->getTerminator();8052CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();8053BasicBlock *ExitBB = CurBB->splitBasicBlock(8054CurBBTI, X.Var->getName() + ".atomic.exit");8055BasicBlock *ContBB = CurBB->splitBasicBlock(8056CurBB->getTerminator(), X.Var->getName() + ".atomic.cont");8057ContBB->getTerminator()->eraseFromParent();8058CurBB->getTerminator()->eraseFromParent();80598060Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);80618062Builder.SetInsertPoint(ContBB);8063Builder.CreateStore(OldValue, V.Var);8064Builder.CreateBr(ExitBB);80658066if (UnreachableInst *ExitTI =8067dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {8068CurBBTI->eraseFromParent();8069Builder.SetInsertPoint(ExitBB);8070} else {8071Builder.SetInsertPoint(ExitTI);8072}8073} else {8074Value *CapturedValue =8075Builder.CreateSelect(SuccessOrFail, E, OldValue);8076Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);8077}8078}8079}8080// The comparison result has to be stored.8081if (R.Var) {8082assert(R.Var->getType()->isPointerTy() &&8083"r.var must be of pointer type");8084assert(R.ElemTy->isIntegerTy() && "r must be of integral type");80858086Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);8087Value *ResultCast = R.IsSigned8088? Builder.CreateSExt(SuccessFailureVal, R.ElemTy)8089: Builder.CreateZExt(SuccessFailureVal, R.ElemTy);8090Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);8091}8092} else {8093assert((Op == OMPAtomicCompareOp::MAX || Op == OMPAtomicCompareOp::MIN) &&8094"Op should be either max or min at this point");8095assert(!IsFailOnly && "IsFailOnly is only valid when the comparison is ==");80968097// Reverse the ordop as the OpenMP forms are different from LLVM forms.8098// Let's take max as example.8099// OpenMP form:8100// x = x > expr ? expr : x;8101// LLVM form:8102// *ptr = *ptr > val ? *ptr : val;8103// We need to transform to LLVM form.8104// x = x <= expr ? x : expr;8105AtomicRMWInst::BinOp NewOp;8106if (IsXBinopExpr) {8107if (IsInteger) {8108if (X.IsSigned)8109NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Min8110: AtomicRMWInst::Max;8111else8112NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMin8113: AtomicRMWInst::UMax;8114} else {8115NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMin8116: AtomicRMWInst::FMax;8117}8118} else {8119if (IsInteger) {8120if (X.IsSigned)8121NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Max8122: AtomicRMWInst::Min;8123else8124NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMax8125: AtomicRMWInst::UMin;8126} else {8127NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMax8128: AtomicRMWInst::FMin;8129}8130}81318132AtomicRMWInst *OldValue =8133Builder.CreateAtomicRMW(NewOp, X.Var, E, MaybeAlign(), AO);8134if (V.Var) {8135Value *CapturedValue = nullptr;8136if (IsPostfixUpdate) {8137CapturedValue = OldValue;8138} else {8139CmpInst::Predicate Pred;8140switch (NewOp) {8141case AtomicRMWInst::Max:8142Pred = CmpInst::ICMP_SGT;8143break;8144case AtomicRMWInst::UMax:8145Pred = CmpInst::ICMP_UGT;8146break;8147case AtomicRMWInst::FMax:8148Pred = CmpInst::FCMP_OGT;8149break;8150case AtomicRMWInst::Min:8151Pred = CmpInst::ICMP_SLT;8152break;8153case AtomicRMWInst::UMin:8154Pred = CmpInst::ICMP_ULT;8155break;8156case AtomicRMWInst::FMin:8157Pred = CmpInst::FCMP_OLT;8158break;8159default:8160llvm_unreachable("unexpected comparison op");8161}8162Value *NonAtomicCmp = Builder.CreateCmp(Pred, OldValue, E);8163CapturedValue = Builder.CreateSelect(NonAtomicCmp, E, OldValue);8164}8165Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);8166}8167}81688169checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Compare);81708171return Builder.saveIP();8172}81738174OpenMPIRBuilder::InsertPointTy8175OpenMPIRBuilder::createTeams(const LocationDescription &Loc,8176BodyGenCallbackTy BodyGenCB, Value *NumTeamsLower,8177Value *NumTeamsUpper, Value *ThreadLimit,8178Value *IfExpr) {8179if (!updateToLocation(Loc))8180return InsertPointTy();81818182uint32_t SrcLocStrSize;8183Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);8184Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);8185Function *CurrentFunction = Builder.GetInsertBlock()->getParent();81868187// Outer allocation basicblock is the entry block of the current function.8188BasicBlock &OuterAllocaBB = CurrentFunction->getEntryBlock();8189if (&OuterAllocaBB == Builder.GetInsertBlock()) {8190BasicBlock *BodyBB = splitBB(Builder, /*CreateBranch=*/true, "teams.entry");8191Builder.SetInsertPoint(BodyBB, BodyBB->begin());8192}81938194// The current basic block is split into four basic blocks. After outlining,8195// they will be mapped as follows:8196// ```8197// def current_fn() {8198// current_basic_block:8199// br label %teams.exit8200// teams.exit:8201// ; instructions after teams8202// }8203//8204// def outlined_fn() {8205// teams.alloca:8206// br label %teams.body8207// teams.body:8208// ; instructions within teams body8209// }8210// ```8211BasicBlock *ExitBB = splitBB(Builder, /*CreateBranch=*/true, "teams.exit");8212BasicBlock *BodyBB = splitBB(Builder, /*CreateBranch=*/true, "teams.body");8213BasicBlock *AllocaBB =8214splitBB(Builder, /*CreateBranch=*/true, "teams.alloca");82158216bool SubClausesPresent =8217(NumTeamsLower || NumTeamsUpper || ThreadLimit || IfExpr);8218// Push num_teams8219if (!Config.isTargetDevice() && SubClausesPresent) {8220assert((NumTeamsLower == nullptr || NumTeamsUpper != nullptr) &&8221"if lowerbound is non-null, then upperbound must also be non-null "8222"for bounds on num_teams");82238224if (NumTeamsUpper == nullptr)8225NumTeamsUpper = Builder.getInt32(0);82268227if (NumTeamsLower == nullptr)8228NumTeamsLower = NumTeamsUpper;82298230if (IfExpr) {8231assert(IfExpr->getType()->isIntegerTy() &&8232"argument to if clause must be an integer value");82338234// upper = ifexpr ? upper : 18235if (IfExpr->getType() != Int1)8236IfExpr = Builder.CreateICmpNE(IfExpr,8237ConstantInt::get(IfExpr->getType(), 0));8238NumTeamsUpper = Builder.CreateSelect(8239IfExpr, NumTeamsUpper, Builder.getInt32(1), "numTeamsUpper");82408241// lower = ifexpr ? lower : 18242NumTeamsLower = Builder.CreateSelect(8243IfExpr, NumTeamsLower, Builder.getInt32(1), "numTeamsLower");8244}82458246if (ThreadLimit == nullptr)8247ThreadLimit = Builder.getInt32(0);82488249Value *ThreadNum = getOrCreateThreadID(Ident);8250Builder.CreateCall(8251getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_teams_51),8252{Ident, ThreadNum, NumTeamsLower, NumTeamsUpper, ThreadLimit});8253}8254// Generate the body of teams.8255InsertPointTy AllocaIP(AllocaBB, AllocaBB->begin());8256InsertPointTy CodeGenIP(BodyBB, BodyBB->begin());8257BodyGenCB(AllocaIP, CodeGenIP);82588259OutlineInfo OI;8260OI.EntryBB = AllocaBB;8261OI.ExitBB = ExitBB;8262OI.OuterAllocaBB = &OuterAllocaBB;82638264// Insert fake values for global tid and bound tid.8265SmallVector<Instruction *, 8> ToBeDeleted;8266InsertPointTy OuterAllocaIP(&OuterAllocaBB, OuterAllocaBB.begin());8267OI.ExcludeArgsFromAggregate.push_back(createFakeIntVal(8268Builder, OuterAllocaIP, ToBeDeleted, AllocaIP, "gid", true));8269OI.ExcludeArgsFromAggregate.push_back(createFakeIntVal(8270Builder, OuterAllocaIP, ToBeDeleted, AllocaIP, "tid", true));82718272auto HostPostOutlineCB = [this, Ident,8273ToBeDeleted](Function &OutlinedFn) mutable {8274// The stale call instruction will be replaced with a new call instruction8275// for runtime call with the outlined function.82768277assert(OutlinedFn.getNumUses() == 1 &&8278"there must be a single user for the outlined function");8279CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());8280ToBeDeleted.push_back(StaleCI);82818282assert((OutlinedFn.arg_size() == 2 || OutlinedFn.arg_size() == 3) &&8283"Outlined function must have two or three arguments only");82848285bool HasShared = OutlinedFn.arg_size() == 3;82868287OutlinedFn.getArg(0)->setName("global.tid.ptr");8288OutlinedFn.getArg(1)->setName("bound.tid.ptr");8289if (HasShared)8290OutlinedFn.getArg(2)->setName("data");82918292// Call to the runtime function for teams in the current function.8293assert(StaleCI && "Error while outlining - no CallInst user found for the "8294"outlined function.");8295Builder.SetInsertPoint(StaleCI);8296SmallVector<Value *> Args = {8297Ident, Builder.getInt32(StaleCI->arg_size() - 2), &OutlinedFn};8298if (HasShared)8299Args.push_back(StaleCI->getArgOperand(2));8300Builder.CreateCall(getOrCreateRuntimeFunctionPtr(8301omp::RuntimeFunction::OMPRTL___kmpc_fork_teams),8302Args);83038304llvm::for_each(llvm::reverse(ToBeDeleted),8305[](Instruction *I) { I->eraseFromParent(); });83068307};83088309if (!Config.isTargetDevice())8310OI.PostOutlineCB = HostPostOutlineCB;83118312addOutlineInfo(std::move(OI));83138314Builder.SetInsertPoint(ExitBB, ExitBB->begin());83158316return Builder.saveIP();8317}83188319GlobalVariable *8320OpenMPIRBuilder::createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,8321std::string VarName) {8322llvm::Constant *MapNamesArrayInit = llvm::ConstantArray::get(8323llvm::ArrayType::get(llvm::PointerType::getUnqual(M.getContext()),8324Names.size()),8325Names);8326auto *MapNamesArrayGlobal = new llvm::GlobalVariable(8327M, MapNamesArrayInit->getType(),8328/*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MapNamesArrayInit,8329VarName);8330return MapNamesArrayGlobal;8331}83328333// Create all simple and struct types exposed by the runtime and remember8334// the llvm::PointerTypes of them for easy access later.8335void OpenMPIRBuilder::initializeTypes(Module &M) {8336LLVMContext &Ctx = M.getContext();8337StructType *T;8338#define OMP_TYPE(VarName, InitValue) VarName = InitValue;8339#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \8340VarName##Ty = ArrayType::get(ElemTy, ArraySize); \8341VarName##PtrTy = PointerType::getUnqual(VarName##Ty);8342#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \8343VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg); \8344VarName##Ptr = PointerType::getUnqual(VarName);8345#define OMP_STRUCT_TYPE(VarName, StructName, Packed, ...) \8346T = StructType::getTypeByName(Ctx, StructName); \8347if (!T) \8348T = StructType::create(Ctx, {__VA_ARGS__}, StructName, Packed); \8349VarName = T; \8350VarName##Ptr = PointerType::getUnqual(T);8351#include "llvm/Frontend/OpenMP/OMPKinds.def"8352}83538354void OpenMPIRBuilder::OutlineInfo::collectBlocks(8355SmallPtrSetImpl<BasicBlock *> &BlockSet,8356SmallVectorImpl<BasicBlock *> &BlockVector) {8357SmallVector<BasicBlock *, 32> Worklist;8358BlockSet.insert(EntryBB);8359BlockSet.insert(ExitBB);83608361Worklist.push_back(EntryBB);8362while (!Worklist.empty()) {8363BasicBlock *BB = Worklist.pop_back_val();8364BlockVector.push_back(BB);8365for (BasicBlock *SuccBB : successors(BB))8366if (BlockSet.insert(SuccBB).second)8367Worklist.push_back(SuccBB);8368}8369}83708371void OpenMPIRBuilder::createOffloadEntry(Constant *ID, Constant *Addr,8372uint64_t Size, int32_t Flags,8373GlobalValue::LinkageTypes,8374StringRef Name) {8375if (!Config.isGPU()) {8376llvm::offloading::emitOffloadingEntry(8377M, ID, Name.empty() ? Addr->getName() : Name, Size, Flags, /*Data=*/0,8378"omp_offloading_entries");8379return;8380}8381// TODO: Add support for global variables on the device after declare target8382// support.8383Function *Fn = dyn_cast<Function>(Addr);8384if (!Fn)8385return;83868387Module &M = *(Fn->getParent());8388LLVMContext &Ctx = M.getContext();83898390// Get "nvvm.annotations" metadata node.8391NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");83928393Metadata *MDVals[] = {8394ConstantAsMetadata::get(Fn), MDString::get(Ctx, "kernel"),8395ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Ctx), 1))};8396// Append metadata to nvvm.annotations.8397MD->addOperand(MDNode::get(Ctx, MDVals));83988399// Add a function attribute for the kernel.8400Fn->addFnAttr(Attribute::get(Ctx, "kernel"));8401if (T.isAMDGCN())8402Fn->addFnAttr("uniform-work-group-size", "true");8403Fn->addFnAttr(Attribute::MustProgress);8404}84058406// We only generate metadata for function that contain target regions.8407void OpenMPIRBuilder::createOffloadEntriesAndInfoMetadata(8408EmitMetadataErrorReportFunctionTy &ErrorFn) {84098410// If there are no entries, we don't need to do anything.8411if (OffloadInfoManager.empty())8412return;84138414LLVMContext &C = M.getContext();8415SmallVector<std::pair<const OffloadEntriesInfoManager::OffloadEntryInfo *,8416TargetRegionEntryInfo>,841716>8418OrderedEntries(OffloadInfoManager.size());84198420// Auxiliary methods to create metadata values and strings.8421auto &&GetMDInt = [this](unsigned V) {8422return ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), V));8423};84248425auto &&GetMDString = [&C](StringRef V) { return MDString::get(C, V); };84268427// Create the offloading info metadata node.8428NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");8429auto &&TargetRegionMetadataEmitter =8430[&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](8431const TargetRegionEntryInfo &EntryInfo,8432const OffloadEntriesInfoManager::OffloadEntryInfoTargetRegion &E) {8433// Generate metadata for target regions. Each entry of this metadata8434// contains:8435// - Entry 0 -> Kind of this type of metadata (0).8436// - Entry 1 -> Device ID of the file where the entry was identified.8437// - Entry 2 -> File ID of the file where the entry was identified.8438// - Entry 3 -> Mangled name of the function where the entry was8439// identified.8440// - Entry 4 -> Line in the file where the entry was identified.8441// - Entry 5 -> Count of regions at this DeviceID/FilesID/Line.8442// - Entry 6 -> Order the entry was created.8443// The first element of the metadata node is the kind.8444Metadata *Ops[] = {8445GetMDInt(E.getKind()), GetMDInt(EntryInfo.DeviceID),8446GetMDInt(EntryInfo.FileID), GetMDString(EntryInfo.ParentName),8447GetMDInt(EntryInfo.Line), GetMDInt(EntryInfo.Count),8448GetMDInt(E.getOrder())};84498450// Save this entry in the right position of the ordered entries array.8451OrderedEntries[E.getOrder()] = std::make_pair(&E, EntryInfo);84528453// Add metadata to the named metadata node.8454MD->addOperand(MDNode::get(C, Ops));8455};84568457OffloadInfoManager.actOnTargetRegionEntriesInfo(TargetRegionMetadataEmitter);84588459// Create function that emits metadata for each device global variable entry;8460auto &&DeviceGlobalVarMetadataEmitter =8461[&C, &OrderedEntries, &GetMDInt, &GetMDString, MD](8462StringRef MangledName,8463const OffloadEntriesInfoManager::OffloadEntryInfoDeviceGlobalVar &E) {8464// Generate metadata for global variables. Each entry of this metadata8465// contains:8466// - Entry 0 -> Kind of this type of metadata (1).8467// - Entry 1 -> Mangled name of the variable.8468// - Entry 2 -> Declare target kind.8469// - Entry 3 -> Order the entry was created.8470// The first element of the metadata node is the kind.8471Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDString(MangledName),8472GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};84738474// Save this entry in the right position of the ordered entries array.8475TargetRegionEntryInfo varInfo(MangledName, 0, 0, 0);8476OrderedEntries[E.getOrder()] = std::make_pair(&E, varInfo);84778478// Add metadata to the named metadata node.8479MD->addOperand(MDNode::get(C, Ops));8480};84818482OffloadInfoManager.actOnDeviceGlobalVarEntriesInfo(8483DeviceGlobalVarMetadataEmitter);84848485for (const auto &E : OrderedEntries) {8486assert(E.first && "All ordered entries must exist!");8487if (const auto *CE =8488dyn_cast<OffloadEntriesInfoManager::OffloadEntryInfoTargetRegion>(8489E.first)) {8490if (!CE->getID() || !CE->getAddress()) {8491// Do not blame the entry if the parent funtion is not emitted.8492TargetRegionEntryInfo EntryInfo = E.second;8493StringRef FnName = EntryInfo.ParentName;8494if (!M.getNamedValue(FnName))8495continue;8496ErrorFn(EMIT_MD_TARGET_REGION_ERROR, EntryInfo);8497continue;8498}8499createOffloadEntry(CE->getID(), CE->getAddress(),8500/*Size=*/0, CE->getFlags(),8501GlobalValue::WeakAnyLinkage);8502} else if (const auto *CE = dyn_cast<8503OffloadEntriesInfoManager::OffloadEntryInfoDeviceGlobalVar>(8504E.first)) {8505OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind Flags =8506static_cast<OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind>(8507CE->getFlags());8508switch (Flags) {8509case OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter:8510case OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo:8511if (Config.isTargetDevice() && Config.hasRequiresUnifiedSharedMemory())8512continue;8513if (!CE->getAddress()) {8514ErrorFn(EMIT_MD_DECLARE_TARGET_ERROR, E.second);8515continue;8516}8517// The vaiable has no definition - no need to add the entry.8518if (CE->getVarSize() == 0)8519continue;8520break;8521case OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink:8522assert(((Config.isTargetDevice() && !CE->getAddress()) ||8523(!Config.isTargetDevice() && CE->getAddress())) &&8524"Declaret target link address is set.");8525if (Config.isTargetDevice())8526continue;8527if (!CE->getAddress()) {8528ErrorFn(EMIT_MD_GLOBAL_VAR_LINK_ERROR, TargetRegionEntryInfo());8529continue;8530}8531break;8532default:8533break;8534}85358536// Hidden or internal symbols on the device are not externally visible.8537// We should not attempt to register them by creating an offloading8538// entry. Indirect variables are handled separately on the device.8539if (auto *GV = dyn_cast<GlobalValue>(CE->getAddress()))8540if ((GV->hasLocalLinkage() || GV->hasHiddenVisibility()) &&8541Flags != OffloadEntriesInfoManager::OMPTargetGlobalVarEntryIndirect)8542continue;85438544// Indirect globals need to use a special name that doesn't match the name8545// of the associated host global.8546if (Flags == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryIndirect)8547createOffloadEntry(CE->getAddress(), CE->getAddress(), CE->getVarSize(),8548Flags, CE->getLinkage(), CE->getVarName());8549else8550createOffloadEntry(CE->getAddress(), CE->getAddress(), CE->getVarSize(),8551Flags, CE->getLinkage());85528553} else {8554llvm_unreachable("Unsupported entry kind.");8555}8556}85578558// Emit requires directive globals to a special entry so the runtime can8559// register them when the device image is loaded.8560// TODO: This reduces the offloading entries to a 32-bit integer. Offloading8561// entries should be redesigned to better suit this use-case.8562if (Config.hasRequiresFlags() && !Config.isTargetDevice())8563offloading::emitOffloadingEntry(8564M, Constant::getNullValue(PointerType::getUnqual(M.getContext())),8565/*Name=*/"",8566/*Size=*/0, OffloadEntriesInfoManager::OMPTargetGlobalRegisterRequires,8567Config.getRequiresFlags(), "omp_offloading_entries");8568}85698570void TargetRegionEntryInfo::getTargetRegionEntryFnName(8571SmallVectorImpl<char> &Name, StringRef ParentName, unsigned DeviceID,8572unsigned FileID, unsigned Line, unsigned Count) {8573raw_svector_ostream OS(Name);8574OS << "__omp_offloading" << llvm::format("_%x", DeviceID)8575<< llvm::format("_%x_", FileID) << ParentName << "_l" << Line;8576if (Count)8577OS << "_" << Count;8578}85798580void OffloadEntriesInfoManager::getTargetRegionEntryFnName(8581SmallVectorImpl<char> &Name, const TargetRegionEntryInfo &EntryInfo) {8582unsigned NewCount = getTargetRegionEntryInfoCount(EntryInfo);8583TargetRegionEntryInfo::getTargetRegionEntryFnName(8584Name, EntryInfo.ParentName, EntryInfo.DeviceID, EntryInfo.FileID,8585EntryInfo.Line, NewCount);8586}85878588TargetRegionEntryInfo8589OpenMPIRBuilder::getTargetEntryUniqueInfo(FileIdentifierInfoCallbackTy CallBack,8590StringRef ParentName) {8591sys::fs::UniqueID ID;8592auto FileIDInfo = CallBack();8593if (auto EC = sys::fs::getUniqueID(std::get<0>(FileIDInfo), ID)) {8594report_fatal_error(("Unable to get unique ID for file, during "8595"getTargetEntryUniqueInfo, error message: " +8596EC.message())8597.c_str());8598}85998600return TargetRegionEntryInfo(ParentName, ID.getDevice(), ID.getFile(),8601std::get<1>(FileIDInfo));8602}86038604unsigned OpenMPIRBuilder::getFlagMemberOffset() {8605unsigned Offset = 0;8606for (uint64_t Remain =8607static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(8608omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF);8609!(Remain & 1); Remain = Remain >> 1)8610Offset++;8611return Offset;8612}86138614omp::OpenMPOffloadMappingFlags8615OpenMPIRBuilder::getMemberOfFlag(unsigned Position) {8616// Rotate by getFlagMemberOffset() bits.8617return static_cast<omp::OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)8618<< getFlagMemberOffset());8619}86208621void OpenMPIRBuilder::setCorrectMemberOfFlag(8622omp::OpenMPOffloadMappingFlags &Flags,8623omp::OpenMPOffloadMappingFlags MemberOfFlag) {8624// If the entry is PTR_AND_OBJ but has not been marked with the special8625// placeholder value 0xFFFF in the MEMBER_OF field, then it should not be8626// marked as MEMBER_OF.8627if (static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(8628Flags & omp::OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ) &&8629static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(8630(Flags & omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF) !=8631omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF))8632return;86338634// Reset the placeholder value to prepare the flag for the assignment of the8635// proper MEMBER_OF value.8636Flags &= ~omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;8637Flags |= MemberOfFlag;8638}86398640Constant *OpenMPIRBuilder::getAddrOfDeclareTargetVar(8641OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause,8642OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause,8643bool IsDeclaration, bool IsExternallyVisible,8644TargetRegionEntryInfo EntryInfo, StringRef MangledName,8645std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,8646std::vector<Triple> TargetTriple, Type *LlvmPtrTy,8647std::function<Constant *()> GlobalInitializer,8648std::function<GlobalValue::LinkageTypes()> VariableLinkage) {8649// TODO: convert this to utilise the IRBuilder Config rather than8650// a passed down argument.8651if (OpenMPSIMD)8652return nullptr;86538654if (CaptureClause == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink ||8655((CaptureClause == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo ||8656CaptureClause ==8657OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter) &&8658Config.hasRequiresUnifiedSharedMemory())) {8659SmallString<64> PtrName;8660{8661raw_svector_ostream OS(PtrName);8662OS << MangledName;8663if (!IsExternallyVisible)8664OS << format("_%x", EntryInfo.FileID);8665OS << "_decl_tgt_ref_ptr";8666}86678668Value *Ptr = M.getNamedValue(PtrName);86698670if (!Ptr) {8671GlobalValue *GlobalValue = M.getNamedValue(MangledName);8672Ptr = getOrCreateInternalVariable(LlvmPtrTy, PtrName);86738674auto *GV = cast<GlobalVariable>(Ptr);8675GV->setLinkage(GlobalValue::WeakAnyLinkage);86768677if (!Config.isTargetDevice()) {8678if (GlobalInitializer)8679GV->setInitializer(GlobalInitializer());8680else8681GV->setInitializer(GlobalValue);8682}86838684registerTargetGlobalVariable(8685CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,8686EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,8687GlobalInitializer, VariableLinkage, LlvmPtrTy, cast<Constant>(Ptr));8688}86898690return cast<Constant>(Ptr);8691}86928693return nullptr;8694}86958696void OpenMPIRBuilder::registerTargetGlobalVariable(8697OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause,8698OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause,8699bool IsDeclaration, bool IsExternallyVisible,8700TargetRegionEntryInfo EntryInfo, StringRef MangledName,8701std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,8702std::vector<Triple> TargetTriple,8703std::function<Constant *()> GlobalInitializer,8704std::function<GlobalValue::LinkageTypes()> VariableLinkage, Type *LlvmPtrTy,8705Constant *Addr) {8706if (DeviceClause != OffloadEntriesInfoManager::OMPTargetDeviceClauseAny ||8707(TargetTriple.empty() && !Config.isTargetDevice()))8708return;87098710OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind Flags;8711StringRef VarName;8712int64_t VarSize;8713GlobalValue::LinkageTypes Linkage;87148715if ((CaptureClause == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo ||8716CaptureClause ==8717OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter) &&8718!Config.hasRequiresUnifiedSharedMemory()) {8719Flags = OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;8720VarName = MangledName;8721GlobalValue *LlvmVal = M.getNamedValue(VarName);87228723if (!IsDeclaration)8724VarSize = divideCeil(8725M.getDataLayout().getTypeSizeInBits(LlvmVal->getValueType()), 8);8726else8727VarSize = 0;8728Linkage = (VariableLinkage) ? VariableLinkage() : LlvmVal->getLinkage();87298730// This is a workaround carried over from Clang which prevents undesired8731// optimisation of internal variables.8732if (Config.isTargetDevice() &&8733(!IsExternallyVisible || Linkage == GlobalValue::LinkOnceODRLinkage)) {8734// Do not create a "ref-variable" if the original is not also available8735// on the host.8736if (!OffloadInfoManager.hasDeviceGlobalVarEntryInfo(VarName))8737return;87388739std::string RefName = createPlatformSpecificName({VarName, "ref"});87408741if (!M.getNamedValue(RefName)) {8742Constant *AddrRef =8743getOrCreateInternalVariable(Addr->getType(), RefName);8744auto *GvAddrRef = cast<GlobalVariable>(AddrRef);8745GvAddrRef->setConstant(true);8746GvAddrRef->setLinkage(GlobalValue::InternalLinkage);8747GvAddrRef->setInitializer(Addr);8748GeneratedRefs.push_back(GvAddrRef);8749}8750}8751} else {8752if (CaptureClause == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink)8753Flags = OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink;8754else8755Flags = OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;87568757if (Config.isTargetDevice()) {8758VarName = (Addr) ? Addr->getName() : "";8759Addr = nullptr;8760} else {8761Addr = getAddrOfDeclareTargetVar(8762CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,8763EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,8764LlvmPtrTy, GlobalInitializer, VariableLinkage);8765VarName = (Addr) ? Addr->getName() : "";8766}8767VarSize = M.getDataLayout().getPointerSize();8768Linkage = GlobalValue::WeakAnyLinkage;8769}87708771OffloadInfoManager.registerDeviceGlobalVarEntryInfo(VarName, Addr, VarSize,8772Flags, Linkage);8773}87748775/// Loads all the offload entries information from the host IR8776/// metadata.8777void OpenMPIRBuilder::loadOffloadInfoMetadata(Module &M) {8778// If we are in target mode, load the metadata from the host IR. This code has8779// to match the metadata creation in createOffloadEntriesAndInfoMetadata().87808781NamedMDNode *MD = M.getNamedMetadata(ompOffloadInfoName);8782if (!MD)8783return;87848785for (MDNode *MN : MD->operands()) {8786auto &&GetMDInt = [MN](unsigned Idx) {8787auto *V = cast<ConstantAsMetadata>(MN->getOperand(Idx));8788return cast<ConstantInt>(V->getValue())->getZExtValue();8789};87908791auto &&GetMDString = [MN](unsigned Idx) {8792auto *V = cast<MDString>(MN->getOperand(Idx));8793return V->getString();8794};87958796switch (GetMDInt(0)) {8797default:8798llvm_unreachable("Unexpected metadata!");8799break;8800case OffloadEntriesInfoManager::OffloadEntryInfo::8801OffloadingEntryInfoTargetRegion: {8802TargetRegionEntryInfo EntryInfo(/*ParentName=*/GetMDString(3),8803/*DeviceID=*/GetMDInt(1),8804/*FileID=*/GetMDInt(2),8805/*Line=*/GetMDInt(4),8806/*Count=*/GetMDInt(5));8807OffloadInfoManager.initializeTargetRegionEntryInfo(EntryInfo,8808/*Order=*/GetMDInt(6));8809break;8810}8811case OffloadEntriesInfoManager::OffloadEntryInfo::8812OffloadingEntryInfoDeviceGlobalVar:8813OffloadInfoManager.initializeDeviceGlobalVarEntryInfo(8814/*MangledName=*/GetMDString(1),8815static_cast<OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind>(8816/*Flags=*/GetMDInt(2)),8817/*Order=*/GetMDInt(3));8818break;8819}8820}8821}88228823void OpenMPIRBuilder::loadOffloadInfoMetadata(StringRef HostFilePath) {8824if (HostFilePath.empty())8825return;88268827auto Buf = MemoryBuffer::getFile(HostFilePath);8828if (std::error_code Err = Buf.getError()) {8829report_fatal_error(("error opening host file from host file path inside of "8830"OpenMPIRBuilder: " +8831Err.message())8832.c_str());8833}88348835LLVMContext Ctx;8836auto M = expectedToErrorOrAndEmitErrors(8837Ctx, parseBitcodeFile(Buf.get()->getMemBufferRef(), Ctx));8838if (std::error_code Err = M.getError()) {8839report_fatal_error(8840("error parsing host file inside of OpenMPIRBuilder: " + Err.message())8841.c_str());8842}88438844loadOffloadInfoMetadata(*M.get());8845}88468847//===----------------------------------------------------------------------===//8848// OffloadEntriesInfoManager8849//===----------------------------------------------------------------------===//88508851bool OffloadEntriesInfoManager::empty() const {8852return OffloadEntriesTargetRegion.empty() &&8853OffloadEntriesDeviceGlobalVar.empty();8854}88558856unsigned OffloadEntriesInfoManager::getTargetRegionEntryInfoCount(8857const TargetRegionEntryInfo &EntryInfo) const {8858auto It = OffloadEntriesTargetRegionCount.find(8859getTargetRegionEntryCountKey(EntryInfo));8860if (It == OffloadEntriesTargetRegionCount.end())8861return 0;8862return It->second;8863}88648865void OffloadEntriesInfoManager::incrementTargetRegionEntryInfoCount(8866const TargetRegionEntryInfo &EntryInfo) {8867OffloadEntriesTargetRegionCount[getTargetRegionEntryCountKey(EntryInfo)] =8868EntryInfo.Count + 1;8869}88708871/// Initialize target region entry.8872void OffloadEntriesInfoManager::initializeTargetRegionEntryInfo(8873const TargetRegionEntryInfo &EntryInfo, unsigned Order) {8874OffloadEntriesTargetRegion[EntryInfo] =8875OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,8876OMPTargetRegionEntryTargetRegion);8877++OffloadingEntriesNum;8878}88798880void OffloadEntriesInfoManager::registerTargetRegionEntryInfo(8881TargetRegionEntryInfo EntryInfo, Constant *Addr, Constant *ID,8882OMPTargetRegionEntryKind Flags) {8883assert(EntryInfo.Count == 0 && "expected default EntryInfo");88848885// Update the EntryInfo with the next available count for this location.8886EntryInfo.Count = getTargetRegionEntryInfoCount(EntryInfo);88878888// If we are emitting code for a target, the entry is already initialized,8889// only has to be registered.8890if (OMPBuilder->Config.isTargetDevice()) {8891// This could happen if the device compilation is invoked standalone.8892if (!hasTargetRegionEntryInfo(EntryInfo)) {8893return;8894}8895auto &Entry = OffloadEntriesTargetRegion[EntryInfo];8896Entry.setAddress(Addr);8897Entry.setID(ID);8898Entry.setFlags(Flags);8899} else {8900if (Flags == OffloadEntriesInfoManager::OMPTargetRegionEntryTargetRegion &&8901hasTargetRegionEntryInfo(EntryInfo, /*IgnoreAddressId*/ true))8902return;8903assert(!hasTargetRegionEntryInfo(EntryInfo) &&8904"Target region entry already registered!");8905OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);8906OffloadEntriesTargetRegion[EntryInfo] = Entry;8907++OffloadingEntriesNum;8908}8909incrementTargetRegionEntryInfoCount(EntryInfo);8910}89118912bool OffloadEntriesInfoManager::hasTargetRegionEntryInfo(8913TargetRegionEntryInfo EntryInfo, bool IgnoreAddressId) const {89148915// Update the EntryInfo with the next available count for this location.8916EntryInfo.Count = getTargetRegionEntryInfoCount(EntryInfo);89178918auto It = OffloadEntriesTargetRegion.find(EntryInfo);8919if (It == OffloadEntriesTargetRegion.end()) {8920return false;8921}8922// Fail if this entry is already registered.8923if (!IgnoreAddressId && (It->second.getAddress() || It->second.getID()))8924return false;8925return true;8926}89278928void OffloadEntriesInfoManager::actOnTargetRegionEntriesInfo(8929const OffloadTargetRegionEntryInfoActTy &Action) {8930// Scan all target region entries and perform the provided action.8931for (const auto &It : OffloadEntriesTargetRegion) {8932Action(It.first, It.second);8933}8934}89358936void OffloadEntriesInfoManager::initializeDeviceGlobalVarEntryInfo(8937StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order) {8938OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);8939++OffloadingEntriesNum;8940}89418942void OffloadEntriesInfoManager::registerDeviceGlobalVarEntryInfo(8943StringRef VarName, Constant *Addr, int64_t VarSize,8944OMPTargetGlobalVarEntryKind Flags, GlobalValue::LinkageTypes Linkage) {8945if (OMPBuilder->Config.isTargetDevice()) {8946// This could happen if the device compilation is invoked standalone.8947if (!hasDeviceGlobalVarEntryInfo(VarName))8948return;8949auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];8950if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) {8951if (Entry.getVarSize() == 0) {8952Entry.setVarSize(VarSize);8953Entry.setLinkage(Linkage);8954}8955return;8956}8957Entry.setVarSize(VarSize);8958Entry.setLinkage(Linkage);8959Entry.setAddress(Addr);8960} else {8961if (hasDeviceGlobalVarEntryInfo(VarName)) {8962auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];8963assert(Entry.isValid() && Entry.getFlags() == Flags &&8964"Entry not initialized!");8965if (Entry.getVarSize() == 0) {8966Entry.setVarSize(VarSize);8967Entry.setLinkage(Linkage);8968}8969return;8970}8971if (Flags == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryIndirect)8972OffloadEntriesDeviceGlobalVar.try_emplace(VarName, OffloadingEntriesNum,8973Addr, VarSize, Flags, Linkage,8974VarName.str());8975else8976OffloadEntriesDeviceGlobalVar.try_emplace(8977VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage, "");8978++OffloadingEntriesNum;8979}8980}89818982void OffloadEntriesInfoManager::actOnDeviceGlobalVarEntriesInfo(8983const OffloadDeviceGlobalVarEntryInfoActTy &Action) {8984// Scan all target region entries and perform the provided action.8985for (const auto &E : OffloadEntriesDeviceGlobalVar)8986Action(E.getKey(), E.getValue());8987}89888989//===----------------------------------------------------------------------===//8990// CanonicalLoopInfo8991//===----------------------------------------------------------------------===//89928993void CanonicalLoopInfo::collectControlBlocks(8994SmallVectorImpl<BasicBlock *> &BBs) {8995// We only count those BBs as control block for which we do not need to8996// reverse the CFG, i.e. not the loop body which can contain arbitrary control8997// flow. For consistency, this also means we do not add the Body block, which8998// is just the entry to the body code.8999BBs.reserve(BBs.size() + 6);9000BBs.append({getPreheader(), Header, Cond, Latch, Exit, getAfter()});9001}90029003BasicBlock *CanonicalLoopInfo::getPreheader() const {9004assert(isValid() && "Requires a valid canonical loop");9005for (BasicBlock *Pred : predecessors(Header)) {9006if (Pred != Latch)9007return Pred;9008}9009llvm_unreachable("Missing preheader");9010}90119012void CanonicalLoopInfo::setTripCount(Value *TripCount) {9013assert(isValid() && "Requires a valid canonical loop");90149015Instruction *CmpI = &getCond()->front();9016assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");9017CmpI->setOperand(1, TripCount);90189019#ifndef NDEBUG9020assertOK();9021#endif9022}90239024void CanonicalLoopInfo::mapIndVar(9025llvm::function_ref<Value *(Instruction *)> Updater) {9026assert(isValid() && "Requires a valid canonical loop");90279028Instruction *OldIV = getIndVar();90299030// Record all uses excluding those introduced by the updater. Uses by the9031// CanonicalLoopInfo itself to keep track of the number of iterations are9032// excluded.9033SmallVector<Use *> ReplacableUses;9034for (Use &U : OldIV->uses()) {9035auto *User = dyn_cast<Instruction>(U.getUser());9036if (!User)9037continue;9038if (User->getParent() == getCond())9039continue;9040if (User->getParent() == getLatch())9041continue;9042ReplacableUses.push_back(&U);9043}90449045// Run the updater that may introduce new uses9046Value *NewIV = Updater(OldIV);90479048// Replace the old uses with the value returned by the updater.9049for (Use *U : ReplacableUses)9050U->set(NewIV);90519052#ifndef NDEBUG9053assertOK();9054#endif9055}90569057void CanonicalLoopInfo::assertOK() const {9058#ifndef NDEBUG9059// No constraints if this object currently does not describe a loop.9060if (!isValid())9061return;90629063BasicBlock *Preheader = getPreheader();9064BasicBlock *Body = getBody();9065BasicBlock *After = getAfter();90669067// Verify standard control-flow we use for OpenMP loops.9068assert(Preheader);9069assert(isa<BranchInst>(Preheader->getTerminator()) &&9070"Preheader must terminate with unconditional branch");9071assert(Preheader->getSingleSuccessor() == Header &&9072"Preheader must jump to header");90739074assert(Header);9075assert(isa<BranchInst>(Header->getTerminator()) &&9076"Header must terminate with unconditional branch");9077assert(Header->getSingleSuccessor() == Cond &&9078"Header must jump to exiting block");90799080assert(Cond);9081assert(Cond->getSinglePredecessor() == Header &&9082"Exiting block only reachable from header");90839084assert(isa<BranchInst>(Cond->getTerminator()) &&9085"Exiting block must terminate with conditional branch");9086assert(size(successors(Cond)) == 2 &&9087"Exiting block must have two successors");9088assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(0) == Body &&9089"Exiting block's first successor jump to the body");9090assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&9091"Exiting block's second successor must exit the loop");90929093assert(Body);9094assert(Body->getSinglePredecessor() == Cond &&9095"Body only reachable from exiting block");9096assert(!isa<PHINode>(Body->front()));90979098assert(Latch);9099assert(isa<BranchInst>(Latch->getTerminator()) &&9100"Latch must terminate with unconditional branch");9101assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");9102// TODO: To support simple redirecting of the end of the body code that has9103// multiple; introduce another auxiliary basic block like preheader and after.9104assert(Latch->getSinglePredecessor() != nullptr);9105assert(!isa<PHINode>(Latch->front()));91069107assert(Exit);9108assert(isa<BranchInst>(Exit->getTerminator()) &&9109"Exit block must terminate with unconditional branch");9110assert(Exit->getSingleSuccessor() == After &&9111"Exit block must jump to after block");91129113assert(After);9114assert(After->getSinglePredecessor() == Exit &&9115"After block only reachable from exit block");9116assert(After->empty() || !isa<PHINode>(After->front()));91179118Instruction *IndVar = getIndVar();9119assert(IndVar && "Canonical induction variable not found?");9120assert(isa<IntegerType>(IndVar->getType()) &&9121"Induction variable must be an integer");9122assert(cast<PHINode>(IndVar)->getParent() == Header &&9123"Induction variable must be a PHI in the loop header");9124assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == Preheader);9125assert(9126cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))->isZero());9127assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);91289129auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);9130assert(cast<Instruction>(NextIndVar)->getParent() == Latch);9131assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);9132assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);9133assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))9134->isOne());91359136Value *TripCount = getTripCount();9137assert(TripCount && "Loop trip count not found?");9138assert(IndVar->getType() == TripCount->getType() &&9139"Trip count and induction variable must have the same type");91409141auto *CmpI = cast<CmpInst>(&Cond->front());9142assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&9143"Exit condition must be a signed less-than comparison");9144assert(CmpI->getOperand(0) == IndVar &&9145"Exit condition must compare the induction variable");9146assert(CmpI->getOperand(1) == TripCount &&9147"Exit condition must compare with the trip count");9148#endif9149}91509151void CanonicalLoopInfo::invalidate() {9152Header = nullptr;9153Cond = nullptr;9154Latch = nullptr;9155Exit = nullptr;9156}915791589159