27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/TypeSwitch.h"
30#include "llvm/Frontend/OpenMP/OMPConstants.h"
31#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DebugInfoMetadata.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/MDBuilder.h"
37#include "llvm/IR/ReplaceConstant.h"
38#include "llvm/Support/AMDGPUAddrSpace.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/NVPTXAddrSpace.h"
43#include "llvm/Support/SaveAndRestore.h"
44#include "llvm/Support/VirtualFileSystem.h"
45#include "llvm/TargetParser/Triple.h"
46#include "llvm/Transforms/Utils/ModuleUtils.h"
59 omp::PrivateClauseOp privatizer, llvm::Value *var);
66static bool disableVirtualCollapse =
false;
68static llvm::omp::ScheduleKind
69convertToScheduleKind(std::optional<omp::ClauseScheduleKind> schedKind) {
70 if (!schedKind.has_value())
71 return llvm::omp::OMP_SCHEDULE_Default;
72 switch (schedKind.value()) {
73 case omp::ClauseScheduleKind::Static:
74 return llvm::omp::OMP_SCHEDULE_Static;
75 case omp::ClauseScheduleKind::Dynamic:
76 return llvm::omp::OMP_SCHEDULE_Dynamic;
77 case omp::ClauseScheduleKind::Guided:
78 return llvm::omp::OMP_SCHEDULE_Guided;
79 case omp::ClauseScheduleKind::Auto:
80 return llvm::omp::OMP_SCHEDULE_Auto;
81 case omp::ClauseScheduleKind::Runtime:
82 return llvm::omp::OMP_SCHEDULE_Runtime;
83 case omp::ClauseScheduleKind::Distribute:
84 return llvm::omp::OMP_SCHEDULE_Distribute;
86 llvm_unreachable(
"unhandled schedule clause argument");
91class OpenMPAllocStackFrame
96 explicit OpenMPAllocStackFrame(
97 llvm::BasicBlock *allocBlock,
98 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks)
99 : allocBlock(allocBlock), deallocBlocks(deallocBlocks) {}
100 llvm::BasicBlock *allocBlock;
101 llvm::SmallVector<llvm::BasicBlock *> deallocBlocks;
107class OpenMPLoopInfoStackFrame
111 llvm::CanonicalLoopInfo *loopInfo =
nullptr;
121 explicit OpenMPTranslationState(llvm::Module &module) : ompBuilder(module) {
125 llvm::OpenMPIRBuilderConfig config(
132 config.setDefaultTargetAS(module.getDataLayout().getProgramAddressSpace());
133 config.setRuntimeCC(module.getTargetTriple().isSPIRV()
134 ? llvm::CallingConv::SPIR_FUNC
135 : llvm::CallingConv::C);
136 ompBuilder.setConfig(std::move(config));
137 ompBuilder.initialize();
140 ~OpenMPTranslationState()
override {
141 if (!ompBuilder.isFinalized())
142 ompBuilder.finalize();
145 LogicalResult finalize()
override {
146 ompBuilder.finalize();
151 llvm::OpenMPIRBuilder ompBuilder;
161static OpenMPTranslationState &
169static llvm::OpenMPIRBuilder *
175static llvm::CanonicalLoopInfo *
177 auto cli =
mlir.getDefiningOp<omp::NewCliOp>();
178 llvm::CanonicalLoopInfo *
result =
180 assert(
result &&
"attempt to get non-existing loop");
187 auto cli =
mlir.getDefiningOp<omp::NewCliOp>();
194 llvm::CanonicalLoopInfo *
llvm) {
195 assert(
llvm &&
"argument must be non-null");
196 auto cli =
mlir.getDefiningOp<omp::NewCliOp>();
197 llvm::CanonicalLoopInfo *&cur =
199 assert(cur ==
nullptr &&
"attempting to map a loop that is already mapped");
220class PreviouslyReportedError
221 :
public llvm::ErrorInfo<PreviouslyReportedError> {
223 void log(raw_ostream &)
const override {
227 std::error_code convertToErrorCode()
const override {
229 "PreviouslyReportedError doesn't support ECError conversion");
236char PreviouslyReportedError::ID = 0;
247class LinearClauseProcessor {
250 SmallVector<llvm::Type *> linearVarTypes;
251 SmallVector<llvm::Value *> linearSteps;
253 SmallVector<omp::PrivateClauseOp> linearPrivatizers;
254 SmallVector<llvm::Value *> linearOrigVars;
255 SmallVector<llvm::Value *> linearPrivateVars;
257 SmallVector<llvm::Value *> linearStartVals;
258 llvm::BasicBlock *linearFinalizationBB;
259 llvm::BasicBlock *linearExitBB;
260 llvm::BasicBlock *linearLastIterExitBB;
261 std::optional<size_t> linearLoopIVIndex;
264 llvm::Expected<llvm::Value *>
265 getAddress(llvm::IRBuilderBase &builder,
266 LLVM::ModuleTranslation &moduleTranslation,
size_t index,
269 linearPrivatizers[index], var);
273 llvm::Error storeLinearVars(llvm::IRBuilderBase &builder,
274 LLVM::ModuleTranslation &moduleTranslation) {
275 for (
size_t index = 0; index < linearOrigVars.size(); index++) {
276 llvm::Expected<llvm::Value *> from = getAddress(
277 builder, moduleTranslation, index, linearPrivateVars[index]);
279 return from.takeError();
280 llvm::LoadInst *linearVarTemp =
281 builder.CreateLoad(linearVarTypes[index], *from);
282 llvm::Expected<llvm::Value *> to =
283 getAddress(builder, moduleTranslation, index, linearOrigVars[index]);
285 return to.takeError();
286 builder.CreateStore(linearVarTemp, *to);
288 return llvm::Error::success();
293 void registerType(LLVM::ModuleTranslation &moduleTranslation,
294 mlir::Attribute &ty) {
295 linearVarTypes.push_back(moduleTranslation.
convertType(
296 mlir::cast<mlir::TypeAttr>(ty).getValue()));
300 void createLinearVar(llvm::IRBuilderBase &builder,
301 const llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
302 omp::PrivateClauseOp privatizer, llvm::Value *origVar,
303 llvm::Value *privateVar,
int idx) {
304 llvm::IRBuilderBase::InsertPointGuard guard(builder);
305 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
306 linearStartVals.push_back(
307 builder.CreateAlloca(linearVarTypes[idx],
nullptr,
".linear_var"));
308 linearPrivatizers.push_back(privatizer);
309 linearOrigVars.push_back(origVar);
310 linearPrivateVars.push_back(privateVar);
314 inline void initLinearStep(LLVM::ModuleTranslation &moduleTranslation,
315 mlir::Value &linearStep) {
316 linearSteps.push_back(moduleTranslation.
lookupValue(linearStep));
320 llvm::Error initLinearVar(llvm::IRBuilderBase &builder,
321 LLVM::ModuleTranslation &moduleTranslation,
322 llvm::BasicBlock *loopPreHeader) {
323 builder.SetInsertPoint(loopPreHeader->getTerminator());
324 for (
size_t index = 0; index < linearOrigVars.size(); index++) {
325 llvm::Expected<llvm::Value *> orig =
326 getAddress(builder, moduleTranslation, index, linearOrigVars[index]);
328 return orig.takeError();
329 llvm::LoadInst *linearVarLoad =
330 builder.CreateLoad(linearVarTypes[index], *orig);
331 builder.CreateStore(linearVarLoad, linearStartVals[index]);
333 return llvm::Error::success();
337 LogicalResult initLinearIV(omp::SimdOp simdOp) {
338 auto loopOp = cast<omp::LoopNestOp>(simdOp.getWrappedLoop());
340 if (loopOp.getIVs().size() != 1)
348 MutableArrayRef<BlockArgument> linearArgs =
349 cast<omp::BlockArgOpenMPOpInterface>(*simdOp).getLinearBlockArgs();
350 SmallVector<Value> ivValues{loopOp.getIVs().front()};
351 for (Operation *user : loopOp.getIVs().front().getUsers())
352 if (isa<LLVM::SExtOp, LLVM::ZExtOp, LLVM::TruncOp>(user))
353 ivValues.push_back(user->getResult(0));
355 for (Value ivValue : ivValues) {
356 for (Operation *user : ivValue.getUsers()) {
357 auto storeOp = dyn_cast<LLVM::StoreOp>(user);
358 if (!storeOp || storeOp.getValue() != ivValue)
362 Value addr = storeOp.getAddr();
365 if (
auto load = dyn_cast_if_present<LLVM::LoadOp>(def)) {
366 addr =
load.getAddr();
367 }
else if (
auto gep = dyn_cast_if_present<LLVM::GEPOp>(def)) {
368 addr = gep.getBase();
370 auto copy = llvm::find_if(addr.
getUsers(), [&](Operation *user) {
371 auto memcpy = dyn_cast<LLVM::MemcpyOp>(user);
372 return memcpy && memcpy.getDst() == addr &&
373 llvm::is_contained(linearArgs, memcpy.getSrc());
377 addr = cast<LLVM::MemcpyOp>(*copy).getSrc();
380 auto *it = llvm::find(linearArgs, addr);
381 if (it == linearArgs.end())
383 size_t index = std::distance(linearArgs.begin(), it);
384 if (linearLoopIVIndex && *linearLoopIVIndex != index)
385 return simdOp.emitError(
386 "Could not determine the linear variable associated with the "
387 "loop nest induction variable");
388 linearLoopIVIndex = index;
395 llvm::Error updateLinearVar(llvm::IRBuilderBase &builder,
396 LLVM::ModuleTranslation &moduleTranslation,
397 llvm::BasicBlock *loopBody,
398 llvm::Value *loopInductionVar) {
399 builder.SetInsertPoint(loopBody->getTerminator());
400 for (
size_t index = 0; index < linearStartVals.size(); index++) {
401 llvm::Type *linearVarType = linearVarTypes[index];
402 llvm::Value *iv = loopInductionVar;
403 llvm::Value *step = linearSteps[index];
404 llvm::Expected<llvm::Value *>
result = getAddress(
405 builder, moduleTranslation, index, linearPrivateVars[index]);
407 return result.takeError();
409 if (!iv->getType()->isIntegerTy())
410 llvm_unreachable(
"OpenMP loop induction variable must be an integer "
413 if (linearVarType->isIntegerTy()) {
415 iv = builder.CreateSExtOrTrunc(iv, linearVarType);
416 step = builder.CreateSExtOrTrunc(step, linearVarType);
418 llvm::LoadInst *linearVarStart =
419 builder.CreateLoad(linearVarType, linearStartVals[index]);
420 llvm::Value *mulInst = builder.CreateMul(iv, step);
421 llvm::Value *addInst = builder.CreateAdd(linearVarStart, mulInst);
422 builder.CreateStore(addInst, *
result);
423 }
else if (linearVarType->isFloatingPointTy()) {
425 step = builder.CreateSExtOrTrunc(step, iv->getType());
426 llvm::Value *mulInst = builder.CreateMul(iv, step);
428 llvm::LoadInst *linearVarStart =
429 builder.CreateLoad(linearVarType, linearStartVals[index]);
430 llvm::Value *mulFp = builder.CreateSIToFP(mulInst, linearVarType);
431 llvm::Value *addInst = builder.CreateFAdd(linearVarStart, mulFp);
432 builder.CreateStore(addInst, *
result);
435 "Linear variable must be of integer or floating-point type");
438 return llvm::Error::success();
442 llvm::Error updateLinearIV(llvm::IRBuilderBase &builder,
443 LLVM::ModuleTranslation &moduleTranslation) {
444 if (!linearLoopIVIndex)
445 return llvm::Error::success();
446 size_t index = *linearLoopIVIndex;
449 llvm::Type *varType = linearVarTypes[index];
450 if (!varType->isIntegerTy())
451 llvm_unreachable(
"Linear iteration variable must be of integer type");
452 llvm::Expected<llvm::Value *> var =
453 getAddress(builder, moduleTranslation, index, linearPrivateVars[index]);
455 return var.takeError();
456 llvm::Value *step = builder.CreateSExtOrTrunc(linearSteps[index], varType);
457 llvm::Value *val = builder.CreateLoad(varType, *var);
458 llvm::Value *addInst = builder.CreateAdd(val, step);
459 builder.CreateStore(addInst, *var);
460 return llvm::Error::success();
465 void splitLinearFiniBB(llvm::IRBuilderBase &builder,
466 llvm::BasicBlock *loopExit) {
467 linearFinalizationBB = loopExit->splitBasicBlock(
468 loopExit->getTerminator(),
"omp_loop.linear_finalization");
469 linearExitBB = linearFinalizationBB->splitBasicBlock(
470 linearFinalizationBB->getTerminator(),
"omp_loop.linear_exit");
471 linearLastIterExitBB = linearFinalizationBB->splitBasicBlock(
472 linearFinalizationBB->getTerminator(),
"omp_loop.linear_lastiter_exit");
476 llvm::OpenMPIRBuilder::InsertPointOrErrorTy
477 finalizeLinearVar(llvm::IRBuilderBase &builder,
478 LLVM::ModuleTranslation &moduleTranslation,
479 llvm::Value *lastIter) {
481 builder.SetInsertPoint(linearFinalizationBB->getTerminator());
482 llvm::Value *loopLastIterLoad = builder.CreateLoad(
483 llvm::Type::getInt32Ty(builder.getContext()), lastIter);
484 llvm::Value *isLast =
485 builder.CreateCmp(llvm::CmpInst::ICMP_NE, loopLastIterLoad,
486 llvm::ConstantInt::get(
487 llvm::Type::getInt32Ty(builder.getContext()), 0));
489 builder.SetInsertPoint(linearLastIterExitBB->getTerminator());
490 if (llvm::Error err = storeLinearVars(builder, moduleTranslation))
491 return std::move(err);
496 builder.SetInsertPoint(linearFinalizationBB->getTerminator());
497 builder.CreateCondBr(isLast, linearLastIterExitBB, linearExitBB);
498 linearFinalizationBB->getTerminator()->eraseFromParent();
500 builder.SetInsertPoint(linearExitBB->getTerminator());
502 ->createBarrier(builder, llvm::omp::OMPD_barrier);
508 emitStoresForLinearVar(llvm::IRBuilderBase &builder,
509 LLVM::ModuleTranslation &moduleTranslation) {
510 return storeLinearVars(builder, moduleTranslation);
518 SymbolRefAttr symbolName) {
519 omp::PrivateClauseOp privatizer =
522 assert(privatizer &&
"privatizer not found in the symbol table");
533 auto todo = [&op](StringRef clauseName) {
534 return op.
emitError() <<
"not yet implemented: Unhandled clause "
535 << clauseName <<
" in " << op.
getName()
539 auto checkAllocate = [&todo](
auto op, LogicalResult &
result) {
540 if (!op.getAllocateVars().empty() || !op.getAllocatorVars().empty())
541 result = todo(
"allocate");
543 auto checkBare = [&todo](
auto op, LogicalResult &
result) {
544 if (op.getKernelType() == omp::TargetExecMode::bare)
545 result = todo(
"ompx_bare");
547 auto checkDepend = [&todo](
auto op, LogicalResult &
result) {
548 if (!op.getDependVars().empty() || op.getDependKinds() ||
549 !op.getDependIterated().empty() || op.getDependIteratedKinds())
552 auto checkHint = [](
auto op, LogicalResult &) {
556 auto checkInReduction = [&todo](
auto op, LogicalResult &
result) {
557 if (isa<omp::TargetOp, omp::TaskOp, omp::TaskloopContextOp>(
558 op.getOperation())) {
559 if (
auto byrefAttr = op.getInReductionByref()) {
560 for (
bool isByRef : *byrefAttr) {
562 result = todo(
"in_reduction with byref modifier");
567 if (isa<omp::TargetOp>(op.getOperation())) {
568 if (
auto inReductionSyms = op.getInReductionSyms()) {
570 (*inReductionSyms).template getAsRange<SymbolRefAttr>()) {
575 "symbol resolution should be guaranteed by the op verifier");
576 if (decl.getInitializerRegion().front().getNumArguments() != 1) {
577 result = todo(
"in_reduction with two-argument initializer");
580 if (!decl.getCleanupRegion().empty()) {
581 result = todo(
"in_reduction with cleanup region");
587 }
else if (!op.getInReductionVars().empty() || op.getInReductionByref() ||
588 op.getInReductionSyms()) {
589 result = todo(
"in_reduction");
592 auto checkNowait = [&todo](
auto op, LogicalResult &
result) {
596 auto checkOrder = [&todo](
auto op, LogicalResult &
result) {
597 if (op.getOrder() || op.getOrderMod())
600 auto checkPrivate = [&todo](
auto op, LogicalResult &
result) {
601 if (!op.getPrivateVars().empty() || op.getPrivateSyms())
602 result = todo(
"privatization");
604 auto checkReduction = [&todo](
auto op, LogicalResult &
result) {
605 if (isa<omp::TeamsOp>(op))
606 if (!op.getReductionVars().empty() || op.getReductionByref() ||
607 op.getReductionSyms())
608 result = todo(
"reduction");
609 for (
unsigned i = 0, e = op.getNumReductionVars(); i != e; ++i) {
610 omp::ReductionModifier mod = op.getReductionModifier(i);
611 if (mod == omp::ReductionModifier::defaultmod)
615 bool taskModifierSupported =
616 mod == omp::ReductionModifier::task &&
617 isa<omp::ParallelOp, omp::WsloopOp, omp::SectionsOp>(op);
618 if (!taskModifierSupported) {
619 result = todo(
"reduction with modifier");
620 }
else if (
auto byref = op.getReductionByref()) {
622 result = todo(
"task reduction modifier with by-ref reduction");
626 auto checkTaskReductionByref = [&todo](
auto op, LogicalResult &
result) {
627 if (
auto byrefAttr = op.getTaskReductionByref())
628 for (
bool isByRef : *byrefAttr)
630 result = todo(
"task_reduction with byref modifier");
634 auto checkReductionByref = [&todo](
auto op, LogicalResult &
result) {
635 if (
auto byrefAttr = op.getReductionByref())
636 for (
bool isByRef : *byrefAttr)
638 result = todo(
"reduction with byref modifier");
642 auto checkNumTeams = [&todo](
auto op, LogicalResult &
result) {
643 if (op.hasNumTeamsMultiDim())
644 result = todo(
"num_teams with multi-dimensional values");
646 auto checkNumThreads = [&todo](
auto op, LogicalResult &
result) {
647 if (op.hasNumThreadsMultiDim())
648 result = todo(
"num_threads with multi-dimensional values");
651 auto checkThreadLimit = [&todo](
auto op, LogicalResult &
result) {
652 if (op.hasThreadLimitMultiDim())
653 result = todo(
"thread_limit with multi-dimensional values");
655 auto checkMap = [&todo](
auto op, LogicalResult &
result) {
656 if (!op.getMapIterated().empty())
657 result = todo(
"map/motion clause with iterator modifier");
660 auto checkDynGroupprivate = [&todo](
auto op, LogicalResult &
result) {
661 if (op.getDynGroupprivateSize())
662 result = todo(
"dyn_groupprivate");
670 auto checkDeclareMapperMap = [&todo](omp::DeclareMapperInfoOp op,
672 for (
Value iterVal : op.getMapIterated()) {
673 auto itersOp = iterVal.getDefiningOp<omp::IteratorOp>();
674 bool supported = itersOp && itersOp.getLoopLowerBounds().size() == 1;
676 omp::YieldOp yieldOp = itersOp.getYieldOp();
677 supported = yieldOp && yieldOp.getResults().size() == 1;
680 yieldOp.getResults()[0].getDefiningOp<omp::MapInfoOp>();
682 mapInfoOp && !mapInfoOp.getVarPtrPtr() &&
683 mapInfoOp.getMembers().empty() &&
684 mapInfoOp.getMapCaptureType() == omp::VariableCaptureKind::ByRef;
688 result = todo(
"map/motion clause with iterator modifier");
696 .Case([&](omp::DistributeOp op) {
697 checkAllocate(op,
result);
700 .Case([&](omp::SectionsOp op) {
701 checkAllocate(op,
result);
703 checkReduction(op,
result);
705 .Case([&](omp::ScopeOp op) { checkReduction(op,
result); })
706 .Case([&](omp::SingleOp op) {
707 checkAllocate(op,
result);
710 .Case([&](omp::TeamsOp op) {
711 checkAllocate(op,
result);
713 checkNumTeams(op,
result);
714 checkThreadLimit(op,
result);
715 checkDynGroupprivate(op,
result);
717 .Case([&](omp::TaskOp op) {
718 checkAllocate(op,
result);
719 checkInReduction(op,
result);
721 .Case([&](omp::TaskgroupOp op) {
722 checkAllocate(op,
result);
723 checkTaskReductionByref(op,
result);
725 .Case([&](omp::DispatchOp op) {
734 .Case([&](omp::TaskloopContextOp op) {
735 checkAllocate(op,
result);
736 checkInReduction(op,
result);
737 checkReduction(op,
result);
738 checkReductionByref(op,
result);
740 .Case([&](omp::WsloopOp op) {
741 checkAllocate(op,
result);
743 checkReduction(op,
result);
745 .Case([&](omp::ParallelOp op) {
746 checkReduction(op,
result);
747 checkNumThreads(op,
result);
749 .Case([&](omp::SimdOp op) { checkReduction(op,
result); })
750 .Case<omp::AtomicReadOp, omp::AtomicWriteOp, omp::AtomicUpdateOp,
751 omp::AtomicCaptureOp>([&](
auto op) { checkHint(op,
result); })
752 .Case([&](omp::AtomicCompareOp op) {
758 auto structTy = dyn_cast<LLVM::LLVMStructType>(argType);
764 result = todo(
"compare for complex types wider than 128 bits");
766 .Case<omp::TargetEnterDataOp, omp::TargetExitDataOp>([&](
auto op) {
770 .Case([&](omp::TargetUpdateOp op) {
774 .Case([&](omp::TargetOp op) {
775 checkAllocate(op,
result);
777 checkInReduction(op,
result);
779 checkThreadLimit(op,
result);
781 .Case([&](omp::TargetDataOp op) { checkMap(op,
result); })
782 .Case([&](omp::DeclareMapperInfoOp op) {
783 checkDeclareMapperMap(op,
result);
795 llvm::handleAllErrors(
797 [&](
const PreviouslyReportedError &) {
result = failure(); },
798 [&](
const llvm::ErrorInfoBase &err) {
821 llvm::OpenMPIRBuilder::InsertPointTy allocInsertPoint;
824 [&](OpenMPAllocStackFrame &frame) {
825 allocInsertPoint = frame.allocBlock->getFirstInsertionPt();
826 deallocInsertPoints = frame.deallocBlocks;
834 allocInsertPoint.getNodeParent()->getParent() ==
835 builder.GetInsertBlock()->getParent()) {
837 deallocBlocks->insert(deallocBlocks->end(), deallocInsertPoints.begin(),
838 deallocInsertPoints.end());
839 return allocInsertPoint;
849 if (builder.GetInsertBlock() ==
850 &builder.GetInsertBlock()->getParent()->getEntryBlock()) {
851 assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end() &&
852 "Assuming end of basic block");
853 llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(
854 builder.getContext(),
"entry", builder.GetInsertBlock()->getParent(),
855 builder.GetInsertBlock()->getNextNode());
856 builder.CreateBr(entryBB);
857 builder.SetInsertPoint(entryBB);
863 for (llvm::BasicBlock &block : *builder.GetInsertBlock()->getParent()) {
867 llvm::Instruction *terminator = block.getTerminatorOrNull();
868 if (isa_and_present<llvm::ReturnInst>(terminator))
869 deallocBlocks->emplace_back(&block);
873 llvm::BasicBlock &funcEntryBlock =
874 builder.GetInsertBlock()->getParent()->getEntryBlock();
875 return funcEntryBlock.getFirstInsertionPt();
881static llvm::CanonicalLoopInfo *
883 llvm::CanonicalLoopInfo *loopInfo =
nullptr;
884 moduleTranslation.
stackWalk<OpenMPLoopInfoStackFrame>(
885 [&](OpenMPLoopInfoStackFrame &frame) {
886 loopInfo = frame.loopInfo;
898 Region ®ion, StringRef blockName, llvm::IRBuilderBase &builder,
901 bool isLoopWrapper = isa<omp::LoopWrapperInterface>(region.
getParentOp());
903 llvm::BasicBlock *continuationBlock =
904 splitBB(builder,
true,
"omp.region.cont");
905 llvm::BasicBlock *sourceBlock = builder.GetInsertBlock();
907 llvm::LLVMContext &llvmContext = builder.getContext();
908 for (
Block &bb : region) {
909 llvm::BasicBlock *llvmBB = llvm::BasicBlock::Create(
910 llvmContext, blockName, builder.GetInsertBlock()->getParent(),
912 moduleTranslation.
mapBlock(&bb, llvmBB);
915 llvm::Instruction *sourceTerminator = sourceBlock->getTerminator();
922 unsigned numYields = 0;
924 if (!isLoopWrapper) {
925 bool operandsProcessed =
false;
927 if (omp::YieldOp yield = dyn_cast<omp::YieldOp>(bb.getTerminator())) {
928 if (!operandsProcessed) {
929 for (
unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) {
930 continuationBlockPHITypes.push_back(
931 moduleTranslation.
convertType(yield->getOperand(i).getType()));
933 operandsProcessed =
true;
935 assert(continuationBlockPHITypes.size() == yield->getNumOperands() &&
936 "mismatching number of values yielded from the region");
937 for (
unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) {
938 llvm::Type *operandType =
939 moduleTranslation.
convertType(yield->getOperand(i).getType());
941 assert(continuationBlockPHITypes[i] == operandType &&
942 "values of mismatching types yielded from the region");
952 if (!continuationBlockPHITypes.empty())
954 continuationBlockPHIs &&
955 "expected continuation block PHIs if converted regions yield values");
956 if (continuationBlockPHIs) {
957 llvm::IRBuilderBase::InsertPointGuard guard(builder);
958 continuationBlockPHIs->reserve(continuationBlockPHITypes.size());
959 builder.SetInsertPoint(continuationBlock->begin());
960 for (llvm::Type *ty : continuationBlockPHITypes)
961 continuationBlockPHIs->push_back(builder.CreatePHI(ty, numYields));
967 for (
Block *bb : blocks) {
968 llvm::BasicBlock *llvmBB = moduleTranslation.
lookupBlock(bb);
971 if (bb->isEntryBlock()) {
972 assert(sourceTerminator->getNumSuccessors() == 1 &&
973 "provided entry block has multiple successors");
974 assert(sourceTerminator->getSuccessor(0) == continuationBlock &&
975 "ContinuationBlock is not the successor of the entry block");
976 sourceTerminator->setSuccessor(0, llvmBB);
979 llvm::IRBuilderBase::InsertPointGuard guard(builder);
981 moduleTranslation.
convertBlock(*bb, bb->isEntryBlock(), builder)))
982 return llvm::make_error<PreviouslyReportedError>();
987 builder.CreateBr(continuationBlock);
998 Operation *terminator = bb->getTerminator();
999 if (isa<omp::TerminatorOp, omp::YieldOp>(terminator)) {
1000 builder.CreateBr(continuationBlock);
1002 for (
unsigned i = 0, e = terminator->
getNumOperands(); i < e; ++i)
1003 (*continuationBlockPHIs)[i]->addIncoming(
1017 return continuationBlock;
1023 case omp::ClauseProcBindKind::Close:
1024 return llvm::omp::ProcBindKind::OMP_PROC_BIND_close;
1025 case omp::ClauseProcBindKind::Master:
1026 return llvm::omp::ProcBindKind::OMP_PROC_BIND_master;
1027 case omp::ClauseProcBindKind::Primary:
1028 return llvm::omp::ProcBindKind::OMP_PROC_BIND_primary;
1029 case omp::ClauseProcBindKind::Spread:
1030 return llvm::omp::ProcBindKind::OMP_PROC_BIND_spread;
1032 llvm_unreachable(
"Unknown ClauseProcBindKind kind");
1039 auto dispatchOp = cast<omp::DispatchOp>(opInst);
1044 auto ®ion = dispatchOp.getRegion();
1049 builder.SetInsertPoint(*
result);
1057 auto maskedOp = cast<omp::MaskedOp>(opInst);
1058 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1063 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
1066 auto ®ion = maskedOp.getRegion();
1067 builder.restoreIP(codeGenIP);
1075 auto finiCB = [&](InsertPointTy codeGenIP) {
return llvm::Error::success(); };
1077 llvm::Value *filterVal =
nullptr;
1078 if (
auto filterVar = maskedOp.getFilteredThreadId()) {
1079 filterVal = moduleTranslation.
lookupValue(filterVar);
1081 llvm::LLVMContext &llvmContext = builder.getContext();
1083 llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext), 0);
1085 assert(filterVal !=
nullptr);
1086 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1087 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
1089 ->createMasked(ompLoc, bodyGenCB, finiCB, filterVal);
1094 builder.restoreIP(*afterIP);
1102 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1103 auto masterOp = cast<omp::MasterOp>(opInst);
1108 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
1111 auto ®ion = masterOp.getRegion();
1112 builder.restoreIP(codeGenIP);
1120 auto finiCB = [&](InsertPointTy codeGenIP) {
return llvm::Error::success(); };
1122 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1123 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
1125 ->createMaster(ompLoc, bodyGenCB, finiCB);
1130 builder.restoreIP(*afterIP);
1138 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1139 auto criticalOp = cast<omp::CriticalOp>(opInst);
1144 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
1147 auto ®ion = cast<omp::CriticalOp>(opInst).getRegion();
1148 builder.restoreIP(codeGenIP);
1156 auto finiCB = [&](InsertPointTy codeGenIP) {
return llvm::Error::success(); };
1158 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1159 llvm::LLVMContext &llvmContext = moduleTranslation.
getLLVMContext();
1160 llvm::Constant *hint =
nullptr;
1163 if (criticalOp.getNameAttr()) {
1166 auto symbolRef = cast<SymbolRefAttr>(criticalOp.getNameAttr());
1167 auto criticalDeclareOp =
1171 llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext),
1172 static_cast<int>(criticalDeclareOp.getHint()));
1174 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
1176 ->createCritical(ompLoc, bodyGenCB, finiCB,
1177 criticalOp.getName().value_or(
""), hint);
1182 builder.restoreIP(*afterIP);
1189struct PrivateVarsInfo {
1192 BlockArgument blockArg;
1193 mlir::Value mlirVar;
1194 omp::PrivateClauseOp privatizer;
1195 llvm::Value *llvmVar =
nullptr;
1198 struct AllocatorInfo {
1199 llvm::Value *allocatedPtr;
1200 llvm::Value *allocator;
1203 template <
typename OP>
1204 PrivateVarsInfo(OP op) {
1205 MutableArrayRef<BlockArgument> blockArgs =
1206 cast<omp::BlockArgOpenMPOpInterface>(*op).getPrivateBlockArgs();
1207 SmallVector<omp::PrivateClauseOp> privatizers;
1209 collectPrivatizationDecls<OP>(op, op.getPrivateSyms(), privatizers);
1210 collectPrivatizationInfo(blockArgs, op.getPrivateVars(), privatizers);
1211 numPrivateVars = vars.size();
1216 template <
typename OP>
1217 void addLinearVars(OP op) {
1218 MutableArrayRef<BlockArgument> blockArgs =
1219 cast<omp::BlockArgOpenMPOpInterface>(*op).getLinearBlockArgs();
1220 SmallVector<omp::PrivateClauseOp> privatizers;
1222 collectPrivatizationDecls<OP>(op, op.getLinearSyms(), privatizers);
1223 collectPrivatizationInfo(blockArgs, op.getLinearVars(), privatizers);
1227 size_t numPrivateVars = 0;
1228 SmallVector<VarInfo> vars;
1229 llvm::DenseMap<Value, llvm::Value *> convertedAllocators;
1230 SmallVector<AllocatorInfo> allocatorPrivates;
1232 SmallVector<llvm::Value *> getLlvmVars()
const {
1233 return llvm::map_to_vector(vars,
1234 [](
const VarInfo &v) {
return v.llvmVar; });
1239 void collectPrivatizationInfo(
1240 MutableArrayRef<BlockArgument> blockArgs, OperandRange privateVars,
1241 const SmallVectorImpl<omp::PrivateClauseOp> &privatizers) {
1242 vars.reserve(vars.size() + blockArgs.size());
1243 for (
auto [blockArg, mlirVar, privatizer] :
1244 llvm::zip_equal(blockArgs, privateVars, privatizers))
1245 vars.push_back({blockArg, mlirVar, privatizer});
1251 void collectPrivatizationDecls(
1252 OP op, std::optional<ArrayAttr> symsAttr,
1253 SmallVectorImpl<omp::PrivateClauseOp> &privatizers) {
1257 privatizers.reserve(privatizers.size() + symsAttr->size());
1259 symsAttr->getAsRange<SymbolRefAttr>(), std::back_inserter(privatizers),
1260 [&](SymbolRefAttr symbolRef) { return findPrivatizer(op, symbolRef); });
1266template <
typename T>
1270 std::optional<ArrayAttr> attr = op.getReductionSyms();
1274 reductions.reserve(reductions.size() + op.getNumReductionVars());
1275 for (
auto symbolRef : attr->getAsRange<SymbolRefAttr>()) {
1276 reductions.push_back(
1291 Operation *contextOp, std::optional<ArrayAttr> syms, StringRef opName,
1295 out.reserve(out.size() + syms->size());
1296 for (
auto sym : syms->getAsRange<SymbolRefAttr>()) {
1301 <<
"failed to resolve " << clauseName
1302 <<
" declare_reduction symbol " << sym.getRootReference() <<
" in "
1304 if (decl.getInitializerRegion().front().getNumArguments() != 1)
1306 <<
"not yet implemented: " << clauseName
1307 <<
" with two-argument initializer in " << opName;
1308 if (!decl.getCleanupRegion().empty())
1309 return contextOp->
emitError() <<
"not yet implemented: " << clauseName
1310 <<
" with cleanup region in " << opName;
1311 if (decl.getReductionRegion().empty())
1313 << clauseName <<
" declare_reduction is missing a combiner region";
1314 out.push_back(decl);
1325 Region ®ion, StringRef blockName, llvm::IRBuilderBase &builder,
1334 llvm::BasicBlock *insertBlock = builder.GetInsertBlock();
1335 llvm::Instruction *potentialTerminator =
1336 insertBlock->empty() ?
nullptr : &insertBlock->back();
1338 if (potentialTerminator && potentialTerminator->isTerminator()) {
1339 assert(builder.GetInsertPoint() == potentialTerminator->getIterator() &&
1340 "Insertion point should be the terminator");
1341 potentialTerminator->removeFromParent();
1343 builder.SetInsertPoint(insertBlock);
1349 llvm::DebugLoc loc = builder.getCurrentDebugLocation();
1351 region.
front(),
true, builder)))
1353 builder.SetCurrentDebugLocation(loc);
1356 if (continuationBlockArgs)
1358 *continuationBlockArgs,
1365 if (potentialTerminator && potentialTerminator->isTerminator()) {
1366 llvm::BasicBlock *block = builder.GetInsertBlock();
1367 if (block->empty()) {
1373 potentialTerminator->insertInto(block, block->begin());
1375 potentialTerminator->insertAfter(&block->back());
1389 if (continuationBlockArgs)
1390 llvm::append_range(*continuationBlockArgs, phis);
1391 builder.SetInsertPoint((*continuationBlock)->getFirstInsertionPt());
1398using OwningReductionGen =
1399 std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
1400 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *,
1402using OwningAtomicReductionGen =
1403 std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
1404 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Type *, llvm::Value *,
1406using OwningDataPtrPtrReductionGen =
1407 std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
1408 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *&)>;
1414static OwningReductionGen
1420 OwningReductionGen gen =
1421 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint,
1422 llvm::Value *lhs, llvm::Value *rhs,
1423 llvm::Value *&
result)
mutable
1424 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
1425 moduleTranslation.
mapValue(decl.getReductionLhsArg(), lhs);
1426 moduleTranslation.
mapValue(decl.getReductionRhsArg(), rhs);
1427 builder.restoreIP(insertPoint);
1430 "omp.reduction.nonatomic.body", builder,
1431 moduleTranslation, &phis)))
1432 return llvm::createStringError(
1433 "failed to inline `combiner` region of `omp.declare_reduction`");
1434 result = llvm::getSingleElement(phis);
1435 return builder.saveIP();
1444static OwningAtomicReductionGen
1446 llvm::IRBuilderBase &builder,
1448 if (decl.getAtomicReductionRegion().empty())
1449 return OwningAtomicReductionGen();
1455 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint, llvm::Type *,
1456 llvm::Value *lhs, llvm::Value *rhs)
mutable
1457 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
1458 moduleTranslation.
mapValue(decl.getAtomicReductionLhsArg(), lhs);
1459 moduleTranslation.
mapValue(decl.getAtomicReductionRhsArg(), rhs);
1460 builder.restoreIP(insertPoint);
1463 "omp.reduction.atomic.body", builder,
1464 moduleTranslation, &phis)))
1465 return llvm::createStringError(
1466 "failed to inline `atomic` region of `omp.declare_reduction`");
1467 assert(phis.empty());
1468 return builder.saveIP();
1477static OwningDataPtrPtrReductionGen
1480 if (!isByRef || decl.getDataPtrPtrRegion().empty())
1481 return OwningDataPtrPtrReductionGen();
1483 OwningDataPtrPtrReductionGen refDataPtrGen =
1484 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint,
1485 llvm::Value *byRefVal, llvm::Value *&
result)
mutable
1486 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
1487 moduleTranslation.
mapValue(decl.getDataPtrPtrRegionArg(), byRefVal);
1488 builder.restoreIP(insertPoint);
1491 "omp.data_ptr_ptr.body", builder,
1492 moduleTranslation, &phis)))
1493 return llvm::createStringError(
1494 "failed to inline `data_ptr_ptr` region of `omp.declare_reduction`");
1495 result = llvm::getSingleElement(phis);
1496 return builder.saveIP();
1499 return refDataPtrGen;
1506 auto orderedOp = cast<omp::OrderedOp>(opInst);
1511 omp::ClauseDepend dependType = *orderedOp.getDoacrossDependType();
1512 bool isDependSource = dependType == omp::ClauseDepend::dependsource;
1513 unsigned numLoops = *orderedOp.getDoacrossNumLoops();
1515 moduleTranslation.
lookupValues(orderedOp.getDoacrossDependVars());
1517 size_t indexVecValues = 0;
1518 while (indexVecValues < vecValues.size()) {
1520 storeValues.reserve(numLoops);
1521 for (
unsigned i = 0; i < numLoops; i++) {
1522 storeValues.push_back(vecValues[indexVecValues]);
1525 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
1527 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1529 ->createOrderedDepend(ompLoc, allocaIP, numLoops,
1530 storeValues,
".cnt.addr",
1541 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1542 auto orderedRegionOp = cast<omp::OrderedRegionOp>(opInst);
1547 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
1550 auto ®ion = cast<omp::OrderedRegionOp>(opInst).getRegion();
1551 builder.restoreIP(codeGenIP);
1559 auto finiCB = [&](InsertPointTy codeGenIP) {
return llvm::Error::success(); };
1561 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1562 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
1564 ->createOrderedThreadsSimd(ompLoc, bodyGenCB, finiCB,
1565 !orderedRegionOp.getParLevelSimd());
1570 builder.restoreIP(*afterIP);
1578struct ReductionVarsInfo {
1581 BlockArgument blockArg;
1582 mlir::Value mlirVar;
1583 omp::DeclareReductionOp decl;
1585 llvm::Value *privateVar =
nullptr;
1586 llvm::Value *storage =
nullptr;
1590 struct DeferredStore {
1591 DeferredStore(llvm::Value *value, llvm::Value *address)
1592 : value(value), address(address) {}
1595 llvm::Value *address;
1598 template <
typename OP>
1599 ReductionVarsInfo(OP op) {
1600 MutableArrayRef<BlockArgument> blockArgs =
1601 cast<omp::BlockArgOpenMPOpInterface>(*op).getReductionBlockArgs();
1602 SmallVector<omp::DeclareReductionOp> decls;
1604 std::optional<ArrayRef<bool>> attr = op.getReductionByref();
1605 ArrayRef<bool> byRefs = attr ? *attr : ArrayRef<bool>();
1607 vars.reserve(blockArgs.size());
1608 for (
auto [blockArg, mlirVar, decl, byRef] :
1609 llvm::zip_equal(blockArgs, op.getReductionVars(), decls, byRefs))
1610 vars.push_back({blockArg, mlirVar, decl, byRef});
1613 SmallVector<VarInfo> vars;
1615 SmallVector<DeferredStore> deferredStores;
1617 size_t size()
const {
return vars.size(); }
1619 SmallVector<omp::DeclareReductionOp> getReductionDecls()
const {
1620 return llvm::map_to_vector(vars, [](
const VarInfo &v) {
return v.decl; });
1622 SmallVector<llvm::Value *> getPrivateReductionVariables()
const {
1623 return llvm::map_to_vector(vars,
1624 [](
const VarInfo &v) {
return v.privateVar; });
1626 SmallVector<bool> getIsByRef()
const {
1627 return llvm::map_to_vector(vars, [](
const VarInfo &v) {
return v.byRef; });
1638 const llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
1639 ReductionVarsInfo &redInfo) {
1640 llvm::IRBuilderBase::InsertPointGuard guard(builder);
1641 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
1647 redInfo.deferredStores.reserve(redInfo.size());
1649 for (ReductionVarsInfo::VarInfo &var : redInfo.vars) {
1650 Region &allocRegion = var.decl.getAllocRegion();
1652 if (allocRegion.
empty())
1657 builder, moduleTranslation, &phis)))
1659 "failed to inline `alloc` region of `omp.declare_reduction`");
1661 assert(phis.size() == 1 &&
"expected one allocation to be yielded");
1662 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
1666 llvm::Type *ptrTy = builder.getPtrTy();
1667 llvm::Type *varTy = moduleTranslation.
convertType(var.decl.getType());
1668 llvm::Value *llvmVar;
1669 if (useDeviceSharedMem) {
1670 llvmVar = ompBuilder->createOMPAllocShared(builder, varTy);
1672 llvmVar = builder.CreateAlloca(varTy);
1673 llvmVar = builder.CreatePointerBitCastOrAddrSpaceCast(llvmVar, ptrTy);
1676 llvm::Value *castPhi =
1677 builder.CreatePointerBitCastOrAddrSpaceCast(phis[0], ptrTy);
1679 redInfo.deferredStores.emplace_back(castPhi, llvmVar);
1681 var.privateVar = llvmVar;
1682 moduleTranslation.
mapValue(var.blockArg, castPhi);
1683 var.storage = castPhi;
1685 assert(allocRegion.
empty() &&
1686 "allocaction is implicit for by-val reduction");
1688 llvm::Type *ptrTy = builder.getPtrTy();
1689 llvm::Type *varTy = moduleTranslation.
convertType(var.decl.getType());
1690 llvm::Value *llvmVar;
1691 if (useDeviceSharedMem) {
1692 llvmVar = ompBuilder->createOMPAllocShared(builder, varTy);
1694 llvmVar = builder.CreateAlloca(varTy);
1695 llvmVar = builder.CreatePointerBitCastOrAddrSpaceCast(llvmVar, ptrTy);
1698 var.privateVar = llvmVar;
1699 moduleTranslation.
mapValue(var.blockArg, llvmVar);
1700 var.storage = llvmVar;
1710 llvm::IRBuilderBase &builder,
1711 const ReductionVarsInfo::VarInfo &redVarInfo) {
1713 omp::DeclareReductionOp reduction = redVarInfo.decl;
1714 Region &initializerRegion = reduction.getInitializerRegion();
1718 llvm::Value *llvmSource = moduleTranslation.
lookupValue(mlirSource);
1719 llvm::Value *origVal = llvmSource;
1721 if (!isa<LLVM::LLVMPointerType>(
1722 reduction.getInitializerMoldArg().getType()) &&
1723 isa<LLVM::LLVMPointerType>(mlirSource.
getType())) {
1726 reduction.getInitializerMoldArg().getType()),
1727 llvmSource,
"omp_orig");
1729 moduleTranslation.
mapValue(reduction.getInitializerMoldArg(), origVal);
1732 moduleTranslation.
mapValue(reduction.getInitializerAllocArg(),
1733 redVarInfo.storage);
1738 llvm::BasicBlock *block =
nullptr) {
1739 if (block ==
nullptr)
1740 block = builder.GetInsertBlock();
1742 if (!block->hasTerminator())
1743 builder.SetInsertPoint(block);
1745 builder.SetInsertPoint(block->getTerminator());
1754initReductionVars(
Operation &op, llvm::IRBuilderBase &builder,
1756 llvm::BasicBlock *latestAllocaBlock,
1757 ReductionVarsInfo &redInfo) {
1758 if (redInfo.size() == 0)
1764 llvm::BasicBlock *initBlock = splitBB(builder,
true,
"omp.reduction.init");
1767 llvm::IRBuilderBase::InsertPointGuard guard(builder);
1768 auto allocaIP = latestAllocaBlock->getTerminator()->getIterator();
1769 builder.restoreIP(allocaIP);
1771 for (
auto [var, byRefVar] : llvm::zip_equal(redInfo.vars, byRefVars)) {
1773 if (!var.decl.getAllocRegion().empty())
1779 llvm::Type *varTy = moduleTranslation.
convertType(var.decl.getType());
1780 if (useDeviceSharedMem)
1781 byRefVar = ompBuilder->createOMPAllocShared(builder, varTy);
1783 byRefVar = builder.CreateAlloca(varTy);
1792 for (
auto [data, addr] : redInfo.deferredStores)
1793 builder.CreateStore(data, addr);
1798 for (
auto [var, byRefVar] : llvm::zip_equal(redInfo.vars, byRefVars)) {
1810 "omp.reduction.neutral", builder,
1811 moduleTranslation, &phis)))
1814 assert(phis.size() == 1 &&
"expected one value to be yielded from the "
1815 "reduction neutral element declaration region");
1820 if (!var.decl.getAllocRegion().empty())
1829 builder.CreateStore(phis[0], byRefVar);
1830 var.privateVar = byRefVar;
1832 moduleTranslation.
mapValue(var.blockArg, phis[0]);
1833 var.storage = phis[0];
1836 builder.CreateStore(phis[0], var.privateVar);
1843 moduleTranslation.
forgetMapping(var.decl.getInitializerRegion());
1850static void collectReductionInfo(
1852 ReductionVarsInfo &redInfo,
1857 unsigned numReductions = redInfo.size();
1859 for (ReductionVarsInfo::VarInfo &var : redInfo.vars) {
1860 owningReductionGens.push_back(
1862 owningAtomicReductionGens.push_back(
1864 owningDataPtrPtrReductionGens.push_back(
1869 reductionInfos.reserve(numReductions);
1871 redInfo.vars, owningReductionGens, owningAtomicReductionGens,
1872 owningDataPtrPtrReductionGens)) {
1873 llvm::OpenMPIRBuilder::ReductionGenAtomicCBTy
atomicGen =
nullptr;
1876 llvm::Value *variable = moduleTranslation.
lookupValue(var.mlirVar);
1879 if (
auto alloca = mlir::dyn_cast<LLVM::AllocaOp>(op)) {
1880 allocatedType = alloca.getElemType();
1887 reductionInfos.push_back(
1888 {moduleTranslation.
convertType(var.decl.getType()), variable,
1890 llvm::OpenMPIRBuilder::EvalKind::Scalar,
redGen,
1892 allocatedType ? moduleTranslation.
convertType(allocatedType) :
nullptr,
1893 var.decl.getByrefElementType()
1894 ? moduleTranslation.
convertType(*var.decl.getByrefElementType())
1904 llvm::IRBuilderBase &builder, StringRef regionName,
1905 bool shouldLoadCleanupRegionArg =
true) {
1906 for (
auto [i, cleanupRegion] : llvm::enumerate(cleanupRegions)) {
1907 if (cleanupRegion->empty())
1913 llvm::Instruction *potentialTerminator =
1914 builder.GetInsertBlock()->empty() ?
nullptr
1915 : &builder.GetInsertBlock()->back();
1916 if (potentialTerminator && potentialTerminator->isTerminator())
1917 builder.SetInsertPoint(potentialTerminator);
1918 llvm::Value *privateVarValue =
1919 shouldLoadCleanupRegionArg
1920 ? builder.CreateLoad(
1922 privateVariables[i])
1923 : privateVariables[i];
1928 moduleTranslation)))
1942 llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
1943 ReductionVarsInfo &redInfo,
bool isNowait =
false,
1944 bool isTeamsReduction =
false) {
1946 if (redInfo.size() == 0)
1958 collectReductionInfo(builder, moduleTranslation, redInfo, owningReductionGens,
1959 owningAtomicReductionGens,
1960 owningReductionGenRefDataPtrGens, reductionInfos);
1965 llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
1966 builder.SetInsertPoint(tempTerminator);
1967 llvm::DebugLoc reductionLoc = builder.getCurrentDebugLocation();
1968 llvm::OpenMPIRBuilder::InsertPointOrErrorTy contInsertPoint =
1969 ompBuilder->createReductions(builder, allocaIP, reductionInfos,
1970 redInfo.getIsByRef(), isNowait,
1976 if (!contInsertPoint->isValid())
1977 return op.
emitOpError() <<
"failed to convert reductions";
1979 llvm::OpenMPIRBuilder::InsertPointTy afterIP = *contInsertPoint;
1980 if (!isTeamsReduction && !isNowait) {
1981 llvm::OpenMPIRBuilder::InsertPointOrErrorTy barrierIP =
1982 ompBuilder->createBarrier({*contInsertPoint, reductionLoc},
1983 llvm::omp::OMPD_for);
1987 afterIP = *barrierIP;
1990 tempTerminator->eraseFromParent();
1991 builder.restoreIP(afterIP);
1995 llvm::transform(redInfo.vars, std::back_inserter(reductionRegions),
1996 [](ReductionVarsInfo::VarInfo &var) {
1997 return &var.decl.getCleanupRegion();
2000 reductionRegions, redInfo.getPrivateReductionVariables(),
2001 moduleTranslation, builder,
"omp.reduction.cleanup");
2004 if (useDeviceSharedMem) {
2005 for (ReductionVarsInfo::VarInfo &var : redInfo.vars)
2006 ompBuilder->createOMPFreeShared(
2007 builder, var.privateVar,
2008 moduleTranslation.
convertType(var.decl.getType()));
2018 llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
2019 ReductionVarsInfo &redInfo) {
2020 if (redInfo.size() == 0)
2027 return initReductionVars(op, builder, moduleTranslation,
2028 allocaIP.getNodeParent(), redInfo);
2042 if (mappedPrivateVars ==
nullptr || !mappedPrivateVars->contains(privateVar))
2045 Value blockArg = (*mappedPrivateVars)[privateVar];
2048 assert(isa<LLVM::LLVMPointerType>(blockArgType) &&
2049 "A block argument corresponding to a mapped var should have "
2052 if (privVarType == blockArgType)
2059 if (!isa<LLVM::LLVMPointerType>(privVarType))
2060 return builder.CreateLoad(moduleTranslation.
convertType(privVarType),
2077 llvm::Type *regionArgType =
2079 if (regionArgType->isPointerTy() || !value->getType()->isPointerTy())
2082 return builder.CreateLoad(regionArgType, value);
2089 omp::PrivateClauseOp privatizer, llvm::Value *var) {
2090 Region ®ion = privatizer.getDataAddressRegion();
2099 builder, moduleTranslation, &address)))
2100 return llvm::make_error<PreviouslyReportedError>();
2102 return address.front();
2112 omp::PrivateClauseOp &privDecl, llvm::Value *nonPrivateVar,
2114 llvm::BasicBlock *privInitBlock,
2116 Region &initRegion = privDecl.getInitRegion();
2117 if (initRegion.
empty())
2118 return llvmPrivateVar;
2120 assert(nonPrivateVar);
2121 moduleTranslation.
mapValue(privDecl.getInitMoldArg(), nonPrivateVar);
2122 moduleTranslation.
mapValue(privDecl.getInitPrivateArg(), llvmPrivateVar);
2127 moduleTranslation, &phis)))
2128 return llvm::createStringError(
2129 "failed to inline `init` region of `omp.private`");
2131 assert(phis.size() == 1 &&
"expected one allocation to be yielded");
2148 llvm::Value *llvmPrivateVar, llvm::BasicBlock *privInitBlock,
2151 builder, moduleTranslation, privDecl,
2154 blockArg, llvmPrivateVar, privInitBlock, mappedPrivateVars);
2160 PrivateVarsInfo &privateVarsInfo,
2162 if (privateVarsInfo.vars.empty())
2163 return llvm::Error::success();
2165 llvm::BasicBlock *privInitBlock = splitBB(builder,
true,
"omp.private.init");
2168 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
2170 builder, moduleTranslation, var.privatizer, var.mlirVar, var.blockArg,
2171 var.llvmVar, privInitBlock, mappedPrivateVars);
2174 return privVarOrErr.takeError();
2176 var.llvmVar = privVarOrErr.get();
2177 moduleTranslation.
mapValue(var.blockArg, var.llvmVar);
2182 return llvm::Error::success();
2187 llvm::IRBuilderBase &builder,
2189 PrivateVarsInfo &privateVarsInfo) {
2190 for (
Value allocatorVar : allocatorVars) {
2191 if (privateVarsInfo.convertedAllocators.contains(allocatorVar))
2194 llvm::Value *allocator = moduleTranslation.
lookupValue(allocatorVar);
2196 return op.
emitError(
"failed to translate OpenMP allocator operand");
2197 if (allocator->getType()->isIntegerTy())
2198 allocator = builder.CreateIntToPtr(allocator, builder.getPtrTy());
2199 else if (allocator->getType()->isPointerTy())
2200 allocator = builder.CreatePointerBitCastOrAddrSpaceCast(
2201 allocator, builder.getPtrTy());
2204 "OpenMP allocator operand must have integer or pointer type");
2206 privateVarsInfo.convertedAllocators.try_emplace(allocatorVar, allocator);
2214template <
typename T>
2216 T op, llvm::IRBuilderBase &builder,
2218 PrivateVarsInfo &privateVarsInfo,
2219 llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
2221 std::optional<llvm::OpenMPIRBuilder::InsertPointTy> allocatorIP =
2226 llvm::BasicBlock *allocaBB = allocaIP.getNodeParent();
2227 llvm::Instruction *allocaTerminator = allocaBB->getTerminator();
2228 splitBB(allocaTerminator->getIterator(),
true,
2229 allocaTerminator->getDebugLoc(),
"omp.region.after_alloca");
2231 allocaTerminator = allocaBB->getTerminator();
2233 assert(allocaTerminator->getNumSuccessors() == 1 &&
2234 "This is an unconditional branch created by splitBB");
2235 allocaIP = allocaTerminator->getIterator();
2237 llvm::Instruction *allocatorTerminator =
nullptr;
2238 llvm::BasicBlock *afterAllocatorAllocations =
nullptr;
2240 llvm::BasicBlock *allocatorBB = allocatorIP->getNodeParent();
2241 allocatorTerminator = allocatorBB->getTerminator();
2242 afterAllocatorAllocations = splitBB(
2243 allocatorTerminator->getIterator(),
true,
2244 allocatorTerminator->getDebugLoc(),
"omp.region.after_allocate");
2245 allocatorTerminator = allocatorBB->getTerminator();
2246 assert(allocatorTerminator->getNumSuccessors() == 1 &&
2247 "This is an unconditional branch created by splitBB");
2250 std::optional<llvm::IRBuilderBase::InsertPointGuard> guard;
2252 guard.emplace(builder);
2253 builder.SetInsertPoint(allocaTerminator);
2255 llvm::DataLayout dataLayout = builder.getDataLayout();
2256 llvm::BasicBlock *afterAllocas = allocaTerminator->getSuccessor(0);
2260 unsigned int allocaAS =
2261 moduleTranslation.
getLLVMModule()->getDataLayout().getAllocaAddrSpace();
2264 .getProgramAddressSpace();
2269 if constexpr (std::is_same_v<T, omp::ParallelOp> ||
2270 std::is_same_v<T, omp::ScopeOp>) {
2271 allocatorVars = op.getAllocatorVars();
2272 allocateAlignments = op.getAllocateAlignmentsAttr();
2273 if (
auto privateIndices = op.getAllocatePrivateIndicesAttr())
2274 for (
auto [allocateIndex, privateIndex] :
2275 llvm::enumerate(privateIndices.asArrayRef()))
2276 allocateItemForPrivate[privateIndex] = allocateIndex;
2279 for (
auto [privateIndex, var] : llvm::enumerate(privateVarsInfo.vars)) {
2280 llvm::Type *llvmAllocType =
2281 moduleTranslation.
convertType(var.privatizer.getType());
2282 llvm::Value *llvmPrivateVar =
nullptr;
2283 int64_t allocateIndex = allocateItemForPrivate[privateIndex];
2284 builder.SetInsertPoint(allocateIndex >= 0 && allocatorTerminator
2285 ? allocatorTerminator
2286 : allocaTerminator);
2287 if (allocateIndex >= 0) {
2288 if (ompBuilder->Config.isTargetDevice() ||
2289 op->template getParentOfType<omp::TargetOp>())
2290 return llvm::createStringError(
2291 "allocate clause in an OpenMP device context is not supported");
2292 if (!llvmAllocType->isSized())
2293 return llvm::createStringError(
2294 "allocate clause private type must have a fixed size");
2295 llvm::TypeSize size = dataLayout.getTypeAllocSize(llvmAllocType);
2296 if (size.isScalable())
2297 return llvm::createStringError(
2298 "allocate clause private type must have a fixed size");
2299 llvm::IntegerType *sizeTy =
2300 moduleTranslation.
getLLVMModule()->getDataLayout().getIntPtrType(
2302 if (!llvm::isUIntN(sizeTy->getBitWidth(), size.getFixedValue()))
2303 return llvm::createStringError(
2304 "OpenMP allocation size cannot be represented by the target size "
2306 llvm::Value *sizeValue =
2307 llvm::ConstantInt::get(sizeTy, size.getFixedValue());
2309 Value allocatorVar = allocatorVars[allocateIndex];
2310 auto allocator = privateVarsInfo.convertedAllocators.find(allocatorVar);
2311 if (allocator == privateVarsInfo.convertedAllocators.end())
2312 return llvm::createStringError(
2313 "failed to find converted OpenMP allocator operand");
2314 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2316 allocateAlignments ? allocateAlignments[allocateIndex] : 0;
2317 if (alignment != 0) {
2321 uint64_t alignmentValue = std::max<uint64_t>(
2322 static_cast<uint64_t
>(alignment),
2323 dataLayout.getABITypeAlign(llvmAllocType).value());
2324 if (!llvm::isUIntN(sizeTy->getBitWidth(), alignmentValue))
2325 return llvm::createStringError(
2326 "OpenMP allocation alignment cannot be represented by the "
2327 "target size type");
2328 llvmPrivateVar = ompBuilder->createOMPAlignedAlloc(
2329 ompLoc, llvm::ConstantInt::get(sizeTy, alignmentValue), sizeValue,
2330 allocator->second,
"omp.private.alloc");
2332 llvmPrivateVar = ompBuilder->createOMPAlloc(
2333 ompLoc, sizeValue, allocator->second,
"omp.private.alloc");
2335 if (!llvmPrivateVar)
2336 return llvm::createStringError(
2337 "failed to create OpenMP private allocation");
2338 privateVarsInfo.allocatorPrivates.push_back(
2339 {llvmPrivateVar, allocator->second});
2340 }
else if (mightUseDeviceSharedMem &&
2342 llvmPrivateVar = ompBuilder->createOMPAllocShared(builder, llvmAllocType);
2344 llvmPrivateVar = builder.CreateAlloca(
2345 llvmAllocType,
nullptr,
"omp.private.alloc");
2346 if (allocaAS != defaultAS)
2347 llvmPrivateVar = builder.CreateAddrSpaceCast(
2348 llvmPrivateVar, builder.getPtrTy(defaultAS));
2351 var.llvmVar = llvmPrivateVar;
2354 return afterAllocatorAllocations ? afterAllocatorAllocations : afterAllocas;
2365 if (mlir::isa<omp::ParallelOp>(parent))
2368 if (mlir::isa<omp::SingleOp, omp::CriticalOp, omp::MaskedOp, omp::MasterOp,
2369 omp::SectionOp>(parent))
2382 llvm::OpenMPIRBuilder::InsertPointOrErrorTy res =
2383 ompBuilder->createBarrier(builder, llvm::omp::OMPD_barrier);
2398 const PrivateVarsInfo &privateVarsInfo,
bool insertBarrier,
2402 assert((moldVars.empty() || moldVars.size() == privateVarsInfo.vars.size()) &&
2403 "expected one mold value per variable when provided");
2404 assert((llvmPrivateVars.empty() ||
2405 llvmPrivateVars.size() == privateVarsInfo.vars.size()) &&
2406 "expected one private allocation per variable when provided");
2409 bool needsFirstprivate = llvm::any_of(
2410 privateVarsInfo.vars, [](
const PrivateVarsInfo::VarInfo &var) {
2412 omp::PrivateClauseOp privOp = var.privatizer;
2413 return privOp.getDataSharingType() ==
2414 omp::DataSharingClauseType::FirstPrivate;
2417 if (!needsFirstprivate)
2418 return insertBarrier
2425 if (moldVars.empty()) {
2426 materializedMoldVars.reserve(privateVarsInfo.vars.size());
2427 for (const PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
2429 llvm::Value *moldVar = findAssociatedValue(
2430 var.mlirVar, builder, moduleTranslation, mappedPrivateVars);
2432 materializedMoldVars.push_back(moldVar);
2434 moldVars = materializedMoldVars;
2437 llvm::BasicBlock *copyBlock =
2438 splitBB(builder,
true,
"omp.private.copy");
2441 unsigned varIdx = 0;
2442 for (
auto [var, moldVar] : llvm::zip_equal(privateVarsInfo.vars, moldVars)) {
2445 llvm::Value *llvmVar =
2446 llvmPrivateVars.empty() ? var.llvmVar : llvmPrivateVars[varIdx];
2449 omp::PrivateClauseOp decl = var.privatizer;
2450 if (decl.getDataSharingType() != omp::DataSharingClauseType::FirstPrivate)
2454 Region ©Region = decl.getCopyRegion();
2457 builder, moduleTranslation, decl.getCopyMoldArg(), moldVar);
2459 builder, moduleTranslation, decl.getCopyPrivateArg(), llvmVar);
2461 moduleTranslation.
mapValue(decl.getCopyMoldArg(), copyMoldVar);
2464 moduleTranslation.
mapValue(decl.getCopyPrivateArg(), copyPrivateVar);
2468 moduleTranslation)))
2469 return decl.emitError(
"failed to inline `copy` region of `omp.private`");
2481 return insertBarrier
2486template <
typename T>
2490 PrivateVarsInfo &privateVarsInfo) {
2493 llvm::transform(privateVarsInfo.vars,
2494 std::back_inserter(privateCleanupRegions),
2495 [](PrivateVarsInfo::VarInfo &var) {
2496 return &var.privatizer.getDeallocRegion();
2501 moduleTranslation, builder,
2502 "omp.private.dealloc",
2504 return mlir::emitError(loc,
"failed to inline `dealloc` region of an "
2505 "`omp.private` op in");
2510 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
2511 if (mightUseDeviceSharedMem &&
2513 ompBuilder->createOMPFreeShared(
2514 builder, var.llvmVar,
2515 moduleTranslation.
convertType(var.privatizer.getType()));
2519 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2520 for (
const PrivateVarsInfo::AllocatorInfo &allocation :
2521 llvm::reverse(privateVarsInfo.allocatorPrivates))
2522 ompBuilder->createOMPFree(ompLoc, allocation.allocatedPtr,
2523 allocation.allocator);
2535 if (mlir::isa<omp::CancelOp, omp::CancellationPointOp>(child))
2552 llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP,
2554 bool isWorksharing =
false);
2561template <
typename OpTy>
2565 llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP,
2569 for (
unsigned i = 0, e = op.getNumReductionVars(); i != e; ++i) {
2570 if (op.getReductionModifier(i) != omp::ReductionModifier::task)
2572 taskDecls.push_back(reductionDecls[i]);
2573 taskVariables.push_back(privateReductionVariables[i]);
2576 taskDecls, taskVariables,
"__omp_taskred_mod_", builder, allocaIP,
2577 moduleTranslation,
true, isWorksharing);
2583 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2584 using StorableBodyGenCallbackTy =
2585 llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
2587 auto sectionsOp = cast<omp::SectionsOp>(opInst);
2592 ReductionVarsInfo redInfo(sectionsOp);
2593 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
2597 *sectionsOp, builder, moduleTranslation, allocaIP, redInfo)))
2600 bool isTaskReductionMod =
2601 sectionsOp.hasReductionModifier(omp::ReductionModifier::task);
2606 auto sectionOp = dyn_cast<omp::SectionOp>(op);
2610 Region ®ion = sectionOp.getRegion();
2611 auto sectionCB = [§ionsOp, ®ion, &builder, &moduleTranslation](
2612 InsertPointTy allocaIP, InsertPointTy codeGenIP,
2614 builder.restoreIP(codeGenIP);
2621 sectionsOp.getRegion().getNumArguments());
2622 for (
auto [sectionsArg, sectionArg] : llvm::zip_equal(
2623 sectionsOp.getRegion().getArguments(), region.
getArguments())) {
2624 llvm::Value *llvmVal = moduleTranslation.
lookupValue(sectionsArg);
2626 moduleTranslation.
mapValue(sectionArg, llvmVal);
2633 sectionCBs.push_back(sectionCB);
2637 if (sectionCBs.empty()) {
2638 if (!sectionsOp.getNowait()) {
2640 ->createBarrier(builder, llvm::omp::OMPD_sections);
2643 builder.restoreIP(*afterIP);
2653 if (isTaskReductionMod &&
2655 sectionsOp, redInfo.getReductionDecls(),
2656 redInfo.getPrivateReductionVariables(), builder, allocaIP,
2657 moduleTranslation,
true))
2658 return sectionsOp.emitError(
2659 "failed to emit task reduction modifier initialization");
2661 assert(isa<omp::SectionOp>(*sectionsOp.getRegion().op_begin()));
2666 auto privCB = [&](InsertPointTy, InsertPointTy codeGenIP, llvm::Value &,
2667 llvm::Value &vPtr, llvm::Value *&replacementValue)
2668 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
2669 replacementValue = &vPtr;
2675 auto finiCB = [&](InsertPointTy codeGenIP) {
return llvm::Error::success(); };
2679 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2680 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
2682 ->createSections(ompLoc, allocaIP, sectionCBs, privCB, finiCB,
2683 isCancellable, sectionsOp.getNowait());
2688 builder.restoreIP(*afterIP);
2691 if (isTaskReductionMod)
2697 allocaIP, redInfo, sectionsOp.getNowait());
2704 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2710 PrivateVarsInfo privateVarsInfo(scopeOp);
2712 moduleTranslation, privateVarsInfo)))
2715 ReductionVarsInfo reductionInfo(scopeOp);
2716 InsertPointTy privateAllocaIP =
2719 if (scopeOp.getAllocateVars().empty()) {
2721 scopeOp, builder, moduleTranslation, privateVarsInfo, privateAllocaIP);
2727 moduleTranslation, privateAllocaIP,
2732 [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
2734 if (!scopeOp.getAllocateVars().empty()) {
2738 scopeOp, builder, moduleTranslation, privateVarsInfo, privateAllocaIP,
2739 nullptr, codeGenIP);
2741 return llvm::make_error<PreviouslyReportedError>();
2742 builder.SetInsertPoint(afterAllocas.get()->getTerminator());
2744 builder.restoreIP(codeGenIP);
2751 return llvm::make_error<PreviouslyReportedError>();
2755 scopeOp.getPrivateNeedsBarrier())))
2756 return llvm::make_error<PreviouslyReportedError>();
2763 auto finiCB = [&](InsertPointTy codeGenIP) -> llvm::Error {
2764 InsertPointTy oldIP = builder.saveIP();
2765 builder.restoreIP(codeGenIP);
2767 scopeOp.getLoc(), privateVarsInfo)))
2768 return llvm::make_error<PreviouslyReportedError>();
2769 builder.restoreIP(oldIP);
2770 return llvm::Error::success();
2773 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2774 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
2775 ompBuilder->createScope(ompLoc, bodyCB, finiCB, scopeOp.getNowait());
2780 builder.restoreIP(*afterIP);
2784 privateAllocaIP, reductionInfo,
2785 scopeOp.getNowait(),
2793 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2794 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2799 auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
2801 builder.restoreIP(codegenIP);
2803 builder, moduleTranslation)
2806 auto finiCB = [&](InsertPointTy codeGenIP) {
return llvm::Error::success(); };
2810 std::optional<ArrayAttr> cpFuncs = singleOp.getCopyprivateSyms();
2813 for (
size_t i = 0, e = cpVars.size(); i < e; ++i) {
2814 llvmCPVars.push_back(moduleTranslation.
lookupValue(cpVars[i]));
2816 singleOp, cast<SymbolRefAttr>((*cpFuncs)[i]));
2817 llvmCPFuncs.push_back(
2821 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
2823 ->createSingle(ompLoc, bodyCB, finiCB, singleOp.getNowait(),
2824 llvmCPVars, llvmCPFuncs);
2829 builder.restoreIP(*afterIP);
2833static omp::DistributeOp
2837 omp::DistributeOp distOp;
2838 WalkResult walk = teamsOp.getRegion().walk([&](omp::DistributeOp op) {
2844 if (walk.wasInterrupted() || !distOp)
2848 llvm::cast<mlir::omp::BlockArgOpenMPOpInterface>(teamsOp.getOperation());
2852 for (
auto ra : iface.getReductionBlockArgs())
2853 for (
auto &use : ra.getUses()) {
2854 auto *useOp = use.getOwner();
2856 if (mlir::isa<LLVM::DbgDeclareOp, LLVM::DbgValueOp>(useOp)) {
2857 debugUses.push_back(useOp);
2860 if (!distOp->isProperAncestor(useOp))
2867 for (
auto *use : debugUses)
2876 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2880 std::optional<ReductionVarsInfo> teamsRedInfo;
2881 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
2887 teamsRedInfo.emplace(op);
2890 allocaIP, *teamsRedInfo)))
2894 auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
2897 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
2898 builder.restoreIP(codegenIP);
2904 llvm::Value *numTeamsLower =
nullptr;
2905 if (
Value numTeamsLowerVar = op.getNumTeamsLower())
2906 numTeamsLower = moduleTranslation.
lookupValue(numTeamsLowerVar);
2908 llvm::Value *numTeamsUpper =
nullptr;
2909 if (!op.getNumTeamsUpperVars().empty())
2910 numTeamsUpper = moduleTranslation.
lookupValue(op.getNumTeams(0));
2912 llvm::Value *threadLimit =
nullptr;
2913 if (!op.getThreadLimitVars().empty())
2914 threadLimit = moduleTranslation.
lookupValue(op.getThreadLimit(0));
2916 llvm::Value *ifExpr =
nullptr;
2917 if (
Value ifVar = op.getIfExpr())
2920 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2921 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
2923 ->createTeams(ompLoc, bodyCB, numTeamsLower, numTeamsUpper,
2924 threadLimit, ifExpr);
2929 builder.restoreIP(*afterIP);
2940static llvm::omp::RTLDependenceKindTy
2943 case mlir::omp::ClauseTaskDepend::taskdependin:
2944 return llvm::omp::RTLDependenceKindTy::DepIn;
2948 case mlir::omp::ClauseTaskDepend::taskdependout:
2949 case mlir::omp::ClauseTaskDepend::taskdependinout:
2950 return llvm::omp::RTLDependenceKindTy::DepInOut;
2951 case mlir::omp::ClauseTaskDepend::taskdependmutexinoutset:
2952 return llvm::omp::RTLDependenceKindTy::DepMutexInOutSet;
2953 case mlir::omp::ClauseTaskDepend::taskdependinoutset:
2954 return llvm::omp::RTLDependenceKindTy::DepInOutSet;
2956 llvm_unreachable(
"unhandled depend kind");
2960 std::optional<ArrayAttr> dependKinds,
OperandRange dependVars,
2963 if (dependVars.empty())
2965 for (
auto dep : llvm::zip(dependVars, dependKinds->getValue())) {
2967 cast<mlir::omp::ClauseTaskDependAttr>(std::get<1>(dep)).getValue();
2969 llvm::Value *depVal = moduleTranslation.
lookupValue(std::get<0>(dep));
2970 llvm::OpenMPIRBuilder::DependData dd(type, depVal->getType(), depVal);
2971 dds.emplace_back(dd);
2983 llvm::IRBuilderBase &llvmBuilder, llvm::OpenMPIRBuilder &ompBuilder,
2985 auto finiCB = [&](llvm::OpenMPIRBuilder::InsertPointTy ip) -> llvm::Error {
2986 llvm::IRBuilderBase::InsertPointGuard guard(llvmBuilder);
2990 llvmBuilder.restoreIP(ip);
2996 cancelTerminators.push_back(llvmBuilder.CreateBr(ip.getNodeParent()));
2997 return llvm::Error::success();
3002 ompBuilder.pushFinalizationCB(
3012 llvm::OpenMPIRBuilder &ompBuilder,
3013 llvm::BasicBlock *afterBB) {
3014 ompBuilder.popFinalizationCB();
3015 llvm::BasicBlock *constructFini = afterBB->getSinglePredecessor();
3016 for (llvm::UncondBrInst *cancelBranch : cancelTerminators)
3017 cancelBranch->setSuccessor(constructFini);
3023class TaskContextStructManager {
3025 TaskContextStructManager(llvm::IRBuilderBase &builder,
3026 LLVM::ModuleTranslation &moduleTranslation,
3027 const PrivateVarsInfo &privateVarsInfo)
3028 : builder{builder}, moduleTranslation{moduleTranslation},
3029 privateVarsInfo{privateVarsInfo} {}
3035 void generateTaskContextStruct();
3041 void createGEPsToPrivateVars();
3047 SmallVector<llvm::Value *>
3048 createGEPsToPrivateVars(llvm::Value *altStructPtr)
const;
3051 void freeStructPtr();
3053 MutableArrayRef<llvm::Value *> getLLVMPrivateVarGEPs() {
3054 return llvmPrivateVarGEPs;
3057 llvm::Value *getStructPtr() {
return structPtr; }
3060 llvm::IRBuilderBase &builder;
3061 LLVM::ModuleTranslation &moduleTranslation;
3062 const PrivateVarsInfo &privateVarsInfo;
3065 SmallVector<llvm::Type *> privateVarTypes;
3069 SmallVector<llvm::Value *> llvmPrivateVarGEPs;
3072 llvm::Value *structPtr =
nullptr;
3074 llvm::Type *structTy =
nullptr;
3086 llvm::SmallVector<llvm::Value *> lowerBounds;
3087 llvm::SmallVector<llvm::Value *> upperBounds;
3088 llvm::SmallVector<llvm::Value *> steps;
3089 llvm::SmallVector<llvm::Value *> trips;
3091 llvm::Value *totalTrips;
3094 IteratorInfo(mlir::omp::IteratorOp itersOp,
3095 mlir::LLVM::ModuleTranslation &moduleTranslation,
3096 llvm::IRBuilderBase &builder) {
3097 dims = itersOp.getLoopLowerBounds().size();
3098 lowerBounds.resize(dims);
3099 upperBounds.resize(dims);
3103 for (
unsigned d = 0; d < dims; ++d) {
3105 moduleTranslation.
lookupValue(itersOp.getLoopLowerBounds()[d]);
3107 moduleTranslation.
lookupValue(itersOp.getLoopUpperBounds()[d]);
3109 moduleTranslation.
lookupValue(itersOp.getLoopSteps()[d]);
3110 assert(lb && ub && st &&
3111 "Expect lowerBounds, upperBounds, and steps in IteratorOp");
3112 assert(lb->getType() == ub->getType() && lb->getType() == st->getType() &&
3113 "Expect matching iterator range types");
3114 assert((!llvm::isa<llvm::ConstantInt>(st) ||
3115 !llvm::cast<llvm::ConstantInt>(st)->isZero()) &&
3116 "Expect non-zero step in IteratorOp");
3118 lowerBounds[d] = lb;
3119 upperBounds[d] = ub;
3124 llvm::Type *countTy =
3125 builder.getIntNTy(lb->getType()->getIntegerBitWidth() + 1);
3126 llvm::Value *start = builder.CreateSExt(lb, countTy);
3127 llvm::Value *stop = builder.CreateSExt(ub, countTy);
3128 llvm::Value *step = builder.CreateSExt(st, countTy);
3129 llvm::Value *count =
3131 ->calculateCanonicalLoopTripCount(
3132 builder, start, stop, step,
3133 true, itersOp.getLoopInclusive(),
"iterator");
3134 trips[d] = builder.CreateZExtOrTrunc(count, builder.getInt64Ty());
3137 totalTrips = llvm::ConstantInt::get(builder.getInt64Ty(), 1);
3138 for (
unsigned d = 0; d < dims; ++d)
3139 totalTrips = builder.CreateMul(totalTrips, trips[d]);
3142 unsigned getDims()
const {
return dims; }
3143 llvm::ArrayRef<llvm::Value *> getLowerBounds()
const {
return lowerBounds; }
3144 llvm::ArrayRef<llvm::Value *> getUpperBounds()
const {
return upperBounds; }
3145 llvm::ArrayRef<llvm::Value *> getSteps()
const {
return steps; }
3146 llvm::ArrayRef<llvm::Value *> getTrips()
const {
return trips; }
3147 llvm::Value *getTotalTrips()
const {
return totalTrips; }
3151void TaskContextStructManager::generateTaskContextStruct() {
3152 if (privateVarsInfo.vars.empty())
3154 privateVarTypes.reserve(privateVarsInfo.vars.size());
3156 for (
const PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
3157 omp::PrivateClauseOp privOp = var.privatizer;
3160 if (!privOp.readsFromMold())
3162 Type mlirType = privOp.getType();
3163 privateVarTypes.push_back(moduleTranslation.
convertType(mlirType));
3166 if (privateVarTypes.empty())
3169 structTy = llvm::StructType::get(moduleTranslation.
getLLVMContext(),
3172 llvm::DataLayout dataLayout = builder.getDataLayout();
3173 llvm::Type *intPtrTy = builder.getIntPtrTy(dataLayout);
3174 llvm::Value *allocSize =
3175 builder.CreateTypeSize(intPtrTy, dataLayout.getTypeAllocSize(structTy));
3178 structPtr = builder.CreateMalloc(intPtrTy, allocSize,
3180 "omp.task.context_ptr");
3183SmallVector<llvm::Value *> TaskContextStructManager::createGEPsToPrivateVars(
3184 llvm::Value *altStructPtr)
const {
3185 SmallVector<llvm::Value *> ret;
3188 ret.reserve(privateVarsInfo.vars.size());
3189 llvm::Value *zero = builder.getInt32(0);
3191 for (
const PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
3192 omp::PrivateClauseOp privDecl = var.privatizer;
3193 if (!privDecl.readsFromMold()) {
3195 ret.push_back(
nullptr);
3198 llvm::Value *iVal = builder.getInt32(i);
3199 llvm::Value *gep = builder.CreateGEP(structTy, altStructPtr, {zero, iVal});
3206void TaskContextStructManager::createGEPsToPrivateVars() {
3208 assert(privateVarTypes.empty());
3212 llvmPrivateVarGEPs = createGEPsToPrivateVars(structPtr);
3215void TaskContextStructManager::freeStructPtr() {
3219 llvm::IRBuilderBase::InsertPointGuard guard{builder};
3221 builder.SetInsertPoint(builder.GetInsertBlock()->getTerminator());
3222 builder.CreateFree(structPtr);
3226 llvm::OpenMPIRBuilder &ompBuilder,
3227 llvm::Value *affinityList, llvm::Value *
index,
3228 llvm::Value *addr, llvm::Value *len) {
3229 llvm::StructType *kmpTaskAffinityInfoTy =
3230 ompBuilder.getKmpTaskAffinityInfoTy();
3231 llvm::Value *entry = builder.CreateInBoundsGEP(
3232 kmpTaskAffinityInfoTy, affinityList,
index,
"omp.affinity.entry");
3234 addr = builder.CreatePtrToInt(addr, kmpTaskAffinityInfoTy->getElementType(0));
3235 len = builder.CreateIntCast(len, kmpTaskAffinityInfoTy->getElementType(1),
3237 llvm::Value *flags = builder.getInt32(0);
3239 builder.CreateStore(addr,
3240 builder.CreateStructGEP(kmpTaskAffinityInfoTy, entry, 0));
3241 builder.CreateStore(len,
3242 builder.CreateStructGEP(kmpTaskAffinityInfoTy, entry, 1));
3243 builder.CreateStore(flags,
3244 builder.CreateStructGEP(kmpTaskAffinityInfoTy, entry, 2));
3248 llvm::IRBuilderBase &builder,
3250 llvm::Value *affinityList) {
3251 for (
auto [i, affinityVar] : llvm::enumerate(affinityVars)) {
3252 auto entryOp = affinityVar.getDefiningOp<mlir::omp::AffinityEntryOp>();
3253 assert(entryOp &&
"affinity item must be omp.affinity_entry");
3255 llvm::Value *addr = moduleTranslation.
lookupValue(entryOp.getAddr());
3256 llvm::Value *len = moduleTranslation.
lookupValue(entryOp.getLen());
3257 assert(addr && len &&
"expect affinity addr and len to be non-null");
3259 affinityList, builder.getInt64(i), addr, len);
3264 llvm::Value *linearIV, IteratorInfo &iterInfo,
mlir::Region &iteratorRegion,
3267 llvm::Value *tmp = linearIV;
3268 for (
int d = (
int)iterInfo.getDims() - 1; d >= 0; --d) {
3269 llvm::Value *trip = iterInfo.getTrips()[d];
3270 llvm::Value *zero = llvm::ConstantInt::get(trip->getType(), 0);
3271 llvm::Value *one = llvm::ConstantInt::get(trip->getType(), 1);
3274 llvm::Value *divisor =
3275 builder.CreateSelect(builder.CreateICmpEQ(trip, zero), one, trip);
3277 llvm::Value *idx = builder.CreateURem(tmp, divisor);
3279 tmp = builder.CreateUDiv(tmp, divisor);
3283 builder.CreateZExtOrTrunc(idx, iterInfo.getLowerBounds()[d]->getType());
3284 llvm::Value *physIV = builder.CreateAdd(
3285 iterInfo.getLowerBounds()[d],
3286 builder.CreateMul(idx, iterInfo.getSteps()[d]),
"omp.it.phys_iv");
3293 moduleTranslation.
mapBlock(&entryBlock, builder.GetInsertBlock());
3294 return moduleTranslation.
convertBlock(entryBlock,
true,
3302 llvm::BasicBlock *continuation =
3303 splitBB(builder,
true,
"omp.iterator.region.cont");
3304 llvm::Instruction *sourceBranch = builder.GetInsertBlock()->getTerminator();
3308 llvm::BasicBlock::Create(builder.getContext(),
"omp.iterator.region",
3309 continuation->getParent(), continuation));
3310 sourceBranch->setSuccessor(0, moduleTranslation.
lookupBlock(&entryBlock));
3313 llvm::IRBuilderBase::InsertPointGuard guard(builder);
3314 if (failed(moduleTranslation.
convertBlock(*block, block->isEntryBlock(),
3316 return mlir::failure();
3317 if (isa<omp::YieldOp>(block->getTerminator()))
3318 builder.CreateBr(continuation);
3322 builder.SetInsertPoint(continuation);
3323 return mlir::success();
3329static mlir::LogicalResult
3332 IteratorInfo &iterInfo, llvm::StringRef loopName,
3336 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
3338 auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy bodyIP,
3339 llvm::Value *linearIV) -> llvm::Error {
3340 llvm::IRBuilderBase::InsertPointGuard guard(builder);
3341 builder.restoreIP(bodyIP);
3344 moduleTranslation))) {
3345 return llvm::make_error<llvm::StringError>(
3346 "failed to convert iterator region", llvm::inconvertibleErrorCode());
3349 mlir::omp::YieldOp yield = itersOp.getYieldOp();
3350 assert(yield && yield.getResults().size() == 1 &&
3351 "expect omp.yield in iterator region to have one result");
3353 genStoreEntry(linearIV, yield);
3359 return llvm::Error::success();
3362 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
3364 ->createIteratorLoop(loc, iterInfo.getTotalTrips(), bodyGen,
3369 builder.restoreIP(*afterIP);
3371 return mlir::success();
3374static mlir::LogicalResult
3377 llvm::OpenMPIRBuilder::AffinityData &ad) {
3379 if (taskOp.getAffinityVars().empty() && taskOp.getIterated().empty()) {
3382 return mlir::success();
3386 llvm::StructType *kmpTaskAffinityInfoTy =
3389 auto allocateAffinityList = [&](llvm::Value *count) -> llvm::Value * {
3390 llvm::IRBuilderBase::InsertPointGuard guard(builder);
3391 if (llvm::isa<llvm::Constant>(count) || llvm::isa<llvm::Argument>(count))
3393 return builder.CreateAlloca(kmpTaskAffinityInfoTy, count,
3394 "omp.affinity_list");
3397 auto createAffinity =
3398 [&](llvm::Value *count,
3399 llvm::Value *info) -> llvm::OpenMPIRBuilder::AffinityData {
3400 llvm::OpenMPIRBuilder::AffinityData ad{};
3401 ad.Count = builder.CreateTrunc(count, builder.getInt32Ty());
3403 builder.CreatePointerBitCastOrAddrSpaceCast(info, builder.getPtrTy(0));
3407 if (!taskOp.getAffinityVars().empty()) {
3408 llvm::Value *count = llvm::ConstantInt::get(
3409 builder.getInt64Ty(), taskOp.getAffinityVars().size());
3410 llvm::Value *list = allocateAffinityList(count);
3413 ads.emplace_back(createAffinity(count, list));
3416 if (!taskOp.getIterated().empty()) {
3417 for (
auto [i, iter] : llvm::enumerate(taskOp.getIterated())) {
3418 auto itersOp = iter.getDefiningOp<omp::IteratorOp>();
3419 assert(itersOp &&
"iterated value must be defined by omp.iterator");
3420 IteratorInfo iterInfo(itersOp, moduleTranslation, builder);
3421 llvm::Value *affList = allocateAffinityList(iterInfo.getTotalTrips());
3423 itersOp, builder, moduleTranslation, iterInfo,
"iterator",
3424 [&](llvm::Value *linearIV, mlir::omp::YieldOp yield) {
3425 auto entryOp = yield.getResults()[0]
3426 .getDefiningOp<mlir::omp::AffinityEntryOp>();
3427 assert(entryOp &&
"expect yield produce an affinity entry");
3434 affList, linearIV, addr, len);
3436 return llvm::failure();
3437 ads.emplace_back(createAffinity(iterInfo.getTotalTrips(), affList));
3441 llvm::Value *totalAffinityCount = builder.getInt32(0);
3442 for (
const auto &affinity : ads)
3443 totalAffinityCount = builder.CreateAdd(
3445 builder.CreateIntCast(affinity.Count, builder.getInt32Ty(),
3448 llvm::Value *affinityInfo = ads.front().Info;
3449 if (ads.size() > 1) {
3450 llvm::StructType *kmpTaskAffinityInfoTy =
3452 llvm::Value *affinityInfoElemSize = builder.getInt64(
3453 moduleTranslation.
getLLVMModule()->getDataLayout().getTypeAllocSize(
3454 kmpTaskAffinityInfoTy));
3456 llvm::Value *packedAffinityInfo = allocateAffinityList(totalAffinityCount);
3457 llvm::Value *packedAffinityInfoOffset = builder.getInt32(0);
3458 for (
const auto &affinity : ads) {
3459 llvm::Value *affinityCount = builder.CreateIntCast(
3460 affinity.Count, builder.getInt32Ty(),
false);
3461 llvm::Value *affinityCountInt64 = builder.CreateIntCast(
3462 affinityCount, builder.getInt64Ty(),
false);
3463 llvm::Value *affinityInfoSize =
3464 builder.CreateMul(affinityCountInt64, affinityInfoElemSize);
3466 llvm::Value *packedAffinityInfoIndex = builder.CreateIntCast(
3467 packedAffinityInfoOffset, kmpTaskAffinityInfoTy->getElementType(0),
3469 packedAffinityInfoIndex = builder.CreateInBoundsGEP(
3470 kmpTaskAffinityInfoTy, packedAffinityInfo, packedAffinityInfoIndex);
3472 builder.CreateMemCpy(
3473 packedAffinityInfoIndex, llvm::Align(1),
3474 builder.CreatePointerBitCastOrAddrSpaceCast(
3475 affinity.Info, builder.getPtrTy(packedAffinityInfoIndex->getType()
3476 ->getPointerAddressSpace())),
3477 llvm::Align(1), affinityInfoSize);
3479 packedAffinityInfoOffset =
3480 builder.CreateAdd(packedAffinityInfoOffset, affinityCount);
3483 affinityInfo = packedAffinityInfo;
3486 ad.Count = totalAffinityCount;
3487 ad.Info = affinityInfo;
3489 return mlir::success();
3495static mlir::LogicalResult
3498 std::optional<ArrayAttr> dependIteratedKinds,
3499 llvm::IRBuilderBase &builder,
3501 llvm::OpenMPIRBuilder::DependenciesInfo &taskDeps) {
3502 if (dependIterated.empty()) {
3505 return mlir::success();
3509 llvm::Type *dependInfoTy = ompBuilder.DependInfo;
3510 unsigned numLocator = dependVars.size();
3513 llvm::Value *totalCount =
3514 llvm::ConstantInt::get(builder.getInt64Ty(), numLocator);
3517 for (
auto iter : dependIterated) {
3518 auto itersOp = iter.getDefiningOp<mlir::omp::IteratorOp>();
3519 assert(itersOp &&
"depend_iterated value must be defined by omp.iterator");
3520 iterInfos.emplace_back(itersOp, moduleTranslation, builder);
3522 builder.CreateAdd(totalCount, iterInfos.back().getTotalTrips());
3527 llvm::DataLayout dataLayout = builder.getDataLayout();
3528 llvm::Value *allocSize = builder.CreateTypeSize(
3529 ompBuilder.SizeTy, dataLayout.getTypeAllocSize(dependInfoTy));
3530 llvm::Value *depArray =
3531 builder.CreateMalloc(ompBuilder.SizeTy, allocSize, totalCount,
3532 nullptr,
".dep.arr.addr");
3535 if (numLocator > 0) {
3538 for (
auto [i, dd] : llvm::enumerate(dds)) {
3539 llvm::Value *idx = llvm::ConstantInt::get(builder.getInt64Ty(), i);
3540 llvm::Value *entry =
3541 builder.CreateInBoundsGEP(dependInfoTy, depArray, idx);
3542 ompBuilder.emitTaskDependency(builder, entry, dd);
3547 llvm::Value *offset =
3548 llvm::ConstantInt::get(builder.getInt64Ty(), numLocator);
3549 for (
auto [i, iterInfo] : llvm::enumerate(iterInfos)) {
3550 auto kindAttr = cast<mlir::omp::ClauseTaskDependAttr>(
3551 dependIteratedKinds->getValue()[i]);
3552 llvm::omp::RTLDependenceKindTy rtlKind =
3555 auto itersOp = dependIterated[i].getDefiningOp<mlir::omp::IteratorOp>();
3557 itersOp, builder, moduleTranslation, iterInfo,
"dep_iterator",
3558 [&](llvm::Value *linearIV, mlir::omp::YieldOp yield) {
3560 moduleTranslation.
lookupValue(yield.getResults()[0]);
3561 llvm::Value *idx = builder.CreateAdd(offset, linearIV);
3562 llvm::Value *entry =
3563 builder.CreateInBoundsGEP(dependInfoTy, depArray, idx);
3564 ompBuilder.emitTaskDependency(
3566 llvm::OpenMPIRBuilder::DependData{rtlKind, addr->getType(),
3569 return mlir::failure();
3572 offset = builder.CreateAdd(offset, iterInfo.getTotalTrips());
3575 taskDeps.DepArray = depArray;
3576 taskDeps.NumDeps = builder.CreateTrunc(totalCount, builder.getInt32Ty());
3577 return mlir::success();
3584 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
3588 PrivateVarsInfo privateVarsInfo(taskOp);
3589 TaskContextStructManager taskStructMgr{builder, moduleTranslation,
3601 InsertPointTy allocaIP =
3606 assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end());
3607 llvm::BasicBlock *taskStartBlock = llvm::BasicBlock::Create(
3608 builder.getContext(),
"omp.task.start",
3609 builder.GetInsertBlock()->getParent());
3610 llvm::Instruction *branchToTaskStartBlock = builder.CreateBr(taskStartBlock);
3611 builder.SetInsertPoint(branchToTaskStartBlock);
3614 llvm::BasicBlock *copyBlock =
3615 splitBB(builder,
true,
"omp.private.copy");
3616 llvm::BasicBlock *initBlock =
3617 splitBB(builder,
true,
"omp.private.init");
3633 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
3636 builder.SetInsertPoint(initBlock->getTerminator());
3639 taskStructMgr.generateTaskContextStruct();
3646 taskStructMgr.createGEPsToPrivateVars();
3648 for (
auto [var, llvmPrivateVarAlloc] : llvm::zip_equal(
3649 privateVarsInfo.vars, taskStructMgr.getLLVMPrivateVarGEPs())) {
3651 if (!var.privatizer.readsFromMold())
3653 assert(llvmPrivateVarAlloc &&
3654 "reads from mold so shouldn't have been skipped");
3657 initPrivateVar(builder, moduleTranslation, var.privatizer, var.mlirVar,
3658 var.blockArg, llvmPrivateVarAlloc, initBlock);
3659 if (!privateVarOrErr)
3660 return handleError(privateVarOrErr, *taskOp.getOperation());
3669 [[maybe_unused]] llvm::Value *llvmPrivateVar = llvmPrivateVarAlloc;
3670 if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
3671 !mlir::isa<LLVM::LLVMPointerType>(var.blockArg.
getType())) {
3672 builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
3674 llvmPrivateVar = builder.CreateLoad(privateVarOrErr.get()->getType(),
3675 llvmPrivateVarAlloc);
3677 assert(llvmPrivateVar->getType() ==
3688 taskOp, builder, moduleTranslation, privateVarsInfo,
3689 taskOp.getPrivateNeedsBarrier(),
3690 {}, taskStructMgr.getLLVMPrivateVarGEPs())))
3691 return llvm::failure();
3693 llvm::OpenMPIRBuilder::AffinityData ad;
3695 return llvm::failure();
3705 taskOp.getOperation(), taskOp.getInReductionSyms(),
"omp.task",
3706 "in_reduction", inRedDecls)))
3709 inRedOrigPtrs.reserve(inRedDecls.size());
3710 for (
Value v : taskOp.getInReductionVars())
3711 inRedOrigPtrs.push_back(moduleTranslation.
lookupValue(v));
3714 builder.SetInsertPoint(taskStartBlock);
3717 [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
3722 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
3725 builder.restoreIP(codegenIP);
3727 llvm::BasicBlock *privInitBlock =
nullptr;
3728 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
3730 if (var.privatizer.readsFromMold())
3733 llvm::IRBuilderBase::InsertPointGuard guard(builder);
3734 llvm::Type *llvmAllocType =
3735 moduleTranslation.
convertType(var.privatizer.getType());
3736 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
3737 llvm::Value *llvmPrivateVar = builder.CreateAlloca(
3738 llvmAllocType,
nullptr,
"omp.private.alloc");
3741 builder, moduleTranslation, var.privatizer, var.mlirVar, var.blockArg,
3742 llvmPrivateVar, privInitBlock);
3743 if (!privateVarOrError)
3744 return privateVarOrError.takeError();
3745 moduleTranslation.
mapValue(var.blockArg, privateVarOrError.get());
3746 var.llvmVar = privateVarOrError.get();
3749 taskStructMgr.createGEPsToPrivateVars();
3750 for (
auto [i, llvmPrivVar] :
3751 llvm::enumerate(taskStructMgr.getLLVMPrivateVarGEPs())) {
3753 assert(privateVarsInfo.vars[i].llvmVar &&
3754 "This is added in the loop above");
3757 privateVarsInfo.vars[i].llvmVar = llvmPrivVar;
3762 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
3764 if (!var.privatizer.readsFromMold())
3767 if (!mlir::isa<LLVM::LLVMPointerType>(var.blockArg.
getType())) {
3768 var.llvmVar = builder.CreateLoad(
3771 assert(var.llvmVar->getType() ==
3773 moduleTranslation.
mapValue(var.blockArg, var.llvmVar);
3784 if (!inRedDecls.empty()) {
3785 auto iface = cast<omp::BlockArgOpenMPOpInterface>(taskOp.getOperation());
3788 llvm::LLVMContext &llvmCtx = m->getContext();
3789 llvm::OpenMPIRBuilder::LocationDescription bodyLoc(builder);
3790 uint32_t srcLocSize;
3791 llvm::Constant *srcLocStr =
3792 ompB.getOrCreateSrcLocStr(bodyLoc, srcLocSize);
3793 llvm::Value *bodyIdent = ompB.getOrCreateIdent(srcLocStr, srcLocSize);
3796 ompB.updateToLocation(bodyLoc);
3797 llvm::Value *bodyGtid = ompB.getOrCreateThreadID(bodyIdent);
3798 llvm::FunctionCallee getThData = ompB.getOrCreateRuntimeFunction(
3799 *m, llvm::omp::OMPRTL___kmpc_task_reduction_get_th_data);
3800 llvm::Type *ptrTy = llvm::PointerType::getUnqual(llvmCtx);
3801 llvm::Value *nullDesc = llvm::ConstantPointerNull::get(ptrTy);
3803 for (
auto [blockArg, origPtr] :
3804 llvm::zip_equal(inRedBlockArgs, inRedOrigPtrs)) {
3811 llvm::Value *lookupPtr = origPtr;
3812 if (
auto *origPtrTy =
3813 llvm::dyn_cast<llvm::PointerType>(lookupPtr->getType());
3814 origPtrTy && origPtrTy->getAddressSpace() != 0)
3815 lookupPtr = builder.CreateAddrSpaceCast(lookupPtr, ptrTy);
3816 llvm::Value *priv = ompB.createRuntimeFunctionCall(
3817 getThData, {bodyGtid, nullDesc, lookupPtr},
"omp.inred.priv");
3818 if (
auto *argPtrTy = llvm::dyn_cast<llvm::PointerType>(
3819 moduleTranslation.
convertType(blockArg.getType()));
3820 argPtrTy && argPtrTy->getAddressSpace() != 0)
3821 priv = builder.CreateAddrSpaceCast(priv, argPtrTy);
3822 moduleTranslation.
mapValue(blockArg, priv);
3827 taskOp.getRegion(),
"omp.task.region", builder, moduleTranslation);
3828 if (failed(
handleError(continuationBlockOrError, *taskOp)))
3829 return llvm::make_error<PreviouslyReportedError>();
3831 builder.SetInsertPoint(continuationBlockOrError.get()->getTerminator());
3834 taskOp.getLoc(), privateVarsInfo)))
3835 return llvm::make_error<PreviouslyReportedError>();
3838 taskStructMgr.freeStructPtr();
3840 return llvm::Error::success();
3849 llvm::omp::Directive::OMPD_taskgroup);
3851 llvm::OpenMPIRBuilder::DependenciesInfo dependencies;
3852 if (failed(
buildDependData(taskOp.getDependVars(), taskOp.getDependKinds(),
3853 taskOp.getDependIterated(),
3854 taskOp.getDependIteratedKinds(), builder,
3855 moduleTranslation, dependencies)))
3858 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
3859 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
3861 ->createTask(ompLoc, allocaIP, deallocBlocks, bodyCB,
3862 !taskOp.getUntied(),
3864 moduleTranslation.
lookupValue(taskOp.getIfExpr()),
3865 dependencies, ad, taskOp.getMergeable(),
3866 moduleTranslation.
lookupValue(taskOp.getEventHandle()),
3867 moduleTranslation.
lookupValue(taskOp.getPriority()),
3868 taskOp.getThreadset() == omp::ThreadsetPolicy::omp_pool);
3875 afterIP->getNodeParent());
3877 builder.restoreIP(*afterIP);
3879 if (dependencies.DepArray)
3880 builder.CreateFree(dependencies.DepArray);
3889 llvm::IRBuilderBase &builder,
3897 loopWrapperOp.getRegion(),
"omp.taskloop.wrapper.region", builder,
3900 if (failed(
handleError(continuationBlockOrError, opInst)))
3903 builder.SetInsertPoint(continuationBlockOrError.get());
3911static llvm::Expected<llvm::Value *>
3914 llvm::IRBuilderBase &builder) {
3915 if (llvm::Value *mapped = moduleTranslation.
lookupValue(value))
3920 return llvm::make_error<llvm::StringError>(
3921 "value is a block argument and is not mapped",
3922 llvm::inconvertibleErrorCode());
3924 return llvm::make_error<llvm::StringError>(
3925 "unsupported op defining taskloop loop bound",
3926 llvm::inconvertibleErrorCode());
3936 if (!operandOrError)
3937 return operandOrError.takeError();
3938 moduleTranslation.
mapValue(operand, *operandOrError);
3939 mappingsToRemove.push_back(operand);
3943 return llvm::make_error<llvm::StringError>(
3944 "failed to convert op defining taskloop loop bound",
3945 llvm::inconvertibleErrorCode());
3948 assert(
result &&
"expected conversion of loop bound op to produce a value");
3952 mappingsToRemove.push_back(resultValue);
3954 for (
Value mappedValue : mappingsToRemove)
3963 llvm::Value *&lbVal, llvm::Value *&ubVal,
3964 llvm::Value *&stepVal) {
3972 return firstLbOrErr.takeError();
3974 llvm::Type *boundType = (*firstLbOrErr)->getType();
3975 ubVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
3976 if (loopOp.getCollapseNumLoops() > 1) {
3994 for (uint64_t i = 0; i < loopOp.getCollapseNumLoops(); i++) {
3996 i == 0 ? std::move(firstLbOrErr)
4000 return lbOrErr.takeError();
4002 upperBounds[i], moduleTranslation, builder);
4004 return ubOrErr.takeError();
4008 return stepOrErr.takeError();
4010 llvm::Value *loopLb = *lbOrErr;
4011 llvm::Value *loopUb = *ubOrErr;
4012 llvm::Value *loopStep = *stepOrErr;
4018 llvm::Value *loopLbMinusOne = builder.CreateSub(
4019 loopLb, builder.getIntN(boundType->getIntegerBitWidth(), 1));
4020 llvm::Value *loopUbMinusOne = builder.CreateSub(
4021 loopUb, builder.getIntN(boundType->getIntegerBitWidth(), 1));
4022 llvm::Value *boundsCmp = builder.CreateICmpSLT(loopLb, loopUb);
4023 llvm::Value *ubMinusLb = builder.CreateSub(loopUb, loopLbMinusOne);
4024 llvm::Value *lbMinusUb = builder.CreateSub(loopLb, loopUbMinusOne);
4025 llvm::Value *loopTripCount =
4026 builder.CreateSelect(boundsCmp, ubMinusLb, lbMinusUb);
4027 loopTripCount = builder.CreateBinaryIntrinsic(
4028 llvm::Intrinsic::abs, loopTripCount, builder.getFalse());
4032 llvm::Value *loopTripCountDivStep =
4033 builder.CreateSDiv(loopTripCount, loopStep);
4034 loopTripCountDivStep = builder.CreateBinaryIntrinsic(
4035 llvm::Intrinsic::abs, loopTripCountDivStep, builder.getFalse());
4036 llvm::Value *loopTripCountRem =
4037 builder.CreateSRem(loopTripCount, loopStep);
4038 loopTripCountRem = builder.CreateBinaryIntrinsic(
4039 llvm::Intrinsic::abs, loopTripCountRem, builder.getFalse());
4040 llvm::Value *needsRoundUp = builder.CreateICmpNE(
4042 builder.getIntN(loopTripCountRem->getType()->getIntegerBitWidth(),
4045 builder.CreateAdd(loopTripCountDivStep,
4046 builder.CreateZExtOrTrunc(
4047 needsRoundUp, loopTripCountDivStep->getType()));
4048 ubVal = builder.CreateMul(ubVal, loopTripCount);
4050 lbVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
4051 stepVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
4056 return ubOrErr.takeError();
4060 return stepOrErr.takeError();
4061 lbVal = *firstLbOrErr;
4063 stepVal = *stepOrErr;
4066 assert(lbVal !=
nullptr &&
"Expected value for lbVal");
4067 assert(ubVal !=
nullptr &&
"Expected value for ubVal");
4068 assert(stepVal !=
nullptr &&
"Expected value for stepVal");
4069 return llvm::Error::success();
4075 llvm::IRBuilderBase &builder,
4077 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4079 omp::TaskloopWrapperOp loopWrapperOp = contextOp.getLoopOp();
4086 PrivateVarsInfo privateVarsInfo(contextOp);
4087 TaskContextStructManager taskStructMgr{builder, moduleTranslation,
4091 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
4094 assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end());
4095 llvm::BasicBlock *taskloopStartBlock = llvm::BasicBlock::Create(
4096 builder.getContext(),
"omp.taskloop.wrapper.start",
4097 builder.GetInsertBlock()->getParent());
4098 llvm::Instruction *branchToTaskloopStartBlock =
4099 builder.CreateBr(taskloopStartBlock);
4100 builder.SetInsertPoint(branchToTaskloopStartBlock);
4102 llvm::BasicBlock *copyBlock =
4103 splitBB(builder,
true,
"omp.private.copy");
4104 llvm::BasicBlock *initBlock =
4105 splitBB(builder,
true,
"omp.private.init");
4108 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
4111 builder.SetInsertPoint(initBlock->getTerminator());
4114 taskStructMgr.generateTaskContextStruct();
4115 taskStructMgr.createGEPsToPrivateVars();
4117 llvmFirstPrivateVars.resize(privateVarsInfo.vars.size());
4119 for (
auto [i, zip] : llvm::enumerate(llvm::zip_equal(
4120 privateVarsInfo.vars, taskStructMgr.getLLVMPrivateVarGEPs()))) {
4121 auto &[var, llvmPrivateVarAlloc] = zip;
4123 if (!var.privatizer.readsFromMold())
4125 assert(llvmPrivateVarAlloc &&
4126 "reads from mold so shouldn't have been skipped");
4129 initPrivateVar(builder, moduleTranslation, var.privatizer, var.mlirVar,
4130 var.blockArg, llvmPrivateVarAlloc, initBlock);
4131 if (!privateVarOrErr)
4132 return handleError(privateVarOrErr, *contextOp.getOperation());
4134 llvmFirstPrivateVars[i] = privateVarOrErr.get();
4136 llvm::IRBuilderBase::InsertPointGuard guard(builder);
4137 builder.SetInsertPoint(builder.GetInsertBlock()->getTerminator());
4139 [[maybe_unused]] llvm::Value *llvmPrivateVar = llvmPrivateVarAlloc;
4140 if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
4141 !mlir::isa<LLVM::LLVMPointerType>(var.blockArg.
getType())) {
4142 builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
4144 llvmPrivateVar = builder.CreateLoad(privateVarOrErr.get()->getType(),
4145 llvmPrivateVarAlloc);
4147 assert(llvmPrivateVar->getType() ==
4154 contextOp, builder, moduleTranslation, privateVarsInfo,
4155 contextOp.getPrivateNeedsBarrier(),
4156 {}, taskStructMgr.getLLVMPrivateVarGEPs())))
4157 return llvm::failure();
4167 contextOp.getOperation(), contextOp.getReductionSyms(),
4168 "omp.taskloop.context",
"reduction", redDecls)))
4172 contextOp.getOperation(), contextOp.getInReductionSyms(),
4173 "omp.taskloop.context",
"in_reduction", inRedDecls)))
4179 redOrigPtrs.reserve(redDecls.size());
4180 for (
Value v : contextOp.getReductionVars())
4181 redOrigPtrs.push_back(moduleTranslation.
lookupValue(v));
4183 inRedOrigPtrs.reserve(inRedDecls.size());
4184 for (
Value v : contextOp.getInReductionVars())
4185 inRedOrigPtrs.push_back(moduleTranslation.
lookupValue(v));
4189 builder.SetInsertPoint(taskloopStartBlock);
4191 llvm::OpenMPIRBuilder &ompBuilderRef = *
getOpenMPBuilder(moduleTranslation);
4198 bool implicitTaskgroup = !redDecls.empty();
4199 llvm::Value *redDesc =
nullptr;
4200 if (implicitTaskgroup) {
4201 llvm::OpenMPIRBuilder::LocationDescription redLoc(builder);
4202 uint32_t srcLocSize;
4203 llvm::Constant *srcLocStr =
4204 ompBuilderRef.getOrCreateSrcLocStr(redLoc, srcLocSize);
4205 llvm::Value *ident = ompBuilderRef.getOrCreateIdent(srcLocStr, srcLocSize);
4208 ompBuilderRef.updateToLocation(redLoc);
4209 llvm::Value *outerGtid = ompBuilderRef.getOrCreateThreadID(ident);
4210 llvm::FunctionCallee taskgroupFn = ompBuilderRef.getOrCreateRuntimeFunction(
4211 *module, llvm::omp::OMPRTL___kmpc_taskgroup);
4212 ompBuilderRef.createRuntimeFunctionCall(taskgroupFn, {ident, outerGtid});
4215 "__omp_taskloop_taskred_", builder,
4216 allocaIP, moduleTranslation);
4221 auto loopOp = cast<omp::LoopNestOp>(loopWrapperOp.getWrappedLoop());
4222 llvm::Value *lbVal =
nullptr;
4223 llvm::Value *ubVal =
nullptr;
4224 llvm::Value *stepVal =
nullptr;
4226 loopOp, builder, moduleTranslation, lbVal, ubVal, stepVal))
4230 [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
4235 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
4238 builder.restoreIP(codegenIP);
4240 llvm::BasicBlock *privInitBlock =
nullptr;
4241 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
4243 if (var.privatizer.readsFromMold())
4246 llvm::IRBuilderBase::InsertPointGuard guard(builder);
4247 llvm::Type *llvmAllocType =
4248 moduleTranslation.
convertType(var.privatizer.getType());
4249 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
4250 llvm::Value *llvmPrivateVar = builder.CreateAlloca(
4251 llvmAllocType,
nullptr,
"omp.private.alloc");
4254 builder, moduleTranslation, var.privatizer, var.mlirVar, var.blockArg,
4255 llvmPrivateVar, privInitBlock);
4256 if (!privateVarOrError)
4257 return privateVarOrError.takeError();
4258 moduleTranslation.
mapValue(var.blockArg, privateVarOrError.get());
4259 var.llvmVar = privateVarOrError.get();
4262 taskStructMgr.createGEPsToPrivateVars();
4263 for (
auto [i, llvmPrivVar] :
4264 llvm::enumerate(taskStructMgr.getLLVMPrivateVarGEPs())) {
4266 assert(privateVarsInfo.vars[i].llvmVar &&
4267 "This is added in the loop above");
4270 privateVarsInfo.vars[i].llvmVar = llvmPrivVar;
4275 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
4277 if (!var.privatizer.readsFromMold())
4280 if (!mlir::isa<LLVM::LLVMPointerType>(var.blockArg.
getType())) {
4281 var.llvmVar = builder.CreateLoad(
4284 assert(var.llvmVar->getType() ==
4286 moduleTranslation.
mapValue(var.blockArg, var.llvmVar);
4298 if (!redDecls.empty() || !inRedDecls.empty()) {
4300 cast<omp::BlockArgOpenMPOpInterface>(contextOp.getOperation());
4303 llvm::LLVMContext &llvmCtx = m->getContext();
4304 llvm::OpenMPIRBuilder::LocationDescription bodyLoc(builder);
4305 uint32_t srcLocSize;
4306 llvm::Constant *srcLocStr =
4307 ompB.getOrCreateSrcLocStr(bodyLoc, srcLocSize);
4308 llvm::Value *bodyIdent = ompB.getOrCreateIdent(srcLocStr, srcLocSize);
4311 ompB.updateToLocation(bodyLoc);
4312 llvm::Value *bodyGtid = ompB.getOrCreateThreadID(bodyIdent);
4313 llvm::FunctionCallee getThData = ompB.getOrCreateRuntimeFunction(
4314 *m, llvm::omp::OMPRTL___kmpc_task_reduction_get_th_data);
4315 llvm::Type *ptrTy = llvm::PointerType::getUnqual(llvmCtx);
4325 auto remapReductionArg = [&](
BlockArgument blockArg, llvm::Value *desc,
4326 llvm::Value *origPtr,
4327 const llvm::Twine &name) {
4328 if (
auto *origPtrTy =
4329 llvm::dyn_cast<llvm::PointerType>(origPtr->getType());
4330 origPtrTy && origPtrTy->getAddressSpace() != 0)
4331 origPtr = builder.CreateAddrSpaceCast(origPtr, ptrTy);
4332 llvm::Value *priv = ompB.createRuntimeFunctionCall(
4333 getThData, {bodyGtid, desc, origPtr}, name);
4334 if (
auto *argPtrTy = llvm::dyn_cast<llvm::PointerType>(
4336 argPtrTy && argPtrTy->getAddressSpace() != 0)
4337 priv = builder.CreateAddrSpaceCast(priv, argPtrTy);
4338 moduleTranslation.
mapValue(blockArg, priv);
4342 for (
auto [blockArg, origPtr] :
4343 llvm::zip_equal(redBlockArgs, redOrigPtrs))
4344 remapReductionArg(blockArg, redDesc, origPtr,
"omp.taskred.priv");
4346 llvm::Value *nullDesc = llvm::ConstantPointerNull::get(ptrTy);
4347 for (
auto [blockArg, origPtr] :
4348 llvm::zip_equal(inRedBlockArgs, inRedOrigPtrs))
4349 remapReductionArg(blockArg, nullDesc, origPtr,
"omp.inred.priv");
4355 contextOp.getRegion(),
"omp.taskloop.context.region", builder,
4358 if (failed(
handleError(continuationBlockOrError, opInst)))
4359 return llvm::make_error<PreviouslyReportedError>();
4361 builder.SetInsertPoint(continuationBlockOrError.get()->getTerminator());
4369 contextOp.getLoc(), privateVarsInfo)))
4370 return llvm::make_error<PreviouslyReportedError>();
4373 taskStructMgr.freeStructPtr();
4375 return llvm::Error::success();
4381 auto taskDupCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
4382 llvm::Value *destPtr, llvm::Value *srcPtr)
4384 llvm::IRBuilderBase::InsertPointGuard guard(builder);
4385 builder.restoreIP(codegenIP);
4388 builder.getPtrTy(srcPtr->getType()->getPointerAddressSpace());
4390 builder.CreateLoad(ptrTy, srcPtr,
"omp.taskloop.context.src");
4392 TaskContextStructManager &srcStructMgr = taskStructMgr;
4393 TaskContextStructManager destStructMgr(builder, moduleTranslation,
4395 destStructMgr.generateTaskContextStruct();
4396 llvm::Value *dest = destStructMgr.getStructPtr();
4397 dest->setName(
"omp.taskloop.context.dest");
4398 builder.CreateStore(dest, destPtr);
4401 srcStructMgr.createGEPsToPrivateVars(src);
4403 destStructMgr.createGEPsToPrivateVars(dest);
4406 for (
auto [var, mold, llvmPrivateVarAlloc] :
4407 llvm::zip_equal(privateVarsInfo.vars, srcGEPs, destGEPs)) {
4409 if (!var.privatizer.readsFromMold())
4411 assert(llvmPrivateVarAlloc &&
4412 "reads from mold so shouldn't have been skipped");
4415 builder, moduleTranslation, var.privatizer.getInitMoldArg(), mold);
4417 builder, moduleTranslation, var.privatizer, moldArg, var.blockArg,
4418 llvmPrivateVarAlloc, builder.GetInsertBlock());
4419 if (!privateVarOrErr)
4420 return privateVarOrErr.takeError();
4429 [[maybe_unused]] llvm::Value *llvmPrivateVar = llvmPrivateVarAlloc;
4430 if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
4431 !mlir::isa<LLVM::LLVMPointerType>(var.blockArg.
getType())) {
4432 builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
4434 llvmPrivateVar = builder.CreateLoad(privateVarOrErr.get()->getType(),
4435 llvmPrivateVarAlloc);
4437 assert(llvmPrivateVar->getType() ==
4446 moduleTranslation, privateVarsInfo,
4447 contextOp.getPrivateNeedsBarrier(), srcGEPs,
4449 return llvm::make_error<PreviouslyReportedError>();
4451 return builder.saveIP();
4459 llvm::Value *ifCond =
nullptr;
4460 llvm::Value *grainsize =
nullptr;
4462 mlir::Value grainsizeVal = contextOp.getGrainsize();
4463 mlir::Value numTasksVal = contextOp.getNumTasks();
4464 if (
Value ifVar = contextOp.getIfExpr())
4467 grainsize = moduleTranslation.
lookupValue(grainsizeVal);
4469 }
else if (numTasksVal) {
4470 grainsize = moduleTranslation.
lookupValue(numTasksVal);
4474 llvm::OpenMPIRBuilder::TaskDupCallbackTy taskDupOrNull =
nullptr;
4475 if (taskStructMgr.getStructPtr())
4476 taskDupOrNull = taskDupCB;
4486 llvm::omp::Directive::OMPD_taskgroup);
4488 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
4489 bool effectiveNoGroup = contextOp.getNogroup() || implicitTaskgroup;
4490 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
4493 ompLoc, allocaIP, deallocBlocks, bodyCB, loopInfo, lbVal, ubVal,
4494 stepVal, contextOp.getUntied(), ifCond, grainsize,
4495 effectiveNoGroup, sched,
4496 moduleTranslation.
lookupValue(contextOp.getFinal()),
4497 contextOp.getMergeable(),
4498 moduleTranslation.
lookupValue(contextOp.getPriority()),
4499 loopOp.getCollapseNumLoops(), taskDupOrNull,
4500 taskStructMgr.getStructPtr(),
4501 contextOp.getThreadset() == omp::ThreadsetPolicy::omp_pool);
4507 afterIP->getNodeParent());
4509 builder.restoreIP(*afterIP);
4513 if (implicitTaskgroup) {
4514 llvm::OpenMPIRBuilder::LocationDescription endLoc(builder);
4515 uint32_t srcLocSize;
4516 llvm::Constant *srcLocStr =
4517 ompBuilder.getOrCreateSrcLocStr(endLoc, srcLocSize);
4518 llvm::Value *ident = ompBuilder.getOrCreateIdent(srcLocStr, srcLocSize);
4521 ompBuilder.updateToLocation(endLoc);
4522 llvm::Value *outerGtid = ompBuilder.getOrCreateThreadID(ident);
4523 llvm::FunctionCallee endTgFn = ompBuilder.getOrCreateRuntimeFunction(
4525 llvm::omp::OMPRTL___kmpc_end_taskgroup);
4526 ompBuilder.createRuntimeFunctionCall(endTgFn, {ident, outerGtid});
4537static llvm::Function *
4540 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
4541 llvm::LLVMContext &ctx = llvmModule->getContext();
4542 llvm::Type *voidTy = llvm::Type::getVoidTy(ctx);
4543 llvm::Type *ptrTy = llvm::PointerType::getUnqual(ctx);
4544 llvm::FunctionType *fty =
4545 llvm::FunctionType::get(voidTy, {ptrTy, ptrTy},
false);
4546 llvm::Function *fn =
4547 llvm::Function::Create(fty, llvm::GlobalValue::InternalLinkage,
4548 baseName +
".red.init", llvmModule);
4549 fn->setDoesNotRecurse();
4550 fn->getArg(0)->setName(
"priv");
4551 fn->getArg(1)->setName(
"orig");
4553 llvm::BasicBlock *entry = llvm::BasicBlock::Create(ctx,
"entry", fn);
4554 llvm::IRBuilder<>
b(entry);
4561 Value moldArg = decl.getInitializerMoldArg();
4562 llvm::Value *origVal = fn->getArg(1);
4563 if (!isa<LLVM::LLVMPointerType>(moldArg.
getType()))
4565 fn->getArg(1),
"omp.orig");
4566 moduleTranslation.
mapValue(moldArg, origVal);
4569 "omp.taskred.init",
b, moduleTranslation,
4571 fn->eraseFromParent();
4574 assert(phis.size() == 1 &&
4575 "expected one value yielded from reduction initializer");
4576 b.CreateStore(phis[0], fn->getArg(0));
4579 moduleTranslation.
forgetMapping(decl.getInitializerRegion());
4587static llvm::Function *
4590 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
4591 llvm::LLVMContext &ctx = llvmModule->getContext();
4592 llvm::Type *voidTy = llvm::Type::getVoidTy(ctx);
4593 llvm::Type *ptrTy = llvm::PointerType::getUnqual(ctx);
4594 llvm::FunctionType *fty =
4595 llvm::FunctionType::get(voidTy, {ptrTy, ptrTy},
false);
4596 llvm::Function *fn =
4597 llvm::Function::Create(fty, llvm::GlobalValue::InternalLinkage,
4598 baseName +
".red.comb", llvmModule);
4599 fn->setDoesNotRecurse();
4600 fn->getArg(0)->setName(
"lhs");
4601 fn->getArg(1)->setName(
"rhs");
4603 llvm::BasicBlock *entry = llvm::BasicBlock::Create(ctx,
"entry", fn);
4604 llvm::IRBuilder<>
b(entry);
4606 llvm::Type *elemTy = moduleTranslation.
convertType(decl.getType());
4607 Block &combBlock = decl.getReductionRegion().
front();
4609 "expected two arguments in declare_reduction combiner");
4610 llvm::Value *lhsVal =
b.CreateLoad(elemTy, fn->getArg(0),
"omp.lhs");
4611 llvm::Value *rhsVal =
b.CreateLoad(elemTy, fn->getArg(1),
"omp.rhs");
4617 "omp.taskred.comb",
b, moduleTranslation,
4619 fn->eraseFromParent();
4622 assert(phis.size() == 1 &&
4623 "expected one value yielded from reduction combiner");
4624 b.CreateStore(phis[0], fn->getArg(0));
4650 llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP,
4652 bool isWorksharing) {
4653 assert(redDecls.size() == origPtrs.size() &&
4654 "expected one orig pointer per reduction decl");
4656 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
4657 llvm::LLVMContext &ctx = llvmModule->getContext();
4658 const llvm::DataLayout &dl = llvmModule->getDataLayout();
4660 llvm::Type *ptrTy = llvm::PointerType::getUnqual(ctx);
4661 llvm::Type *i32Ty = llvm::Type::getInt32Ty(ctx);
4662 llvm::Type *sizeTy =
4663 llvm::Type::getIntNTy(ctx, dl.getPointerSizeInBits(0));
4667 llvm::StructType *redInputTy =
4668 llvm::StructType::getTypeByName(ctx,
"kmp_taskred_input_t");
4670 redInputTy = llvm::StructType::create(
4671 ctx, {ptrTy, ptrTy, sizeTy, ptrTy, ptrTy, ptrTy, i32Ty},
4672 "kmp_taskred_input_t");
4674 unsigned n = redDecls.size();
4675 llvm::ArrayType *arrTy = llvm::ArrayType::get(redInputTy, n);
4678 llvm::AllocaInst *arrAlloca;
4680 llvm::IRBuilderBase::InsertPointGuard guard(builder);
4681 builder.restoreIP(allocaIP);
4683 builder.CreateAlloca(arrTy,
nullptr,
".taskred.input");
4687 llvm::Value *zero = builder.getInt32(0);
4688 for (
unsigned i = 0; i < n; ++i) {
4689 omp::DeclareReductionOp decl = redDecls[i];
4690 llvm::Value *orig = origPtrs[i];
4691 if (
auto *origPtrTy = llvm::dyn_cast<llvm::PointerType>(orig->getType());
4692 origPtrTy && origPtrTy->getAddressSpace() != 0)
4693 orig = builder.CreateAddrSpaceCast(orig, ptrTy);
4694 llvm::Type *elemTy = moduleTranslation.
convertType(decl.getType());
4695 uint64_t size = dl.getTypeAllocSize(elemTy).getFixedValue();
4697 std::string baseName =
4698 (llvm::Twine(helperNamePrefix) + decl.getSymName()).str();
4699 llvm::Function *initFn =
4701 llvm::Function *combFn =
4703 if (!initFn || !combFn)
4705 llvm::Value *elemPtr = builder.CreateInBoundsGEP(
4706 arrTy, arrAlloca, {zero, builder.getInt32(i)},
".taskred.elem");
4707 auto storeField = [&](
unsigned fieldIdx, llvm::Value *val) {
4708 llvm::Value *fieldPtr =
4709 builder.CreateStructGEP(redInputTy, elemPtr, fieldIdx);
4710 builder.CreateStore(val, fieldPtr);
4712 storeField(0, orig);
4713 storeField(1, orig);
4714 storeField(2, llvm::ConstantInt::get(sizeTy, size));
4715 storeField(3, initFn);
4716 storeField(4, llvm::ConstantPointerNull::get(ptrTy));
4717 storeField(5, combFn);
4718 storeField(6, llvm::ConstantInt::get(i32Ty, 0));
4722 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
4723 uint32_t srcLocSize;
4724 llvm::Constant *srcLocStr =
4725 ompBuilder->getOrCreateSrcLocStr(ompLoc, srcLocSize);
4726 llvm::Value *ident = ompBuilder->getOrCreateIdent(srcLocStr, srcLocSize);
4727 ompBuilder->updateToLocation(ompLoc);
4728 llvm::Value *gtid = ompBuilder->getOrCreateThreadID(ident);
4732 llvm::FunctionCallee modInit = ompBuilder->getOrCreateRuntimeFunction(
4733 *llvmModule, llvm::omp::OMPRTL___kmpc_taskred_modifier_init);
4734 return ompBuilder->createRuntimeFunctionCall(
4736 {ident, gtid, builder.getInt32(isWorksharing ? 1 : 0),
4737 builder.getInt32(n), arrAlloca},
4741 llvm::FunctionCallee taskredInit = ompBuilder->getOrCreateRuntimeFunction(
4742 *llvmModule, llvm::omp::OMPRTL___kmpc_taskred_init);
4743 return ompBuilder->createRuntimeFunctionCall(
4744 taskredInit, {gtid, builder.getInt32(n), arrAlloca},
".taskred.desc");
4754 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
4755 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
4756 uint32_t srcLocSize;
4757 llvm::Constant *srcLocStr =
4758 ompBuilder->getOrCreateSrcLocStr(ompLoc, srcLocSize);
4759 llvm::Value *ident = ompBuilder->getOrCreateIdent(srcLocStr, srcLocSize);
4760 ompBuilder->updateToLocation(ompLoc);
4761 llvm::Value *gtid = ompBuilder->getOrCreateThreadID(ident);
4762 llvm::FunctionCallee fini = ompBuilder->getOrCreateRuntimeFunction(
4763 *llvmModule, llvm::omp::OMPRTL___kmpc_task_reduction_modifier_fini);
4764 ompBuilder->createRuntimeFunctionCall(
4765 fini, {ident, gtid, builder.getInt32(isWorksharing ? 1 : 0)});
4772 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4781 if (
auto syms = tgOp.getTaskReductionSyms()) {
4782 redDecls.reserve(syms->size());
4783 for (
auto sym : syms->getAsRange<SymbolRefAttr>()) {
4787 return tgOp.emitError()
4788 <<
"failed to resolve task_reduction declare_reduction symbol "
4789 << sym.getRootReference() <<
" in omp.taskgroup";
4790 if (decl.getInitializerRegion().front().getNumArguments() != 1)
4791 return tgOp.emitError(
"not yet implemented: task_reduction with "
4792 "two-argument initializer in omp.taskgroup");
4793 if (!decl.getCleanupRegion().empty())
4794 return tgOp.emitError(
"not yet implemented: task_reduction with "
4795 "cleanup region in omp.taskgroup");
4796 if (decl.getReductionRegion().empty())
4797 return tgOp.emitError(
"task_reduction declare_reduction is missing a "
4799 redDecls.push_back(decl);
4804 [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
4806 builder.restoreIP(codegenIP);
4808 if (!redDecls.empty()) {
4810 origPtrs.reserve(redDecls.size());
4811 for (
Value v : tgOp.getTaskReductionVars())
4812 origPtrs.push_back(moduleTranslation.
lookupValue(v));
4814 builder, allocaIP, moduleTranslation))
4815 return llvm::createStringError(
4816 llvm::inconvertibleErrorCode(),
4817 "failed to emit task_reduction initialization for omp.taskgroup");
4825 for (
auto [i, blockArg] :
4826 llvm::enumerate(tgOp.getRegion().getArguments())) {
4828 moduleTranslation.
lookupValue(tgOp.getTaskReductionVars()[i]);
4829 moduleTranslation.
mapValue(blockArg, orig);
4833 builder, moduleTranslation)
4838 InsertPointTy allocaIP =
4840 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
4841 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
4843 ->createTaskgroup(ompLoc, allocaIP, deallocBlocks, bodyCB);
4848 builder.restoreIP(*afterIP);
4855 if (!initOp.getDependVars().empty() || initOp.getDependKinds() ||
4856 !initOp.getDependIterated().empty() || initOp.getDependIteratedKinds())
4857 return initOp.emitError()
4858 <<
"not yet implemented: Unhandled clause depend in "
4859 << omp::InteropInitOp::getOperationName() <<
" operation";
4862 llvm::Value *interopVar =
4863 moduleTranslation.
lookupValue(initOp.getInteropVar());
4864 llvm::Value *device = initOp.getDevice()
4865 ? moduleTranslation.
lookupValue(initOp.getDevice())
4869 llvm::Value *numDeps = llvm::ConstantInt::get(builder.getInt32Ty(), 0);
4870 llvm::Value *depArray = llvm::ConstantPointerNull::get(builder.getPtrTy());
4871 bool hasNowait = initOp.getNowait();
4878 bool hasTarget =
false, hasTargetSync =
false;
4880 switch (cast<omp::InteropTypeAttr>(typeAttr).getValue()) {
4881 case omp::InteropType::target:
4884 case omp::InteropType::targetsync:
4885 hasTargetSync =
true;
4889 llvm::omp::OMPInteropType interopType =
4890 (!hasTarget && hasTargetSync) ? llvm::omp::OMPInteropType::TargetSync
4891 : llvm::omp::OMPInteropType::Target;
4892 ompBuilder->createOMPInteropInit(builder, interopVar, interopType, device,
4893 numDeps, depArray, hasNowait);
4899 llvm::IRBuilderBase &builder,
4901 if (!destroyOp.getDependVars().empty() || destroyOp.getDependKinds() ||
4902 !destroyOp.getDependIterated().empty() ||
4903 destroyOp.getDependIteratedKinds())
4904 return destroyOp.emitError()
4905 <<
"not yet implemented: Unhandled clause depend in "
4906 << omp::InteropDestroyOp::getOperationName() <<
" operation";
4909 llvm::Value *interopVar =
4910 moduleTranslation.
lookupValue(destroyOp.getInteropVar());
4911 llvm::Value *device =
4912 destroyOp.getDevice()
4913 ? moduleTranslation.
lookupValue(destroyOp.getDevice())
4916 llvm::Value *numDeps = llvm::ConstantInt::get(builder.getInt32Ty(), 0);
4917 llvm::Value *depArray = llvm::ConstantPointerNull::get(builder.getPtrTy());
4918 bool hasNowait = destroyOp.getNowait();
4920 ompBuilder->createOMPInteropDestroy(builder, interopVar, device, numDeps,
4921 depArray, hasNowait);
4928 if (!useOp.getDependVars().empty() || useOp.getDependKinds() ||
4929 !useOp.getDependIterated().empty() || useOp.getDependIteratedKinds())
4930 return useOp.emitError()
4931 <<
"not yet implemented: Unhandled clause depend in "
4932 << omp::InteropUseOp::getOperationName() <<
" operation";
4935 llvm::Value *interopVar =
4936 moduleTranslation.
lookupValue(useOp.getInteropVar());
4937 llvm::Value *device = useOp.getDevice()
4938 ? moduleTranslation.
lookupValue(useOp.getDevice())
4941 llvm::Value *numDeps = llvm::ConstantInt::get(builder.getInt32Ty(), 0);
4942 llvm::Value *depArray = llvm::ConstantPointerNull::get(builder.getPtrTy());
4943 bool hasNowait = useOp.getNowait();
4945 ompBuilder->createOMPInteropUse(builder, interopVar, device, numDeps,
4946 depArray, hasNowait);
4956 llvm::OpenMPIRBuilder::DependenciesInfo dds;
4958 twOp.getDependVars(), twOp.getDependKinds(), twOp.getDependIterated(),
4959 twOp.getDependIteratedKinds(), builder, moduleTranslation, dds))) {
4964 ->createTaskwait(builder, dds, twOp.getNowait());
4966 builder.CreateFree(dds.DepArray);
4977 auto wsloopOp = cast<omp::WsloopOp>(opInst);
4981 auto loopOp = cast<omp::LoopNestOp>(wsloopOp.getWrappedLoop());
4985 wsloopOp.getScheduleKind().value_or(omp::ClauseScheduleKind::Static);
4988 llvm::Value *step = moduleTranslation.
lookupValue(loopOp.getLoopSteps()[0]);
4989 llvm::Type *ivType = step->getType();
4990 llvm::Value *chunk =
nullptr;
4991 if (wsloopOp.getScheduleChunk()) {
4992 llvm::Value *chunkVar =
4993 moduleTranslation.
lookupValue(wsloopOp.getScheduleChunk());
4994 chunk = builder.CreateSExtOrTrunc(chunkVar, ivType);
4997 omp::DistributeOp distributeOp =
nullptr;
4998 llvm::Value *distScheduleChunk =
nullptr;
4999 bool hasDistSchedule =
false;
5000 if (llvm::isa_and_present<omp::DistributeOp>(opInst.
getParentOp())) {
5001 distributeOp = cast<omp::DistributeOp>(opInst.
getParentOp());
5002 hasDistSchedule = distributeOp.getDistScheduleStatic();
5003 if (distributeOp.getDistScheduleChunkSize()) {
5004 llvm::Value *chunkVar = moduleTranslation.
lookupValue(
5005 distributeOp.getDistScheduleChunkSize());
5006 distScheduleChunk = builder.CreateSExtOrTrunc(chunkVar, ivType);
5010 PrivateVarsInfo privateVarsInfo(wsloopOp);
5011 privateVarsInfo.addLinearVars(wsloopOp);
5012 ReductionVarsInfo reductionInfo(wsloopOp);
5014 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5017 llvm::BasicBlock *allocaBlock = allocaIP.getNodeParent();
5019 wsloopOp, builder, moduleTranslation, privateVarsInfo, allocaIP);
5034 wsloopOp.getPrivateNeedsBarrier())))
5037 assert(afterAllocas.get()->getSinglePredecessor());
5038 if (failed(initReductionVars(*wsloopOp, builder, moduleTranslation,
5039 afterAllocas.get()->getSinglePredecessor(),
5046 bool isTaskReductionMod =
5047 wsloopOp.hasReductionModifier(omp::ReductionModifier::task);
5048 if (isTaskReductionMod &&
5050 wsloopOp, reductionInfo.getReductionDecls(),
5051 reductionInfo.getPrivateReductionVariables(), builder, allocaIP,
5052 moduleTranslation,
true))
5053 return wsloopOp.emitError(
5054 "failed to emit task reduction modifier initialization");
5057 bool isOrdered = wsloopOp.getOrdered().has_value();
5058 std::optional<omp::ScheduleModifier> scheduleMod = wsloopOp.getScheduleMod();
5059 bool isSimd = wsloopOp.getScheduleSimd();
5060 bool loopNeedsBarrier = !wsloopOp.getNowait();
5065 llvm::omp::WorksharingLoopType workshareLoopType =
5066 llvm::isa_and_present<omp::DistributeOp>(opInst.
getParentOp())
5067 ? llvm::omp::WorksharingLoopType::DistributeForStaticLoop
5068 : llvm::omp::WorksharingLoopType::ForStaticLoop;
5072 llvm::omp::Directive::OMPD_for);
5074 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5077 LinearClauseProcessor linearClauseProcessor;
5079 if (!wsloopOp.getLinearVars().empty()) {
5080 auto linearVarTypes = wsloopOp.getLinearVarTypes().value();
5082 linearClauseProcessor.registerType(moduleTranslation, linearVarType);
5084 for (
auto [idx, linearVar] : llvm::enumerate(wsloopOp.getLinearVars())) {
5085 size_t privIdx = privateVarsInfo.numPrivateVars + idx;
5086 linearClauseProcessor.createLinearVar(
5087 builder, allocaIP, privateVarsInfo.vars[privIdx].privatizer,
5089 privateVarsInfo.vars[privIdx].llvmVar, idx);
5091 for (
mlir::Value linearStep : wsloopOp.getLinearStepVars())
5092 linearClauseProcessor.initLinearStep(moduleTranslation, linearStep);
5096 wsloopOp.getRegion(),
"omp.wsloop.region", builder, moduleTranslation);
5104 if (!wsloopOp.getLinearVars().empty()) {
5106 linearClauseProcessor.initLinearVar(builder, moduleTranslation,
5107 loopInfo->getPreheader()),
5110 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
5112 ->createBarrier(builder, llvm::omp::OMPD_barrier);
5115 builder.restoreIP(*afterBarrierIP);
5116 if (failed(
handleError(linearClauseProcessor.updateLinearVar(
5117 builder, moduleTranslation, loopInfo->getBody(),
5118 loopInfo->getIndVar()),
5121 linearClauseProcessor.splitLinearFiniBB(builder, loopInfo->getExit());
5124 builder.SetInsertPoint((*regionBlock)->begin());
5127 bool noLoopMode =
false;
5128 omp::TargetOp targetOp = wsloopOp->getParentOfType<mlir::omp::TargetOp>();
5130 targetOp.getKernelType() == omp::TargetExecMode::spmd_no_loop) {
5132 cast<omp::ComposableOpInterface>(*targetOp).findCapturedOp();
5136 if (loopOp == targetCapturedOp)
5141 allocaIP = allocaBlock->getFirstInsertionPt();
5142 llvm::OpenMPIRBuilder::InsertPointOrErrorTy wsloopIP =
5143 ompBuilder->applyWorkshareLoop(
5144 ompLoc.DL, loopInfo, allocaIP, loopNeedsBarrier,
5145 convertToScheduleKind(schedule), chunk, isSimd,
5146 scheduleMod == omp::ScheduleModifier::monotonic,
5147 scheduleMod == omp::ScheduleModifier::nonmonotonic, isOrdered,
5148 workshareLoopType, noLoopMode, hasDistSchedule, distScheduleChunk,
5149 !wsloopOp.getLinearVars().empty());
5156 llvm::BasicBlock *wsloopContinuationBB = wsloopIP->getNodeParent();
5159 if (!wsloopOp.getLinearVars().empty()) {
5160 llvm::OpenMPIRBuilder::InsertPointTy oldIP = builder.saveIP();
5161 assert(loopInfo->getLastIter() &&
5162 "`lastiter` in CanonicalLoopInfo is nullptr");
5163 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
5164 linearClauseProcessor.finalizeLinearVar(builder, moduleTranslation,
5165 loopInfo->getLastIter());
5169 builder.restoreIP(oldIP);
5176 if (isTaskReductionMod)
5182 allocaIP, reductionInfo,
5183 wsloopOp.getNowait(),
5188 wsloopOp.getLoc(), privateVarsInfo);
5195 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
5202 PrivateVarsInfo privateVarsInfo(opInst);
5204 moduleTranslation, privateVarsInfo)))
5208 ReductionVarsInfo reductionInfo(opInst);
5214 bool isTaskReductionMod =
5215 opInst.hasReductionModifier(omp::ReductionModifier::task);
5218 [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
5221 opInst, builder, moduleTranslation, privateVarsInfo, allocaIP);
5223 return llvm::make_error<PreviouslyReportedError>();
5226 allocaIP = allocaIP.getNodeParent()->getTerminator()->getIterator();
5230 return llvm::make_error<PreviouslyReportedError>();
5232 assert(afterAllocas.get()->getSinglePredecessor());
5233 builder.restoreIP(codeGenIP);
5239 return llvm::make_error<PreviouslyReportedError>();
5243 opInst.getPrivateNeedsBarrier())))
5244 return llvm::make_error<PreviouslyReportedError>();
5246 if (failed(initReductionVars(*opInst, builder, moduleTranslation,
5247 afterAllocas.get()->getSinglePredecessor(),
5249 return llvm::make_error<PreviouslyReportedError>();
5254 if (isTaskReductionMod &&
5256 opInst, reductionInfo.getReductionDecls(),
5257 reductionInfo.getPrivateReductionVariables(), builder, allocaIP,
5258 moduleTranslation,
false))
5259 return llvm::createStringError(
5260 "failed to emit task reduction modifier initialization");
5265 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
5269 opInst.getRegion(),
"omp.par.region", builder, moduleTranslation);
5271 return regionBlock.takeError();
5274 if (opInst.getNumReductionVars() > 0) {
5279 owningReductionGenRefDataPtrGens;
5281 collectReductionInfo(builder, moduleTranslation, reductionInfo,
5282 owningReductionGens, owningAtomicReductionGens,
5283 owningReductionGenRefDataPtrGens, reductionInfos);
5286 builder.SetInsertPoint((*regionBlock)->getTerminator());
5290 if (isTaskReductionMod)
5295 llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
5296 builder.SetInsertPoint(tempTerminator);
5298 llvm::OpenMPIRBuilder::InsertPointOrErrorTy contInsertPoint =
5299 ompBuilder->createReductions(builder, allocaIP, reductionInfos,
5300 reductionInfo.getIsByRef(),
5303 if (!contInsertPoint)
5304 return contInsertPoint.takeError();
5306 if (!contInsertPoint->isValid())
5307 return llvm::make_error<PreviouslyReportedError>();
5309 tempTerminator->eraseFromParent();
5310 builder.restoreIP(*contInsertPoint);
5313 return llvm::Error::success();
5316 auto privCB = [](InsertPointTy allocaIP, InsertPointTy codeGenIP,
5317 llvm::Value &, llvm::Value &val, llvm::Value *&replVal) {
5326 auto finiCB = [&](InsertPointTy codeGenIP) -> llvm::Error {
5327 InsertPointTy oldIP = builder.saveIP();
5328 builder.restoreIP(codeGenIP);
5333 llvm::transform(reductionInfo.vars,
5334 std::back_inserter(reductionCleanupRegions),
5335 [](ReductionVarsInfo::VarInfo &var) {
5336 return &var.decl.getCleanupRegion();
5339 reductionCleanupRegions,
5340 reductionInfo.getPrivateReductionVariables(), moduleTranslation,
5341 builder,
"omp.reduction.cleanup")))
5342 return llvm::createStringError(
5343 "failed to inline `cleanup` region of `omp.declare_reduction`");
5346 opInst.getLoc(), privateVarsInfo)))
5347 return llvm::make_error<PreviouslyReportedError>();
5351 if (isCancellable) {
5352 auto IPOrErr = ompBuilder->createBarrier(
5353 llvm::OpenMPIRBuilder::LocationDescription(builder),
5354 llvm::omp::Directive::OMPD_unknown,
5358 return IPOrErr.takeError();
5361 builder.restoreIP(oldIP);
5362 return llvm::Error::success();
5365 llvm::Value *ifCond =
nullptr;
5366 if (
auto ifVar = opInst.getIfExpr())
5368 llvm::Value *numThreads =
nullptr;
5369 if (!opInst.getNumThreadsVars().empty())
5370 numThreads = moduleTranslation.
lookupValue(opInst.getNumThreads(0));
5371 auto pbKind = llvm::omp::OMP_PROC_BIND_default;
5372 if (
auto bind = opInst.getProcBindKind())
5376 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5378 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5380 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
5381 ompBuilder->createParallel(ompLoc, allocaIP, deallocBlocks, bodyGenCB,
5382 privCB, finiCB, ifCond, numThreads, pbKind,
5388 builder.restoreIP(*afterIP);
5393static llvm::omp::OrderKind
5396 return llvm::omp::OrderKind::OMP_ORDER_unknown;
5398 case omp::ClauseOrderKind::Concurrent:
5399 return llvm::omp::OrderKind::OMP_ORDER_concurrent;
5401 llvm_unreachable(
"Unknown ClauseOrderKind kind");
5409 auto simdOp = cast<omp::SimdOp>(opInst);
5414 PrivateVarsInfo privateVarsInfo(simdOp);
5415 privateVarsInfo.addLinearVars(simdOp);
5416 ReductionVarsInfo reductionInfo(simdOp);
5418 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5422 simdOp, builder, moduleTranslation, privateVarsInfo, allocaIP);
5440 LinearClauseProcessor linearClauseProcessor;
5441 if (linearClauseProcessor.initLinearIV(simdOp).failed())
5444 if (!simdOp.getLinearVars().empty()) {
5445 auto linearVarTypes = simdOp.getLinearVarTypes().value();
5447 linearClauseProcessor.registerType(moduleTranslation, linearVarType);
5448 for (
auto [idx, linearVar] : llvm::enumerate(simdOp.getLinearVars())) {
5449 size_t privIdx = privateVarsInfo.numPrivateVars + idx;
5450 linearClauseProcessor.createLinearVar(
5451 builder, allocaIP, privateVarsInfo.vars[privIdx].privatizer,
5453 privateVarsInfo.vars[privIdx].llvmVar, idx);
5455 for (
mlir::Value linearStep : simdOp.getLinearStepVars())
5456 linearClauseProcessor.initLinearStep(moduleTranslation, linearStep);
5459 assert(afterAllocas.get()->getSinglePredecessor());
5460 if (failed(initReductionVars(*simdOp, builder, moduleTranslation,
5461 afterAllocas.get()->getSinglePredecessor(),
5465 llvm::ConstantInt *simdlen =
nullptr;
5466 if (std::optional<uint64_t> simdlenVar = simdOp.getSimdlen())
5467 simdlen = builder.getInt64(simdlenVar.value());
5469 llvm::ConstantInt *safelen =
nullptr;
5470 if (std::optional<uint64_t> safelenVar = simdOp.getSafelen())
5471 safelen = builder.getInt64(safelenVar.value());
5476 llvm::BasicBlock *sourceBlock = builder.GetInsertBlock();
5477 std::optional<ArrayAttr> alignmentValues = simdOp.getAlignments();
5479 for (
size_t i = 0; i < operands.size(); ++i) {
5480 llvm::Value *alignment =
nullptr;
5481 llvm::Value *llvmVal = moduleTranslation.
lookupValue(operands[i]);
5482 llvm::Type *ty = llvmVal->getType();
5484 auto intAttr = cast<IntegerAttr>((*alignmentValues)[i]);
5485 alignment = builder.getInt64(intAttr.getInt());
5486 assert(ty->isPointerTy() &&
"Invalid type for aligned variable");
5487 assert(alignment &&
"Invalid alignment value");
5491 if (!intAttr.getValue().isPowerOf2())
5494 auto curInsert = builder.saveIP();
5495 builder.SetInsertPoint(sourceBlock);
5496 llvmVal = builder.CreateLoad(ty, llvmVal);
5497 builder.restoreIP(curInsert);
5498 alignedVars[llvmVal] = alignment;
5502 simdOp.getRegion(),
"omp.simd.region", builder, moduleTranslation);
5509 if (simdOp.getLinearVars().size()) {
5511 linearClauseProcessor.initLinearVar(builder, moduleTranslation,
5512 loopInfo->getPreheader()),
5516 if (failed(
handleError(linearClauseProcessor.updateLinearVar(
5517 builder, moduleTranslation, loopInfo->getBody(),
5518 loopInfo->getIndVar()),
5522 builder.SetInsertPoint((*regionBlock)->begin());
5524 ompBuilder->applySimd(loopInfo, alignedVars,
5526 ? moduleTranslation.
lookupValue(simdOp.getIfExpr())
5528 order, simdlen, safelen);
5531 linearClauseProcessor.updateLinearIV(builder, moduleTranslation),
5534 if (failed(
handleError(linearClauseProcessor.emitStoresForLinearVar(
5535 builder, moduleTranslation),
5543 for (
auto [i, var] : llvm::enumerate(reductionInfo.vars)) {
5544 OwningReductionGen gen =
5546 llvm::Value *originalVariable = moduleTranslation.
lookupValue(var.mlirVar);
5547 llvm::Type *reductionType =
5548 moduleTranslation.
convertType(var.decl.getType());
5552 llvm::Value *redValue = originalVariable;
5555 builder.CreateLoad(reductionType, redValue,
"red.value." + Twine(i));
5556 llvm::Value *privateRedValue = builder.CreateLoad(
5557 reductionType, var.privateVar,
"red.private.value." + Twine(i));
5558 llvm::Value *reduced;
5560 auto res = gen(builder.saveIP(), redValue, privateRedValue, reduced);
5563 builder.restoreIP(res.get());
5567 builder.CreateStore(reduced, originalVariable);
5572 llvm::transform(reductionInfo.vars, std::back_inserter(reductionRegions),
5573 [](ReductionVarsInfo::VarInfo &var) {
5574 return &var.decl.getCleanupRegion();
5577 reductionRegions, reductionInfo.getPrivateReductionVariables(),
5578 moduleTranslation, builder,
"omp.reduction.cleanup")))
5586static llvm::OpenMPIRBuilder::CollapseIVMapping
5588 using Mapping = llvm::OpenMPIRBuilder::CollapseIVMapping;
5589 if (isTargetDevice || loopOp.getCollapseNumLoops() != 2 ||
5590 disableVirtualCollapse)
5591 return Mapping::DivMod;
5592 auto wsloop = dyn_cast<omp::WsloopOp>(loopOp->getParentOp());
5593 if (!wsloop || isa<omp::LoopWrapperInterface>(wsloop->getParentOp()) ||
5594 wsloop.getScheduleKind().value_or(omp::ClauseScheduleKind::Static) !=
5595 omp::ClauseScheduleKind::Static ||
5596 wsloop.getScheduleChunk() || wsloop.getOrdered().has_value() ||
5597 !wsloop.getLinearVars().empty())
5598 return Mapping::DivMod;
5599 return Mapping::Virtual;
5607 auto loopOp = cast<omp::LoopNestOp>(opInst);
5613 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5618 auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip,
5619 llvm::Value *iv) -> llvm::Error {
5622 loopOp.getRegion().front().getArgument(loopInfos.size()), iv);
5627 bodyInsertPoints.push_back(ip);
5629 if (loopInfos.size() != loopOp.getNumLoops() - 1)
5630 return llvm::Error::success();
5633 builder.restoreIP(ip);
5635 loopOp.getRegion(),
"omp.loop_nest.region", builder, moduleTranslation);
5637 return regionBlock.takeError();
5639 builder.SetInsertPoint((*regionBlock)->begin());
5640 return llvm::Error::success();
5648 for (
unsigned i = 0, e = loopOp.getNumLoops(); i < e; ++i) {
5649 llvm::Value *lowerBound =
5650 moduleTranslation.
lookupValue(loopOp.getLoopLowerBounds()[i]);
5651 llvm::Value *upperBound =
5652 moduleTranslation.
lookupValue(loopOp.getLoopUpperBounds()[i]);
5653 llvm::Value *step = moduleTranslation.
lookupValue(loopOp.getLoopSteps()[i]);
5658 llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc;
5659 llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP;
5661 loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back(),
5663 computeIP = loopInfos.front()->getPreheaderIP();
5667 ompBuilder->createCanonicalLoop(
5668 loc, bodyGen, lowerBound, upperBound, step,
5669 true, loopOp.getLoopInclusive(), computeIP);
5674 loopInfos.push_back(*loopResult);
5677 llvm::OpenMPIRBuilder::InsertPointTy afterIP =
5678 loopInfos.front()->getAfterIP();
5681 if (
const auto &tiles = loopOp.getTileSizes()) {
5682 llvm::Type *ivType = loopInfos.front()->getIndVarType();
5685 for (
auto tile : tiles.value()) {
5686 llvm::Value *tileVal = llvm::ConstantInt::get(ivType,
tile);
5687 tileSizes.push_back(tileVal);
5690 std::vector<llvm::CanonicalLoopInfo *> newLoops =
5691 ompBuilder->tileLoops(ompLoc.DL, loopInfos, tileSizes);
5695 llvm::BasicBlock *afterBB = newLoops.front()->getAfter();
5696 llvm::BasicBlock *afterAfterBB = afterBB->getSingleSuccessor();
5697 afterIP = afterAfterBB->begin();
5701 for (
const auto &newLoop : newLoops)
5702 loopInfos.push_back(newLoop);
5706 const auto &numCollapse = loopOp.getCollapseNumLoops();
5708 loopInfos.begin(), loopInfos.begin() + (numCollapse));
5710 llvm::SaveAndRestore<llvm::OpenMPIRBuilder::CollapseIVMapping> mappingGuard(
5711 ompBuilder->Config.CollapseMapping,
5713 auto newTopLoopInfo =
5714 ompBuilder->collapseLoops(ompLoc.DL, collapseLoopInfos, {});
5716 assert(newTopLoopInfo &&
"New top loop information is missing");
5717 moduleTranslation.
stackWalk<OpenMPLoopInfoStackFrame>(
5718 [&](OpenMPLoopInfoStackFrame &frame) {
5719 frame.loopInfo = newTopLoopInfo;
5727 builder.restoreIP(afterIP);
5737 llvm::OpenMPIRBuilder::LocationDescription loopLoc(builder);
5738 Value loopIV = op.getInductionVar();
5739 Value loopTC = op.getTripCount();
5741 llvm::Value *llvmTC = moduleTranslation.
lookupValue(loopTC);
5744 ompBuilder->createCanonicalLoop(
5746 [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *llvmIV) {
5749 moduleTranslation.
mapValue(loopIV, llvmIV);
5751 builder.restoreIP(ip);
5756 return bodyGenStatus.takeError();
5758 llvmTC,
"omp.loop");
5760 return op.emitError(llvm::toString(llvmOrError.takeError()));
5762 llvm::CanonicalLoopInfo *llvmCLI = *llvmOrError;
5763 llvm::IRBuilderBase::InsertPoint afterIP = llvmCLI->getAfterIP();
5764 builder.restoreIP(afterIP);
5767 if (
Value cli = op.getCli())
5780 Value applyee = op.getApplyee();
5781 assert(applyee &&
"Loop to apply unrolling on required");
5783 llvm::CanonicalLoopInfo *consBuilderCLI =
5785 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5786 ompBuilder->unrollLoopHeuristic(loc.DL, consBuilderCLI);
5799 Value applyee = op.getApplyee();
5800 assert(applyee &&
"Loop to apply unrolling on required");
5802 llvm::CanonicalLoopInfo *consBuilderCLI =
5804 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5805 ompBuilder->unrollLoopFull(loc.DL, consBuilderCLI);
5818 Value applyee = op.getApplyee();
5819 assert(applyee &&
"Loop to apply unrolling on required");
5821 llvm::CanonicalLoopInfo *consBuilderCLI =
5823 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5827 int32_t factor =
static_cast<int32_t
>(op.getUnrollFactor());
5828 ompBuilder->unrollLoopPartial(loc.DL, consBuilderCLI, factor,
5837static LogicalResult
applyTile(omp::TileOp op, llvm::IRBuilderBase &builder,
5840 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5845 for (
Value size : op.getSizes()) {
5846 llvm::Value *translatedSize = moduleTranslation.
lookupValue(size);
5847 assert(translatedSize &&
5848 "sizes clause arguments must already be translated");
5849 translatedSizes.push_back(translatedSize);
5852 for (
Value applyee : op.getApplyees()) {
5853 llvm::CanonicalLoopInfo *consBuilderCLI =
5855 assert(applyee &&
"Canonical loop must already been translated");
5856 translatedLoops.push_back(consBuilderCLI);
5859 auto generatedLoops =
5860 ompBuilder->tileLoops(loc.DL, translatedLoops, translatedSizes);
5861 if (!op.getGeneratees().empty()) {
5862 for (
auto [mlirLoop,
genLoop] :
5863 zip_equal(op.getGeneratees(), generatedLoops))
5868 for (
Value applyee : op.getApplyees())
5876static LogicalResult
applyFuse(omp::FuseOp op, llvm::IRBuilderBase &builder,
5879 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5883 for (
size_t i = 0; i < op.getApplyees().size(); i++) {
5884 Value applyee = op.getApplyees()[i];
5885 llvm::CanonicalLoopInfo *consBuilderCLI =
5887 assert(applyee &&
"Canonical loop must already been translated");
5888 if (op.getFirst().has_value() && i < op.getFirst().value() - 1)
5889 beforeFuse.push_back(consBuilderCLI);
5890 else if (op.getCount().has_value() &&
5891 i >= op.getFirst().value() + op.getCount().value() - 1)
5892 afterFuse.push_back(consBuilderCLI);
5894 toFuse.push_back(consBuilderCLI);
5897 (op.getGeneratees().empty() ||
5898 beforeFuse.size() + afterFuse.size() + 1 == op.getGeneratees().size()) &&
5899 "Wrong number of generatees");
5902 auto generatedLoop = ompBuilder->fuseLoops(loc.DL, toFuse);
5903 if (!op.getGeneratees().empty()) {
5905 for (; i < beforeFuse.size(); i++)
5906 mapOmpLoop(moduleTranslation, op.getGeneratees()[i], beforeFuse[i]);
5907 mapOmpLoop(moduleTranslation, op.getGeneratees()[i++], generatedLoop);
5908 for (; i < afterFuse.size(); i++)
5909 mapOmpLoop(moduleTranslation, op.getGeneratees()[i], afterFuse[i]);
5913 for (
Value applyee : op.getApplyees())
5920static llvm::AtomicOrdering
5923 return llvm::AtomicOrdering::Monotonic;
5926 case omp::ClauseMemoryOrderKind::Seq_cst:
5927 return llvm::AtomicOrdering::SequentiallyConsistent;
5928 case omp::ClauseMemoryOrderKind::Acq_rel:
5929 return llvm::AtomicOrdering::AcquireRelease;
5930 case omp::ClauseMemoryOrderKind::Acquire:
5931 return llvm::AtomicOrdering::Acquire;
5932 case omp::ClauseMemoryOrderKind::Release:
5933 return llvm::AtomicOrdering::Release;
5934 case omp::ClauseMemoryOrderKind::Relaxed:
5935 return llvm::AtomicOrdering::Monotonic;
5937 llvm_unreachable(
"Unknown ClauseMemoryOrderKind kind");
5944static llvm::AtomicOrdering
5946 llvm::AtomicOrdering atomicOrdering) {
5947 if (atomicCompareOp.getFailMemoryOrder())
5949 return llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(atomicOrdering);
5956 auto readOp = cast<omp::AtomicReadOp>(opInst);
5961 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5964 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5967 llvm::Value *x = moduleTranslation.
lookupValue(readOp.getX());
5968 llvm::Value *v = moduleTranslation.
lookupValue(readOp.getV());
5970 llvm::Type *elementType =
5971 moduleTranslation.
convertType(readOp.getElementType());
5973 llvm::OpenMPIRBuilder::AtomicOpValue V = {v, elementType,
false,
false};
5974 llvm::OpenMPIRBuilder::AtomicOpValue X = {x, elementType,
false,
false};
5975 builder.restoreIP(ompBuilder->createAtomicRead(ompLoc, X, V, AO, allocaIP));
5983 auto writeOp = cast<omp::AtomicWriteOp>(opInst);
5988 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5991 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5993 llvm::Value *expr = moduleTranslation.
lookupValue(writeOp.getExpr());
5994 llvm::Value *dest = moduleTranslation.
lookupValue(writeOp.getX());
5995 llvm::Type *ty = moduleTranslation.
convertType(writeOp.getExpr().getType());
5996 llvm::OpenMPIRBuilder::AtomicOpValue x = {dest, ty,
false,
5999 ompBuilder->createAtomicWrite(ompLoc, x, expr, ao, allocaIP));
6007 .Case([&](LLVM::AddOp) {
return llvm::AtomicRMWInst::BinOp::Add; })
6008 .Case([&](LLVM::SubOp) {
return llvm::AtomicRMWInst::BinOp::Sub; })
6009 .Case([&](LLVM::AndOp) {
return llvm::AtomicRMWInst::BinOp::And; })
6010 .Case([&](LLVM::OrOp) {
return llvm::AtomicRMWInst::BinOp::Or; })
6011 .Case([&](LLVM::XOrOp) {
return llvm::AtomicRMWInst::BinOp::Xor; })
6012 .Case([&](LLVM::SMaxOp) {
return llvm::AtomicRMWInst::BinOp::Max; })
6013 .Case([&](LLVM::SMinOp) {
return llvm::AtomicRMWInst::BinOp::Min; })
6014 .Case([&](LLVM::UMaxOp) {
return llvm::AtomicRMWInst::BinOp::UMax; })
6015 .Case([&](LLVM::UMinOp) {
return llvm::AtomicRMWInst::BinOp::UMin; })
6016 .Case([&](LLVM::FAddOp) {
return llvm::AtomicRMWInst::BinOp::FAdd; })
6017 .Case([&](LLVM::FSubOp) {
return llvm::AtomicRMWInst::BinOp::FSub; })
6018 .Case([&](LLVM::MaxNumOp) {
return llvm::AtomicRMWInst::BinOp::FMax; })
6019 .Case([&](LLVM::MinNumOp) {
return llvm::AtomicRMWInst::BinOp::FMin; })
6021 [&](LLVM::MaximumOp) {
return llvm::AtomicRMWInst::BinOp::FMaximum; })
6023 [&](LLVM::MinimumOp) {
return llvm::AtomicRMWInst::BinOp::FMinimum; })
6024 .Default(llvm::AtomicRMWInst::BinOp::BAD_BINOP);
6027static llvm::omp::AtomicControl
6029 llvm::omp::AtomicControl ac;
6030 ac.IgnoreDenormalMode =
false;
6031 ac.FineGrainedMemory =
false;
6032 ac.RemoteMemory =
false;
6033 if (atomicUpdateOp && atomicUpdateOp.getAtomicControlAttr()) {
6034 mlir::omp::AtomicControlAttr atomicControlAttr =
6035 atomicUpdateOp.getAtomicControlAttr();
6036 ac.IgnoreDenormalMode = atomicControlAttr.getIgnoreDenormalMode();
6037 ac.FineGrainedMemory = atomicControlAttr.getFineGrainedMemory();
6038 ac.RemoteMemory = atomicControlAttr.getRemoteMemory();
6046 llvm::IRBuilderBase &builder,
6053 auto &innerOpList = opInst.getRegion().front().getOperations();
6054 bool isXBinopExpr{
false};
6055 llvm::AtomicRMWInst::BinOp binop;
6057 llvm::Value *llvmExpr =
nullptr;
6058 llvm::Value *llvmX =
nullptr;
6059 llvm::Type *llvmXElementType =
nullptr;
6060 if (innerOpList.size() == 2) {
6066 opInst.getRegion().getArgument(0))) {
6067 return opInst.emitError(
"no atomic update operation with region argument"
6068 " as operand found inside atomic.update region");
6071 isXBinopExpr = innerOp.
getOperand(0) == opInst.getRegion().getArgument(0);
6073 llvmExpr = moduleTranslation.
lookupValue(mlirExpr);
6077 binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
6079 llvmX = moduleTranslation.
lookupValue(opInst.getX());
6081 opInst.getRegion().getArgument(0).getType());
6082 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
6086 llvm::AtomicOrdering atomicOrdering =
6091 [&opInst, &moduleTranslation](
6092 llvm::Value *atomicx,
6095 moduleTranslation.
mapValue(*opInst.getRegion().args_begin(), atomicx);
6096 moduleTranslation.
mapBlock(&bb, builder.GetInsertBlock());
6097 if (failed(moduleTranslation.
convertBlock(bb,
true, builder)))
6098 return llvm::make_error<PreviouslyReportedError>();
6100 omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.
getTerminator());
6101 assert(yieldop && yieldop.getResults().size() == 1 &&
6102 "terminator must be omp.yield op and it must have exactly one "
6104 return moduleTranslation.
lookupValue(yieldop.getResults()[0]);
6110 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
6111 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
6112 ompBuilder->createAtomicUpdate(ompLoc, allocaIP, llvmAtomicX, llvmExpr,
6113 atomicOrdering, binop, updateFn,
6114 isXBinopExpr, atomicControl);
6119 builder.restoreIP(*afterIP);
6125static std::optional<llvm::omp::OMPAtomicCompareOp>
6127 switch (predicate) {
6128 case LLVM::ICmpPredicate::eq:
6129 return llvm::omp::OMPAtomicCompareOp::EQ;
6130 case LLVM::ICmpPredicate::slt:
6131 case LLVM::ICmpPredicate::ult:
6132 return llvm::omp::OMPAtomicCompareOp::MIN;
6133 case LLVM::ICmpPredicate::sgt:
6134 case LLVM::ICmpPredicate::ugt:
6135 return llvm::omp::OMPAtomicCompareOp::MAX;
6137 return std::nullopt;
6143static std::optional<llvm::omp::OMPAtomicCompareOp>
6145 switch (predicate) {
6146 case LLVM::FCmpPredicate::oeq:
6147 case LLVM::FCmpPredicate::ueq:
6148 return llvm::omp::OMPAtomicCompareOp::EQ;
6149 case LLVM::FCmpPredicate::olt:
6150 case LLVM::FCmpPredicate::ult:
6151 return llvm::omp::OMPAtomicCompareOp::MIN;
6152 case LLVM::FCmpPredicate::ogt:
6153 case LLVM::FCmpPredicate::ugt:
6154 return llvm::omp::OMPAtomicCompareOp::MAX;
6156 return std::nullopt;
6183 if (
auto extractOp = v.getDefiningOp<LLVM::ExtractValueOp>())
6184 return extractOp.getContainer();
6188 if (!isa<LLVM::AndOp, LLVM::OrOp>(op))
6192 if (!lhsFcmp || !rhsFcmp)
6194 mlir::Value lhsAgg0 = traceToAggregate(lhsFcmp.getOperand(0));
6195 mlir::Value lhsAgg1 = traceToAggregate(lhsFcmp.getOperand(1));
6196 bool lhsXIsOp0 = (lhsAgg0 == block.
getArgument(0));
6197 bool lhsXIsOp1 = (lhsAgg1 == block.
getArgument(0));
6198 if (!lhsXIsOp0 && !lhsXIsOp1)
6200 mlir::Value eAggregate = lhsXIsOp0 ? lhsAgg1 : lhsAgg0;
6204 result.isNE = isa<LLVM::OrOp>(op);
6205 result.eAggregate = eAggregate;
6206 result.isXBinopExpr = lhsXIsOp0;
6218 llvm::Value *llvmX, llvm::Type *complexTy,
6219 llvm::Value *eVal, llvm::Value *dVal,
6220 llvm::AtomicOrdering atomicOrdering,
6221 llvm::AtomicOrdering failOrdering,
6222 bool isWeak, llvm::Value *&oldComplex,
6223 llvm::Value *&cmpOk) {
6224 const llvm::DataLayout &DL = builder.getDataLayout();
6225 unsigned totalBits = DL.getTypeStoreSizeInBits(complexTy).getFixedValue();
6226 llvm::IntegerType *intTy =
6227 llvm::IntegerType::get(builder.getContext(), totalBits);
6228 llvm::Align complexAlign = DL.getABITypeAlign(complexTy);
6229 llvm::Align intAlign = DL.getABITypeAlign(intTy);
6230 llvm::Align maxAlign = std::max(complexAlign, intAlign);
6233 llvm::AllocaInst *dAlloca =
6234 builder.CreateAlloca(complexTy,
nullptr,
"cmplx.d");
6235 dAlloca->setAlignment(maxAlign);
6236 builder.CreateAlignedStore(dVal, dAlloca, maxAlign);
6238 builder.CreateAlignedLoad(intTy, dAlloca, maxAlign,
"cmplx.d.int");
6243 llvm::LoadInst *xCurr =
6244 builder.CreateAlignedLoad(intTy, llvmX, maxAlign,
"cmplx.x.load");
6245 xCurr->setAtomic(failOrdering);
6246 llvm::AllocaInst *xAlloca =
6247 builder.CreateAlloca(complexTy,
nullptr,
"cmplx.x");
6248 xAlloca->setAlignment(maxAlign);
6249 builder.CreateAlignedStore(xCurr, xAlloca, maxAlign);
6250 llvm::Value *xStruct =
6251 builder.CreateAlignedLoad(complexTy, xAlloca, maxAlign,
"cmplx.x.val");
6256 llvm::Value *reX = builder.CreateExtractValue(xStruct, 0);
6257 llvm::Value *imX = builder.CreateExtractValue(xStruct, 1);
6258 llvm::Value *reE = builder.CreateExtractValue(eVal, 0);
6259 llvm::Value *imE = builder.CreateExtractValue(eVal, 1);
6260 llvm::Value *reEq = builder.CreateFCmpOEQ(reX, reE,
"cmplx.re.eq");
6261 llvm::Value *imEq = builder.CreateFCmpOEQ(imX, imE,
"cmplx.im.eq");
6262 llvm::Value *fpEqual = builder.CreateAnd(reEq, imEq,
"cmplx.eq");
6267 llvm::BasicBlock *curBB = builder.GetInsertBlock();
6268 llvm::Function *fn = curBB->getParent();
6269 llvm::BasicBlock *swapBB =
6270 llvm::BasicBlock::Create(builder.getContext(),
"cmplx.atomic.swap", fn);
6271 llvm::BasicBlock *exitBB =
6272 llvm::BasicBlock::Create(builder.getContext(),
"cmplx.atomic.exit", fn);
6273 builder.CreateCondBr(fpEqual, swapBB, exitBB);
6275 builder.SetInsertPoint(swapBB);
6276 llvm::AtomicCmpXchgInst *cmpXchg = builder.CreateAtomicCmpXchg(
6277 llvmX, xCurr, dInt, maxAlign, atomicOrdering, failOrdering);
6278 cmpXchg->setWeak(isWeak);
6279 llvm::Value *oldSwap = builder.CreateExtractValue(cmpXchg, 0);
6280 llvm::Value *okSwap = builder.CreateExtractValue(cmpXchg, 1);
6281 builder.CreateBr(exitBB);
6284 builder.SetInsertPoint(exitBB);
6285 llvm::PHINode *oldIntPHI = builder.CreatePHI(intTy, 2,
"cmplx.old.int");
6286 oldIntPHI->addIncoming(oldSwap, swapBB);
6287 oldIntPHI->addIncoming(xCurr, curBB);
6288 llvm::PHINode *okPHI = builder.CreatePHI(builder.getInt1Ty(), 2,
"cmplx.ok");
6289 okPHI->addIncoming(okSwap, swapBB);
6290 okPHI->addIncoming(builder.getFalse(), curBB);
6293 llvm::AllocaInst *oldAlloca =
6294 builder.CreateAlloca(complexTy,
nullptr,
"cmplx.old");
6295 oldAlloca->setAlignment(maxAlign);
6296 builder.CreateAlignedStore(oldIntPHI, oldAlloca, maxAlign);
6297 oldComplex = builder.CreateAlignedLoad(complexTy, oldAlloca, maxAlign,
6305 llvm::omp::OMPAtomicCompareOp
compareOp = llvm::omp::OMPAtomicCompareOp::EQ;
6325 return atomicCompareOp.emitError(
6326 "unsupported comparison predicate (NE) for complex atomic compare");
6327 info.
compareOp = llvm::omp::OMPAtomicCompareOp::EQ;
6329 info.
eVal = materializeValue(cplx.eAggregate);
6331 if (
auto selectOp = dyn_cast<LLVM::SelectOp>(op)) {
6332 info.
dVal = materializeValue(selectOp.getTrueValue());
6342 if (
auto icmpOp = dyn_cast<LLVM::ICmpOp>(op);
6343 icmpOp && icmpOp.getOperand(0) != block.
getArgument(0) &&
6349 .Case<LLVM::ICmpOp>([&](LLVM::ICmpOp icmpOp) -> LogicalResult {
6353 return atomicCompareOp.emitError(
6354 "unsupported comparison predicate in atomic compare");
6356 LLVM::ICmpPredicate pred = icmpOp.getPredicate();
6357 info.
isSigned = (pred == LLVM::ICmpPredicate::slt ||
6358 pred == LLVM::ICmpPredicate::sgt ||
6359 pred == LLVM::ICmpPredicate::sle ||
6360 pred == LLVM::ICmpPredicate::sge);
6364 : icmpOp.getOperand(0);
6365 info.
eVal = materializeValue(eOperand);
6368 .Case<LLVM::FCmpOp>([&](LLVM::FCmpOp fcmpOp) -> LogicalResult {
6372 return atomicCompareOp.emitError(
6373 "unsupported comparison predicate in atomic compare");
6378 : fcmpOp.getOperand(0);
6379 info.
eVal = materializeValue(eOperand);
6382 .Case<LLVM::SelectOp>([&](LLVM::SelectOp selectOp) {
6384 info.
dVal = materializeValue(selectOp.getTrueValue());
6387 .Case<mlir::arith::MaxSIOp, mlir::arith::MinSIOp,
6388 mlir::arith::MaxUIOp, mlir::arith::MinUIOp,
6389 mlir::arith::MaximumFOp, mlir::arith::MinimumFOp,
6390 LLVM::SMaxOp, LLVM::SMinOp, LLVM::UMaxOp, LLVM::UMinOp,
6391 LLVM::MaxNumOp, LLVM::MinNumOp>([&](
Operation *) {
6396 bool isMax = isa<mlir::arith::MaxSIOp, mlir::arith::MaxUIOp,
6397 mlir::arith::MaximumFOp, LLVM::SMaxOp,
6398 LLVM::UMaxOp, LLVM::MaxNumOp>(op);
6399 info.
compareOp = isMax ? llvm::omp::OMPAtomicCompareOp::MIN
6400 : llvm::omp::OMPAtomicCompareOp::MAX;
6401 info.
isSigned = isa<mlir::arith::MaxSIOp, mlir::arith::MinSIOp,
6402 LLVM::SMaxOp, LLVM::SMinOp>(op);
6406 info.
eVal = materializeValue(eOperand);
6420 llvm::IRBuilderBase &builder,
6426 omp::AtomicUpdateOp atomicUpdateOp = atomicCaptureOp.getAtomicUpdateOp();
6427 omp::AtomicWriteOp atomicWriteOp = atomicCaptureOp.getAtomicWriteOp();
6428 omp::AtomicCompareOp atomicCompareOp = atomicCaptureOp.getAtomicCompareOp();
6432 if (atomicCompareOp) {
6433 omp::AtomicReadOp atomicReadOp = atomicCaptureOp.getAtomicReadOp();
6434 assert(atomicReadOp &&
"expected atomic.read in capture+compare");
6436 Region ®ion = atomicCompareOp.getRegion();
6439 llvm::Type *llvmXElementType =
6441 llvm::Value *llvmX = moduleTranslation.
lookupValue(atomicCompareOp.getX());
6442 llvm::Value *llvmV = moduleTranslation.
lookupValue(atomicReadOp.getV());
6444 bool isSigned =
false;
6445 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {
6446 llvmX, llvmXElementType, isSigned,
false};
6447 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicV = {
6448 llvmV, llvmXElementType,
false,
false};
6449 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicR = {
nullptr,
nullptr,
false,
6452 llvm::AtomicOrdering atomicOrdering =
6456 auto isAtomicComparePatternOp = [](
Operation &op) {
6457 return llvm::isa<LLVM::ICmpOp, LLVM::FCmpOp, LLVM::SelectOp, LLVM::AndOp,
6458 LLVM::OrOp, LLVM::SMaxOp, LLVM::SMinOp, LLVM::UMaxOp,
6459 LLVM::UMinOp, LLVM::MaxNumOp, LLVM::MinNumOp,
6460 mlir::arith::MaxSIOp, mlir::arith::MinSIOp,
6461 mlir::arith::MaxUIOp, mlir::arith::MinUIOp,
6462 mlir::arith::MaximumFOp, mlir::arith::MinimumFOp>(op);
6465 if (isAtomicComparePatternOp(op))
6467 bool allOperandsMapped =
6469 return moduleTranslation.lookupValue(v) != nullptr;
6471 if (!allOperandsMapped)
6474 return atomicCompareOp.emitError(
6475 "failed to translate operation inside atomic compare region");
6478 auto materializeValue = [&](
mlir::Value val) -> llvm::Value * {
6479 if (llvm::Value *existing = moduleTranslation.
lookupValue(val))
6481 if (
auto loadOp = val.getDefiningOp<LLVM::LoadOp>()) {
6482 if (loadOp->getParentRegion() == ®ion) {
6483 llvm::Value *loadAddr =
6487 llvm::Type *loadType =
6488 moduleTranslation.
convertType(loadOp.getResult().getType());
6489 return builder.CreateLoad(loadType, loadAddr);
6498 atomicCompareOp, patternInfo)))
6501 llvm::omp::OMPAtomicCompareOp compareOp = patternInfo.
compareOp;
6502 llvm::Value *eVal = patternInfo.
eVal;
6503 llvm::Value *dVal = patternInfo.
dVal;
6508 return atomicCompareOp.emitError(
6509 "failed to extract expected value (e) from atomic compare region");
6512 if (yieldOp.getResults().empty())
6513 return atomicCompareOp.emitError(
6514 "failed to extract desired value (d) from atomic compare region");
6515 dVal = materializeValue(yieldOp.getResults()[0]);
6518 llvmAtomicX.IsSigned = isSigned;
6520 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
6521 bool isReadFirst = isa<omp::AtomicReadOp>(atomicCaptureOp.getFirstOp());
6522 bool isPostfixCapture = !isReadFirst;
6523 bool isFailOnly = atomicCaptureOp.getFailOnly();
6531 if (llvmXElementType->isStructTy()) {
6532 llvm::Value *oldComplex =
nullptr;
6533 llvm::Value *cmpOk =
nullptr;
6534 llvm::AtomicOrdering failOrdering =
6537 atomicOrdering, failOrdering,
6538 atomicCompareOp.getWeak(), oldComplex, cmpOk);
6542 llvm::Value *cmpFailed = builder.CreateNot(cmpOk);
6543 llvm::BasicBlock *curBB = builder.GetInsertBlock();
6544 llvm::Function *fn = curBB->getParent();
6545 llvm::BasicBlock *contBB = llvm::BasicBlock::Create(
6546 builder.getContext(),
"omp.atomic.cont", fn);
6547 llvm::BasicBlock *exitBB = llvm::BasicBlock::Create(
6548 builder.getContext(),
"omp.atomic.exit", fn);
6549 builder.CreateCondBr(cmpFailed, contBB, exitBB);
6550 builder.SetInsertPoint(contBB);
6551 builder.CreateStore(oldComplex, llvmAtomicV.Var,
6552 llvmAtomicV.IsVolatile);
6553 builder.CreateBr(exitBB);
6554 builder.SetInsertPoint(exitBB);
6555 }
else if (isPostfixCapture) {
6557 llvm::Value *newComplex = builder.CreateSelect(cmpOk, dVal, oldComplex);
6558 builder.CreateStore(newComplex, llvmAtomicV.Var,
6559 llvmAtomicV.IsVolatile);
6562 builder.CreateStore(oldComplex, llvmAtomicV.Var,
6563 llvmAtomicV.IsVolatile);
6575 bool isMinMax = compareOp != llvm::omp::OMPAtomicCompareOp::EQ;
6577 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicVForCall = llvmAtomicV;
6584 bool minMaxManualCapture = isMinMax && (isPostfixCapture || isFailOnly);
6585 bool eqPostfixManualCapture = !isMinMax && isPostfixCapture && !isFailOnly;
6586 if (minMaxManualCapture || eqPostfixManualCapture)
6587 llvmAtomicVForCall = {
nullptr,
nullptr,
false,
false};
6591 bool builderFailOnly = isFailOnly && !isMinMax;
6598 bool isPostfixUpdate = !builderFailOnly;
6600 bool isWeak = atomicCompareOp.getWeak();
6601 bool savedHandleFPNegZero = ompBuilder->setHandleFPNegZero(
true);
6602 llvm::AtomicOrdering failureOrdering =
6604 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
6605 ompBuilder->createAtomicCompare(
6606 ompLoc, llvmAtomicX, llvmAtomicVForCall, llvmAtomicR, eVal, dVal,
6607 atomicOrdering, compareOp, isXBinopExpr, isPostfixUpdate,
6608 builderFailOnly, failureOrdering, isWeak);
6609 ompBuilder->setHandleFPNegZero(savedHandleFPNegZero);
6611 if (failed(
handleError(afterIP, *atomicCaptureOp)))
6614 builder.restoreIP(*afterIP);
6623 if (isMinMax && (isPostfixCapture || isFailOnly)) {
6624 llvm::BasicBlock *curBB = builder.GetInsertBlock();
6625 llvm::AtomicRMWInst *rmw =
nullptr;
6626 for (
auto &inst : llvm::reverse(*curBB)) {
6627 if (
auto *r = dyn_cast<llvm::AtomicRMWInst>(&inst)) {
6632 assert(rmw &&
"expected atomicrmw for min/max compare capture");
6633 llvm::Value *oldVal = rmw;
6634 llvm::Value *rhs = rmw->getValOperand();
6640 llvm::CmpInst::Predicate updatePred;
6641 switch (rmw->getOperation()) {
6642 case llvm::AtomicRMWInst::Min:
6643 updatePred = llvm::CmpInst::ICMP_SGT;
6645 case llvm::AtomicRMWInst::Max:
6646 updatePred = llvm::CmpInst::ICMP_SLT;
6648 case llvm::AtomicRMWInst::UMin:
6649 updatePred = llvm::CmpInst::ICMP_UGT;
6651 case llvm::AtomicRMWInst::UMax:
6652 updatePred = llvm::CmpInst::ICMP_ULT;
6654 case llvm::AtomicRMWInst::FMin:
6655 updatePred = llvm::CmpInst::FCMP_OGT;
6657 case llvm::AtomicRMWInst::FMax:
6658 updatePred = llvm::CmpInst::FCMP_OLT;
6662 "unexpected atomicrmw op for min/max compare capture");
6664 llvm::Value *updated = builder.CreateCmp(updatePred, oldVal, rhs);
6665 llvm::Value *failed = builder.CreateNot(updated);
6666 llvm::Function *fn = curBB->getParent();
6667 llvm::BasicBlock *contBB = llvm::BasicBlock::Create(
6668 builder.getContext(),
"omp.atomic.cont", fn);
6669 llvm::BasicBlock *exitBB = llvm::BasicBlock::Create(
6670 builder.getContext(),
"omp.atomic.exit", fn);
6671 builder.CreateCondBr(failed, contBB, exitBB);
6672 builder.SetInsertPoint(contBB);
6673 builder.CreateStore(oldVal, llvmAtomicV.Var, llvmAtomicV.IsVolatile);
6674 builder.CreateBr(exitBB);
6675 builder.SetInsertPoint(exitBB);
6677 llvm::Intrinsic::ID id;
6678 switch (rmw->getOperation()) {
6679 case llvm::AtomicRMWInst::Min:
6680 id = llvm::Intrinsic::smin;
6682 case llvm::AtomicRMWInst::Max:
6683 id = llvm::Intrinsic::smax;
6685 case llvm::AtomicRMWInst::UMin:
6686 id = llvm::Intrinsic::umin;
6688 case llvm::AtomicRMWInst::UMax:
6689 id = llvm::Intrinsic::umax;
6691 case llvm::AtomicRMWInst::FMin:
6692 id = llvm::Intrinsic::minnum;
6694 case llvm::AtomicRMWInst::FMax:
6695 id = llvm::Intrinsic::maxnum;
6699 "unexpected atomicrmw op for min/max compare capture");
6701 llvm::Value *newVal = builder.CreateBinaryIntrinsic(
id, oldVal, rhs);
6702 builder.CreateStore(newVal, llvmAtomicV.Var, llvmAtomicV.IsVolatile);
6708 if (!isMinMax && isPostfixCapture && !isFailOnly) {
6709 llvm::BasicBlock *curBB = builder.GetInsertBlock();
6710 llvm::Value *oldVal =
nullptr;
6711 llvm::Value *successVal =
nullptr;
6715 for (
auto &inst : llvm::reverse(*curBB)) {
6716 if (isa<llvm::AtomicCmpXchgInst>(&inst)) {
6717 oldVal = builder.CreateExtractValue(&inst, 0);
6718 successVal = builder.CreateExtractValue(&inst, 1);
6729 for (
auto &inst : *curBB) {
6730 auto *phi = dyn_cast<llvm::PHINode>(&inst);
6733 if (phi->getType()->isIntegerTy(1))
6736 for (
auto &inst : *curBB) {
6737 if (
auto *bc = dyn_cast<llvm::BitCastInst>(&inst)) {
6744 assert(oldVal &&
"expected cmpxchg or PHI+bitcast for compare capture");
6745 assert(successVal &&
"expected success flag for compare capture");
6746 llvm::Value *newVal = builder.CreateSelect(successVal, dVal, oldVal);
6747 builder.CreateStore(newVal, llvmAtomicV.Var, llvmAtomicV.IsVolatile);
6754 bool isXBinopExpr =
false, isPostfixUpdate =
false;
6755 llvm::AtomicRMWInst::BinOp binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
6757 assert((atomicUpdateOp || atomicWriteOp) &&
6758 "internal op must be an atomic.update or atomic.write op");
6760 if (atomicWriteOp) {
6761 isPostfixUpdate =
true;
6762 mlirExpr = atomicWriteOp.getExpr();
6764 isPostfixUpdate = atomicCaptureOp.getSecondOp() ==
6765 atomicCaptureOp.getAtomicUpdateOp().getOperation();
6766 auto &innerOpList = atomicUpdateOp.getRegion().front().getOperations();
6769 if (innerOpList.size() == 2) {
6772 atomicUpdateOp.getRegion().getArgument(0))) {
6773 return atomicUpdateOp.emitError(
6774 "no atomic update operation with region argument"
6775 " as operand found inside atomic.update region");
6779 innerOp.
getOperand(0) == atomicUpdateOp.getRegion().getArgument(0);
6782 binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
6786 llvm::Value *llvmExpr = moduleTranslation.
lookupValue(mlirExpr);
6787 llvm::Value *llvmX =
6788 moduleTranslation.
lookupValue(atomicCaptureOp.getAtomicReadOp().getX());
6789 llvm::Value *llvmV =
6790 moduleTranslation.
lookupValue(atomicCaptureOp.getAtomicReadOp().getV());
6791 llvm::Type *llvmXElementType = moduleTranslation.
convertType(
6792 atomicCaptureOp.getAtomicReadOp().getElementType());
6793 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
6796 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicV = {llvmV, llvmXElementType,
6800 llvm::AtomicOrdering atomicOrdering =
6804 [&](llvm::Value *atomicx,
6807 return moduleTranslation.
lookupValue(atomicWriteOp.getExpr());
6808 Block &bb = *atomicUpdateOp.getRegion().
begin();
6809 moduleTranslation.
mapValue(*atomicUpdateOp.getRegion().args_begin(),
6811 moduleTranslation.
mapBlock(&bb, builder.GetInsertBlock());
6812 if (failed(moduleTranslation.
convertBlock(bb,
true, builder)))
6813 return llvm::make_error<PreviouslyReportedError>();
6815 omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.
getTerminator());
6816 assert(yieldop && yieldop.getResults().size() == 1 &&
6817 "terminator must be omp.yield op and it must have exactly one "
6819 return moduleTranslation.
lookupValue(yieldop.getResults()[0]);
6822 llvm::omp::AtomicControl atomicControl =
6826 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
6827 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
6828 ompBuilder->createAtomicCapture(
6829 ompLoc, allocaIP, llvmAtomicX, llvmAtomicV, llvmExpr, atomicOrdering,
6830 binop, updateFn, atomicUpdateOp, isPostfixUpdate, isXBinopExpr,
6833 if (failed(
handleError(afterIP, *atomicCaptureOp)))
6836 builder.restoreIP(*afterIP);
6858 llvm::IRBuilderBase &builder,
6864 Region ®ion = atomicCompareOp.getRegion();
6868 llvm::Type *llvmXElementType =
6870 if (!llvmXElementType)
6871 return atomicCompareOp.emitError(
6872 "unable to determine element type for atomic compare");
6874 llvm::Value *llvmX = moduleTranslation.
lookupValue(atomicCompareOp.getX());
6879 bool isSigned =
false;
6880 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
6884 llvm::AtomicOrdering atomicOrdering =
6887 auto isAtomicComparePatternOp = [](
Operation &op) {
6888 return llvm::isa<LLVM::ICmpOp, LLVM::FCmpOp, LLVM::SelectOp, LLVM::AndOp,
6889 LLVM::OrOp, LLVM::SMaxOp, LLVM::SMinOp, LLVM::UMaxOp,
6890 LLVM::UMinOp, LLVM::MaxNumOp, LLVM::MinNumOp,
6891 mlir::arith::MaxSIOp, mlir::arith::MinSIOp,
6892 mlir::arith::MaxUIOp, mlir::arith::MinUIOp,
6893 mlir::arith::MaximumFOp, mlir::arith::MinimumFOp>(op);
6913 if (isAtomicComparePatternOp(op))
6918 return moduleTranslation.lookupValue(v) != nullptr;
6920 if (!allOperandsMapped)
6924 return atomicCompareOp.emitError(
6925 "failed to translate operation inside atomic compare region");
6930 auto materializeValue = [&](
mlir::Value val) -> llvm::Value * {
6932 if (llvm::Value *existing = moduleTranslation.
lookupValue(val))
6936 if (
auto loadOp = val.getDefiningOp<LLVM::LoadOp>()) {
6937 if (loadOp->getParentRegion() == ®ion) {
6938 llvm::Value *loadAddr = moduleTranslation.
lookupValue(loadOp.getAddr());
6941 llvm::Type *loadType =
6942 moduleTranslation.
convertType(loadOp.getResult().getType());
6943 return builder.CreateLoad(loadType, loadAddr);
6951 llvm::omp::OMPAtomicCompareOp compareOp = llvm::omp::OMPAtomicCompareOp::EQ;
6952 llvm::Value *eVal =
nullptr;
6953 llvm::Value *dVal =
nullptr;
6954 bool isXBinopExpr =
false;
6960 if (isComplexPattern) {
6963 return atomicCompareOp.emitError(
6964 "unsupported comparison predicate (NE) for complex atomic compare");
6965 compareOp = llvm::omp::OMPAtomicCompareOp::EQ;
6970 if (isComplexPattern) {
6973 if (
auto selectOp = dyn_cast<LLVM::SelectOp>(op)) {
6974 dVal = materializeValue(selectOp.getTrueValue());
6980 if (yieldOp.getResults().empty())
6981 return atomicCompareOp.emitError(
6982 "failed to extract desired value (d) from atomic compare region");
6983 dVal = materializeValue(yieldOp.getResults()[0]);
6986 llvm::Value *oldComplex =
nullptr;
6987 llvm::Value *cmpOk =
nullptr;
6988 llvm::AtomicOrdering failOrdering =
6991 atomicOrdering, failOrdering,
6992 atomicCompareOp.getWeak(), oldComplex, cmpOk);
7000 atomicCompareOp, patternInfo)))
7003 eVal = patternInfo.
eVal;
7004 dVal = patternInfo.
dVal;
7010 return atomicCompareOp.emitError(
7011 "failed to extract expected value (e) from atomic compare region");
7015 if (yieldOp.getResults().empty())
7016 return atomicCompareOp.emitError(
7017 "failed to extract desired value (d) from atomic compare region");
7018 dVal = materializeValue(yieldOp.getResults()[0]);
7021 llvmAtomicX.IsSigned = isSigned;
7023 llvm::OpenMPIRBuilder::AtomicOpValue vOpVal = {
nullptr,
nullptr,
false,
7025 llvm::OpenMPIRBuilder::AtomicOpValue rOpVal = {
nullptr,
nullptr,
false,
7027 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
7029 bool isWeak = atomicCompareOp.getWeak();
7031 bool savedHandleFPNegZero = ompBuilder->setHandleFPNegZero(
true);
7032 llvm::AtomicOrdering failureOrdering =
7034 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
7035 ompBuilder->createAtomicCompare(
7036 ompLoc, llvmAtomicX, vOpVal, rOpVal, eVal, dVal, atomicOrdering,
7037 compareOp, isXBinopExpr,
false,
7038 false, failureOrdering, isWeak);
7039 ompBuilder->setHandleFPNegZero(savedHandleFPNegZero);
7041 if (failed(
handleError(afterIP, *atomicCompareOp)))
7044 builder.restoreIP(*afterIP);
7049 omp::ClauseCancellationConstructType directive) {
7050 switch (directive) {
7051 case omp::ClauseCancellationConstructType::Loop:
7052 return llvm::omp::Directive::OMPD_for;
7053 case omp::ClauseCancellationConstructType::Parallel:
7054 return llvm::omp::Directive::OMPD_parallel;
7055 case omp::ClauseCancellationConstructType::Sections:
7056 return llvm::omp::Directive::OMPD_sections;
7057 case omp::ClauseCancellationConstructType::Taskgroup:
7058 return llvm::omp::Directive::OMPD_taskgroup;
7060 llvm_unreachable(
"Unhandled cancellation construct type");
7069 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
7072 llvm::Value *ifCond =
nullptr;
7073 if (
Value ifVar = op.getIfExpr())
7076 llvm::omp::Directive cancelledDirective =
7079 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
7080 ompBuilder->createCancel(ompLoc, ifCond, cancelledDirective);
7082 if (failed(
handleError(afterIP, *op.getOperation())))
7085 builder.restoreIP(afterIP.get());
7092 llvm::IRBuilderBase &builder,
7097 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
7100 llvm::omp::Directive cancelledDirective =
7103 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
7104 ompBuilder->createCancellationPoint(ompLoc, cancelledDirective);
7106 if (failed(
handleError(afterIP, *op.getOperation())))
7109 builder.restoreIP(afterIP.get());
7119 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
7121 auto threadprivateOp = cast<omp::ThreadprivateOp>(opInst);
7126 Value symAddr = threadprivateOp.getSymAddr();
7129 if (
auto asCast = dyn_cast<LLVM::AddrSpaceCastOp>(symOp))
7132 if (!isa<LLVM::AddressOfOp>(symOp))
7133 return opInst.
emitError(
"Addressing symbol not found");
7134 LLVM::AddressOfOp addressOfOp = dyn_cast<LLVM::AddressOfOp>(symOp);
7136 LLVM::GlobalOp global =
7137 addressOfOp.getGlobal(moduleTranslation.
symbolTable());
7138 llvm::GlobalValue *globalValue = moduleTranslation.
lookupGlobal(global);
7139 llvm::Type *type = globalValue->getValueType();
7140 llvm::TypeSize typeSize = builder.getDataLayout().getTypeStoreSize(type);
7141 llvm::ConstantInt *size = builder.getInt64(typeSize.getFixedValue());
7142 llvm::Value *callInst = ompBuilder->createCachedThreadPrivate(
7143 ompLoc, globalValue, size, global.getSymName() +
".cache");
7149static llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseKind
7151 switch (deviceClause) {
7152 case mlir::omp::DeclareTargetDeviceType::host:
7153 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseHost;
7155 case mlir::omp::DeclareTargetDeviceType::nohost:
7156 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNoHost;
7158 case mlir::omp::DeclareTargetDeviceType::any:
7159 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseAny;
7162 llvm_unreachable(
"unhandled device clause");
7165static llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind
7167 mlir::omp::DeclareTargetCaptureClause captureClause) {
7168 switch (captureClause) {
7169 case mlir::omp::DeclareTargetCaptureClause::to:
7170 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;
7171 case mlir::omp::DeclareTargetCaptureClause::link:
7172 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink;
7173 case mlir::omp::DeclareTargetCaptureClause::enter:
7174 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter;
7175 case mlir::omp::DeclareTargetCaptureClause::none:
7176 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryNone;
7178 llvm_unreachable(
"unhandled capture clause");
7183 if (
auto addrCast = dyn_cast_if_present<LLVM::AddrSpaceCastOp>(op))
7185 if (
auto addressOfOp = dyn_cast_if_present<LLVM::AddressOfOp>(op)) {
7186 auto modOp = addressOfOp->getParentOfType<mlir::ModuleOp>();
7187 return modOp.lookupSymbol(addressOfOp.getGlobalName());
7194 if (
auto addrCast = dyn_cast_if_present<LLVM::AddrSpaceCastOp>(op))
7195 value = addrCast.getOperand();
7219 if (!llvmVarTy->isPointerTy())
7223 if (
auto gop = dyn_cast<LLVM::GlobalOp>(globalOp))
7224 return moduleTranslation.
convertType(gop.getGlobalType());
7227 dyn_cast_if_present<LLVM::AllocaOp>(baseVar.
getDefiningOp()))
7228 return moduleTranslation.
convertType(allocaOp.getElemType());
7230 if (llvm::Value *baseLlvm = moduleTranslation.
lookupValue(baseVar))
7231 if (
auto *allocaInst = dyn_cast<llvm::AllocaInst>(baseLlvm))
7232 return allocaInst->getAllocatedType();
7241 llvm::IRBuilderBase &builder,
const llvm::DataLayout &dataLayout) {
7243 dyn_cast_if_present<LLVM::AllocaOp>(baseVar.
getDefiningOp())) {
7244 if (
Value arraySize = allocaOp.getArraySize()) {
7245 llvm::Type *elemTy =
7246 moduleTranslation.
convertType(allocaOp.getElemType());
7247 llvm::Value *numElems = moduleTranslation.
lookupValue(arraySize);
7248 if (!numElems->getType()->isIntegerTy(64))
7249 numElems = builder.CreateZExt(numElems, builder.getInt64Ty());
7250 uint64_t elemSize = dataLayout.getTypeAllocSize(elemTy).getFixedValue();
7251 return builder.CreateMul(numElems, builder.getInt64(elemSize));
7254 if (llvm::Value *baseLlvm = moduleTranslation.
lookupValue(baseVar)) {
7255 if (
auto *allocaInst = dyn_cast<llvm::AllocaInst>(baseLlvm)) {
7256 if (allocaInst->isArrayAllocation() &&
7257 !llvm::isa<llvm::ArrayType>(allocaInst->getAllocatedType())) {
7259 dataLayout.getTypeAllocSize(allocaInst->getAllocatedType())
7261 return builder.CreateMul(allocaInst->getArraySize(),
7262 builder.getInt64(elemSize));
7266 return std::nullopt;
7269static llvm::SmallString<64>
7271 llvm::OpenMPIRBuilder &ompBuilder,
7272 llvm::vfs::FileSystem &vfs) {
7274 llvm::raw_svector_ostream os(suffix);
7277 auto fileInfoCallBack = [&loc]() {
7278 return std::pair<std::string, uint64_t>(
7279 llvm::StringRef(loc.getFilename()), loc.getLine());
7284 ompBuilder.getTargetEntryUniqueInfo(fileInfoCallBack, vfs).FileID);
7286 os <<
"_decl_tgt_ref_ptr";
7292 if (
auto declareTargetGlobal =
7293 dyn_cast_if_present<omp::DeclareTargetInterface>(
7295 omp::DeclareTargetAttr declareTargetAttr =
7296 declareTargetGlobal.getDeclareTarget();
7297 if (declareTargetAttr && declareTargetAttr.getCaptureClause() ==
7298 omp::DeclareTargetCaptureClause::link)
7305 if (
auto declareTargetGlobal =
7306 dyn_cast_if_present<omp::DeclareTargetInterface>(
7308 omp::DeclareTargetAttr declareTargetAttr =
7309 declareTargetGlobal.getDeclareTarget();
7310 if (declareTargetAttr && (declareTargetAttr.getCaptureClause() ==
7311 omp::DeclareTargetCaptureClause::to ||
7312 declareTargetAttr.getCaptureClause() ==
7313 omp::DeclareTargetCaptureClause::enter))
7332 ompBuilder->Config.hasRequiresUnifiedSharedMemory())) {
7336 if (gOp.getSymName().contains(suffix))
7341 (gOp.getSymName().str() + suffix.str()).str());
7349struct MapInfosTy : llvm::OpenMPIRBuilder::MapInfosTy {
7350 SmallVector<Operation *, 4> Mappers;
7353 void append(MapInfosTy &curInfo) {
7354 Mappers.append(curInfo.Mappers.begin(), curInfo.Mappers.end());
7355 llvm::OpenMPIRBuilder::MapInfosTy::append(curInfo);
7364struct MapInfoData : MapInfosTy {
7365 llvm::SmallVector<bool, 4> IsDeclareTarget;
7366 llvm::SmallVector<bool, 4> IsAMember;
7368 llvm::SmallVector<bool, 4> IsAMapping;
7369 llvm::SmallVector<mlir::Operation *, 4> MapClause;
7370 llvm::SmallVector<llvm::Value *, 4> OriginalValue;
7373 llvm::SmallVector<llvm::Type *, 4> BaseType;
7376 void append(MapInfoData &CurInfo) {
7377 IsDeclareTarget.append(CurInfo.IsDeclareTarget.begin(),
7378 CurInfo.IsDeclareTarget.end());
7379 MapClause.append(CurInfo.MapClause.begin(), CurInfo.MapClause.end());
7380 OriginalValue.append(CurInfo.OriginalValue.begin(),
7381 CurInfo.OriginalValue.end());
7382 BaseType.append(CurInfo.BaseType.begin(), CurInfo.BaseType.end());
7383 MapInfosTy::append(CurInfo);
7387enum class TargetDirectiveEnumTy : uint32_t {
7391 TargetEnterData = 3,
7396static TargetDirectiveEnumTy getTargetDirectiveEnumTyFromOp(Operation *op) {
7397 return llvm::TypeSwitch<Operation *, TargetDirectiveEnumTy>(op)
7398 .Case([](omp::TargetDataOp) {
return TargetDirectiveEnumTy::TargetData; })
7399 .Case([](omp::TargetEnterDataOp) {
7400 return TargetDirectiveEnumTy::TargetEnterData;
7402 .Case([&](omp::TargetExitDataOp) {
7403 return TargetDirectiveEnumTy::TargetExitData;
7405 .Case([&](omp::TargetUpdateOp) {
7406 return TargetDirectiveEnumTy::TargetUpdate;
7408 .Case([&](omp::TargetOp) {
return TargetDirectiveEnumTy::Target; })
7409 .Default([&](Operation *op) {
return TargetDirectiveEnumTy::None; });
7415 if (
auto nestedArrTy = llvm::dyn_cast_if_present<LLVM::LLVMArrayType>(
7416 arrTy.getElementType()))
7430 if (mapOp.getVarPtrPtr())
7447 return bitEnumContainsAll(mapType, omp::ClauseMapFlags::priv |
7448 omp::ClauseMapFlags::target_param |
7449 omp::ClauseMapFlags::attach);
7464 llvm::Value *basePointer,
7465 llvm::Type *baseType,
7466 llvm::IRBuilderBase &builder,
7468 if (
auto memberClause =
7469 mlir::dyn_cast_if_present<mlir::omp::MapInfoOp>(clauseOp)) {
7474 if (!memberClause.getBounds().empty()) {
7475 llvm::Value *elementCount = builder.getInt64(1);
7476 for (
auto bounds : memberClause.getBounds()) {
7477 if (
auto boundOp = mlir::dyn_cast_if_present<mlir::omp::MapBoundsOp>(
7478 bounds.getDefiningOp())) {
7483 elementCount = builder.CreateMul(
7487 moduleTranslation.
lookupValue(boundOp.getUpperBound()),
7488 moduleTranslation.
lookupValue(boundOp.getLowerBound())),
7489 builder.getInt64(1)));
7496 if (
auto arrTy = llvm::dyn_cast_if_present<LLVM::LLVMArrayType>(type))
7504 llvm::Value *sizeCalc = builder.CreateMul(
7505 elementCount, builder.getInt64(underlyingTypeSzInBits / 8),
7543 return builder.CreateSelect(
7544 builder.CreateICmpEQ(sizeCalc, builder.getInt64(0)),
7545 builder.getInt64(1), sizeCalc);
7559static llvm::omp::OpenMPOffloadMappingFlags
7561 const bool hasExplicitMap =
7562 (mlirFlags &
~omp::ClauseMapFlags::is_device_ptr) !=
7563 omp::ClauseMapFlags::none;
7565 llvm::omp::OpenMPOffloadMappingFlags mapType =
7566 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
7568 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::to))
7569 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TO;
7571 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::from))
7572 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_FROM;
7574 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::always))
7575 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS;
7577 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::del))
7578 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_DELETE;
7580 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::return_param))
7581 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
7583 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::priv))
7584 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PRIVATE;
7586 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::literal))
7587 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
7589 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::implicit))
7590 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT;
7592 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::close))
7593 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_CLOSE;
7595 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::present))
7596 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PRESENT;
7598 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::ompx_hold))
7599 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_OMPX_HOLD;
7601 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::attach))
7602 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH;
7604 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::target_param))
7605 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
7607 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::is_device_ptr)) {
7608 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
7609 if (!hasExplicitMap)
7610 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
7617 if (StringAttr name = mapOp.getNameAttr())
7618 return name.getValue();
7626 ArrayRef<Value> useDevAddrOperands = {},
7627 ArrayRef<Value> hasDevAddrOperands = {}) {
7629 auto checkRefPtrOrPteeMapWithAttach = [](omp::ClauseMapFlags mapType) {
7631 bitEnumContainsAll(mapType, omp::ClauseMapFlags::ref_ptr) ||
7632 bitEnumContainsAll(mapType, omp::ClauseMapFlags::ref_ptee);
7633 return hasRefType &&
7634 bitEnumContainsAll(mapType, omp::ClauseMapFlags::attach);
7637 auto checkIsAMember = [](
const auto &mapVars,
auto mapOp) {
7645 for (Value mapValue : mapVars) {
7646 auto map = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
7647 for (
auto member : map.getMembers())
7648 if (member == mapOp)
7655 for (Value mapValue : mapVars) {
7656 auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
7657 bool isAttachStyleMap =
7658 checkRefPtrOrPteeMapWithAttach(mapOp.getMapType()) ||
7660 Value offloadPtr = (mapOp.getVarPtrPtr() && !isAttachStyleMap)
7661 ? mapOp.getVarPtrPtr()
7662 : mapOp.getVarPtr();
7663 mapData.OriginalValue.push_back(moduleTranslation.
lookupValue(offloadPtr));
7664 mapData.Pointers.push_back(
7665 isAttachStyleMap ? moduleTranslation.
lookupValue(mapOp.getVarPtrPtr())
7666 : mapData.OriginalValue.back());
7668 if (llvm::Value *refPtr =
7670 mapData.IsDeclareTarget.push_back(
true);
7671 mapData.BasePointers.push_back(refPtr);
7673 mapData.IsDeclareTarget.push_back(
true);
7674 mapData.BasePointers.push_back(mapData.OriginalValue.back());
7676 mapData.IsDeclareTarget.push_back(
false);
7677 mapData.BasePointers.push_back(mapData.OriginalValue.back());
7683 mapData.BaseType.push_back(moduleTranslation.
convertType(
7684 mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtrType().value()
7685 : mapOp.getVarPtrType()));
7692 mlir::Type sizeType = (isAttachStyleMap || !mapOp.getVarPtrPtr())
7693 ? mapOp.getVarPtrType()
7694 : mapOp.getVarPtrPtrType().value();
7696 dl, sizeType, isAttachStyleMap ?
nullptr : mapOp,
7697 mapData.Pointers.back(), moduleTranslation.
convertType(sizeType),
7698 builder, moduleTranslation));
7699 mapData.MapClause.push_back(mapOp.getOperation());
7702 mapData.HasAttachPtr.push_back(
false);
7706 mapData.DevicePointers.push_back(llvm::OpenMPIRBuilder::DeviceInfoTy::None);
7707 if (mapOp.getMapperId())
7708 mapData.Mappers.push_back(
7710 mapOp, mapOp.getMapperIdAttr()));
7712 mapData.Mappers.push_back(
nullptr);
7713 mapData.IsAMapping.push_back(
true);
7714 mapData.IsAMember.push_back(checkIsAMember(mapVars, mapOp));
7717 auto findMapInfo = [&mapData](llvm::Value *val,
7718 llvm::OpenMPIRBuilder::DeviceInfoTy devInfoTy,
7719 size_t memberCount) {
7722 for (llvm::Value *basePtr : mapData.OriginalValue) {
7723 auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[index]);
7734 (mapData.Types[index] &
7735 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH) ==
7736 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH;
7737 if (!isAttachMap && basePtr == val && mapData.IsAMapping[index] &&
7738 memberCount == mapOp.getMembers().size()) {
7740 mapData.Types[index] |=
7741 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
7742 mapData.DevicePointers[index] = devInfoTy;
7750 auto addDevInfos = [&](
const llvm::ArrayRef<Value> &useDevOperands,
7751 llvm::OpenMPIRBuilder::DeviceInfoTy devInfoTy) {
7752 for (Value mapValue : useDevOperands) {
7753 auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
7755 mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
7756 llvm::Value *origValue = moduleTranslation.
lookupValue(offloadPtr);
7759 if (!findMapInfo(origValue, devInfoTy, mapOp.getMembers().size())) {
7760 mapData.OriginalValue.push_back(origValue);
7761 mapData.Pointers.push_back(mapData.OriginalValue.back());
7762 mapData.IsDeclareTarget.push_back(
false);
7763 mapData.BasePointers.push_back(mapData.OriginalValue.back());
7764 mlir::Type baseTy = mapOp.getVarPtrPtr()
7765 ? mapOp.getVarPtrPtrType().value()
7766 : mapOp.getVarPtrType();
7767 mapData.BaseType.push_back(moduleTranslation.
convertType(baseTy));
7768 mapData.Sizes.push_back(builder.getInt64(0));
7769 mapData.MapClause.push_back(mapOp.getOperation());
7770 mapData.Types.push_back(
7771 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM);
7773 mapData.HasAttachPtr.push_back(
false);
7777 mapData.DevicePointers.push_back(devInfoTy);
7778 mapData.Mappers.push_back(
nullptr);
7779 mapData.IsAMapping.push_back(
false);
7780 mapData.IsAMember.push_back(checkIsAMember(useDevOperands, mapOp));
7785 addDevInfos(useDevAddrOperands, llvm::OpenMPIRBuilder::DeviceInfoTy::Address);
7786 addDevInfos(useDevPtrOperands, llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer);
7788 for (Value mapValue : hasDevAddrOperands) {
7789 auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
7791 mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
7792 llvm::Value *origValue = moduleTranslation.
lookupValue(offloadPtr);
7794 auto mapTypeAlways = llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS;
7796 (mapOp.getMapType() & omp::ClauseMapFlags::is_device_ptr) !=
7797 omp::ClauseMapFlags::none;
7799 mapData.OriginalValue.push_back(origValue);
7800 mapData.BasePointers.push_back(origValue);
7801 mapData.Pointers.push_back(origValue);
7802 mapData.IsDeclareTarget.push_back(
false);
7804 mlir::Type baseTy = mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtrType().value()
7805 : mapOp.getVarPtrType();
7806 mapData.BaseType.push_back(moduleTranslation.
convertType(baseTy));
7807 mapData.Sizes.push_back(builder.getInt64(dl.
getTypeSize(baseTy)));
7809 mapData.MapClause.push_back(mapOp.getOperation());
7810 if (llvm::to_underlying(mapType & mapTypeAlways)) {
7814 mapData.Types.push_back(mapType);
7816 mapData.HasAttachPtr.push_back(
false);
7820 if (mapOp.getMapperId()) {
7821 mapData.Mappers.push_back(
7823 mapOp, mapOp.getMapperIdAttr()));
7825 mapData.Mappers.push_back(
nullptr);
7830 mapData.Types.push_back(
7831 isDevicePtr ? mapType
7832 : llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL);
7834 mapData.HasAttachPtr.push_back(
false);
7835 mapData.Mappers.push_back(
nullptr);
7840 mapData.DevicePointers.push_back(
7841 isDevicePtr ? llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer
7842 : llvm::OpenMPIRBuilder::DeviceInfoTy::Address);
7843 mapData.IsAMapping.push_back(
false);
7844 mapData.IsAMember.push_back(checkIsAMember(hasDevAddrOperands, mapOp));
7849 auto *res = llvm::find(mapData.MapClause, memberOp);
7850 assert(res != mapData.MapClause.end() &&
7851 "MapInfoOp for member not found in MapData, cannot return index");
7852 return std::distance(mapData.MapClause.begin(), res);
7856 omp::MapInfoOp mapInfo,
bool first =
true) {
7857 ArrayAttr indexAttr = mapInfo.getMembersIndexAttr();
7867 auto memberIndicesA = cast<ArrayAttr>(indexAttr[a]);
7868 auto memberIndicesB = cast<ArrayAttr>(indexAttr[b]);
7870 for (auto it : llvm::zip(memberIndicesA, memberIndicesB)) {
7871 int64_t aIndex = mlir::cast<IntegerAttr>(std::get<0>(it)).getInt();
7872 int64_t bIndex = mlir::cast<IntegerAttr>(std::get<1>(it)).getInt();
7874 if (aIndex == bIndex)
7877 if (aIndex < bIndex)
7880 if (aIndex > bIndex)
7887 bool memberAParent = memberIndicesA.size() < memberIndicesB.size();
7889 occludedChildren.push_back(
b);
7891 occludedChildren.push_back(a);
7892 return memberAParent;
7895 for (
auto v : occludedChildren)
7902 ArrayAttr indexAttr = mapInfo.getMembersIndexAttr();
7904 if (indexAttr.size() == 1)
7905 return cast<omp::MapInfoOp>(mapInfo.getMembers()[0].getDefiningOp());
7909 return llvm::cast<omp::MapInfoOp>(
7910 mapInfo.getMembers()[
indices.front()].getDefiningOp());
7933static std::vector<llvm::Value *>
7935 llvm::IRBuilderBase &builder,
bool isArrayTy,
7937 std::vector<llvm::Value *> idx;
7938 isByteOffset =
false;
7949 idx.push_back(builder.getInt64(0));
7950 for (
int i = bounds.size() - 1; i >= 0; --i) {
7951 if (
auto boundOp = dyn_cast_if_present<omp::MapBoundsOp>(
7952 bounds[i].getDefiningOp())) {
7953 idx.push_back(moduleTranslation.
lookupValue(boundOp.getLowerBound()));
7958 llvm::Value *offset = builder.getInt64(0);
7959 for (
Value bound : bounds) {
7961 dyn_cast_if_present<omp::MapBoundsOp>(bound.getDefiningOp());
7962 if (!boundOp || !boundOp.getStride())
7967 isByteOffset = boundOp.getStrideInBytes();
7970 for (
Value bound : bounds) {
7972 dyn_cast_if_present<omp::MapBoundsOp>(bound.getDefiningOp());
7973 if (!boundOp || !boundOp.getStride())
7988 moduleTranslation.
lookupValue(boundOp.getLowerBound());
7989 llvm::Value *stride =
7990 moduleTranslation.
lookupValue(boundOp.getStride());
7991 offset = builder.CreateAdd(offset, builder.CreateMul(lb, stride));
7993 idx.push_back(offset);
7995 for (
int i = bounds.size() - 1; i >= 0; --i) {
7996 if (
auto boundOp = dyn_cast_if_present<omp::MapBoundsOp>(
7997 bounds[i].getDefiningOp())) {
8010 if (i == ((
int)bounds.size() - 1))
8012 moduleTranslation.
lookupValue(boundOp.getLowerBound()));
8014 idx.back() = builder.CreateAdd(
8015 builder.CreateMul(idx.back(), moduleTranslation.
lookupValue(
8016 boundOp.getExtent())),
8017 moduleTranslation.
lookupValue(boundOp.getLowerBound()));
8027 llvm::transform(values, std::back_inserter(ints), [](
Attribute value) {
8028 return cast<IntegerAttr>(value).getInt();
8036 omp::MapInfoOp parentOp) {
8038 if (parentOp.getMembers().empty())
8042 if (parentOp.getMembers().size() == 1) {
8043 overlapMapDataIdxs.push_back(0);
8047 ArrayAttr indexAttr = parentOp.getMembersIndexAttr();
8048 size_t numMembers = indexAttr.size();
8052 for (
auto [i, indicesAttr] : llvm::enumerate(indexAttr))
8053 getAsIntegers(cast<ArrayAttr>(indicesAttr), memberIndices[i]);
8059 llvm::SmallDenseSet<size_t> skipIndices;
8060 for (
size_t i = 0; i < numMembers; ++i) {
8061 const auto &iIndices = memberIndices[i];
8062 for (
size_t j = 0;
j < numMembers; ++
j) {
8065 const auto &jIndices = memberIndices[
j];
8067 if (jIndices.size() < iIndices.size() &&
8068 std::equal(jIndices.begin(), jIndices.end(), iIndices.begin())) {
8069 skipIndices.insert(i);
8076 for (
size_t i = 0; i < numMembers; ++i)
8077 if (!skipIndices.contains(i))
8078 overlapMapDataIdxs.push_back(i);
8089 llvm::IRBuilderBase &builder,
8090 MapInfoData &mapData,
size_t mapDataIdx,
8091 MapInfosTy &combinedInfo) {
8092 auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[mapDataIdx]);
8093 if (mapOp.getBounds().empty() || mapOp.getMapperId() ||
8094 mapOp->getParentOfType<omp::DeclareMapperOp>() ||
8095 bitEnumContainsAll(mapOp.getMapType(), omp::ClauseMapFlags::attach))
8098 llvm::Type *elementType = mapData.BaseType[mapDataIdx];
8103 while (
auto *arrayType = dyn_cast<llvm::ArrayType>(elementType)) {
8104 arrayExtents.push_back(arrayType->getNumElements());
8105 elementType = arrayType->getElementType();
8107 llvm::Value *elementSize = builder.getInt64(
8108 builder.GetInsertBlock()->getModule()->getDataLayout().getTypeAllocSize(
8113 llvm::OpenMPIRBuilder::MapValuesArrayTy offsets{builder.getInt64(0)};
8114 llvm::OpenMPIRBuilder::MapValuesArrayTy counts{elementSize};
8115 llvm::OpenMPIRBuilder::MapValuesArrayTy strides{builder.getInt64(1)};
8116 llvm::Value *sourceStride = elementSize;
8117 llvm::Value *contiguousSize = elementSize;
8120 bool isContiguous =
true;
8121 for (
auto [dim, bound] : llvm::enumerate(mapOp.getBounds())) {
8122 auto bounds = cast<omp::MapBoundsOp>(bound.getDefiningOp());
8123 auto getInt64 = [&](
Value value) {
8124 return builder.CreateSExtOrTrunc(moduleTranslation.
lookupValue(value),
8125 builder.getInt64Ty());
8127 llvm::Value *lower = bounds.getLowerBound()
8128 ? getInt64(bounds.getLowerBound())
8129 : builder.getInt64(0);
8130 llvm::Value *count = builder.CreateAdd(
8131 builder.CreateSub(getInt64(bounds.getUpperBound()), lower),
8132 builder.getInt64(1));
8134 builder.CreateSelect(builder.CreateICmpSGT(count, builder.getInt64(0)),
8135 count, builder.getInt64(0));
8136 llvm::Value *stride = sourceStride;
8137 if (bounds.getStrideInBytes() && bounds.getStride())
8138 stride = getInt64(bounds.getStride());
8139 else if (arrayExtents.empty() && bounds.getStride())
8140 stride = builder.CreateMul(getInt64(bounds.getStride()), elementSize);
8141 offsets.push_back(builder.CreateMul(lower, stride));
8142 counts.push_back(count);
8143 strides.push_back(stride);
8144 isContiguous &= stride == contiguousSize;
8145 contiguousSize = builder.CreateMul(contiguousSize, count);
8150 if (dim < arrayExtents.size())
8151 sourceStride = builder.CreateMul(
8153 builder.getInt64(arrayExtents[arrayExtents.size() - dim - 1]));
8154 else if (bounds.getExtent())
8156 builder.CreateMul(sourceStride, getInt64(bounds.getExtent()));
8161 llvm::Value *base = mapData.OriginalValue[mapDataIdx];
8162 if (mapOp.getVarPtrPtr())
8163 base = builder.CreateLoad(builder.getPtrTy(), base);
8166 counts[1] = builder.CreateSelect(builder.CreateIsNull(base),
8167 builder.getInt64(0), counts[1]);
8170 combinedInfo.BasePointers.back() = base;
8171 combinedInfo.Types.back() |=
8172 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG;
8173 auto &nonContig = combinedInfo.NonContigInfo;
8174 nonContig.IsNonContiguous =
true;
8175 nonContig.Dims.resize(combinedInfo.Types.size(), 1);
8176 nonContig.Dims.back() = counts.size();
8177 nonContig.Offsets.push_back(std::move(offsets));
8178 nonContig.Counts.push_back(std::move(counts));
8179 nonContig.Strides.push_back(std::move(strides));
8193 llvm::OpenMPIRBuilder &ompBuilder, MapInfoData &mapData,
size_t mapDataIdx,
8194 MapInfosTy &combinedInfo, TargetDirectiveEnumTy targetDirective,
8195 llvm::omp::OpenMPOffloadMappingFlags memberOfFlag =
8196 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE,
8197 bool isTargetParam =
true,
int mapDataParentIdx = -1) {
8198 auto mapFlag = mapData.Types[mapDataIdx];
8199 auto mapInfoOp = llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIdx]);
8203 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH) ==
8204 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
8210 if (isTargetParam &&
8211 (targetDirective == TargetDirectiveEnumTy::Target &&
8212 !mapData.IsDeclareTarget[mapDataIdx]) &&
8214 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
8216 if (mapInfoOp.getMapCaptureType() == omp::VariableCaptureKind::ByCopy &&
8218 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
8227 if (memberOfFlag != llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE) {
8228 if (!isPtrTy && !isAttachMap)
8229 ompBuilder.setCorrectMemberOfFlag(mapFlag, memberOfFlag);
8236 mapFlag &=
~llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
8246 if (isPtrTy && !isAttachMap && mapData.IsDeclareTarget[mapDataIdx])
8247 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ;
8256 !bitEnumContainsAll(mapInfoOp.getMapType(),
8257 omp::ClauseMapFlags::ref_ptr) &&
8258 bitEnumContainsAll(mapInfoOp.getMapType(), omp::ClauseMapFlags::ref_ptee);
8259 bool isRefPtrPtee = bitEnumContainsAll(mapInfoOp.getMapType(),
8260 omp::ClauseMapFlags::ref_ptr |
8261 omp::ClauseMapFlags::ref_ptee);
8263 if (!mapInfoOp->getParentOfType<omp::DeclareMapperOp>() &&
8264 mapDataParentIdx >= 0 && !(isRefPtee || (isRefPtrPtee && isPtrTy))) {
8265 combinedInfo.BasePointers.emplace_back(
8266 mapData.BasePointers[mapDataParentIdx]);
8268 combinedInfo.BasePointers.emplace_back(mapData.BasePointers[mapDataIdx]);
8271 combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIdx]);
8272 combinedInfo.DevicePointers.emplace_back(
8273 memberOfFlag != llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE
8274 ? llvm::OpenMPIRBuilder::DeviceInfoTy::None
8275 : mapData.DevicePointers[mapDataIdx]);
8276 combinedInfo.Mappers.emplace_back(mapData.Mappers[mapDataIdx]);
8277 combinedInfo.Names.emplace_back(mapData.Names[mapDataIdx]);
8278 combinedInfo.Types.emplace_back(mapFlag);
8280 combinedInfo.HasAttachPtr.emplace_back(
false);
8284 combinedInfo.Sizes.emplace_back(
8286 ? builder.CreateSelect(
8287 builder.CreateIsNull(mapData.Pointers[mapDataIdx]),
8288 builder.getInt64(0), mapData.Sizes[mapDataIdx])
8289 : mapData.Sizes[mapDataIdx]);
8290 if (targetDirective == TargetDirectiveEnumTy::TargetUpdate)
8312 llvm::OpenMPIRBuilder &ompBuilder,
DataLayout &dl, MapInfosTy &combinedInfo,
8313 MapInfoData &mapData, uint64_t mapDataIndex,
8314 llvm::omp::OpenMPOffloadMappingFlags memberOfFlag,
8315 TargetDirectiveEnumTy targetDirective) {
8316 using MapFlags = llvm::omp::OpenMPOffloadMappingFlags;
8317 assert(!ompBuilder.Config.isTargetDevice() &&
8318 "function only supported for host device codegen");
8320 llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
8321 auto *parentMapper = mapData.Mappers[mapDataIndex];
8327 MapFlags baseFlag = (targetDirective == TargetDirectiveEnumTy::Target &&
8328 !mapData.IsDeclareTarget[mapDataIndex])
8329 ? MapFlags::OMP_MAP_TARGET_PARAM
8330 : MapFlags::OMP_MAP_NONE;
8336 MapFlags parentFlags = mapData.Types[mapDataIndex];
8337 MapFlags preserve = MapFlags::OMP_MAP_TO | MapFlags::OMP_MAP_FROM |
8338 MapFlags::OMP_MAP_ALWAYS | MapFlags::OMP_MAP_CLOSE |
8339 MapFlags::OMP_MAP_PRESENT |
8340 MapFlags::OMP_MAP_OMPX_HOLD |
8341 MapFlags::OMP_MAP_IMPLICIT;
8342 baseFlag |= (parentFlags & preserve);
8344 MapFlags parentFlags = mapData.Types[mapDataIndex];
8345 MapFlags preserve = MapFlags::OMP_MAP_TO | MapFlags::OMP_MAP_FROM |
8346 MapFlags::OMP_MAP_PRESENT |
8347 MapFlags::OMP_MAP_RETURN_PARAM |
8348 MapFlags::OMP_MAP_IMPLICIT;
8349 baseFlag |= (parentFlags & preserve);
8352 combinedInfo.Types.emplace_back(baseFlag);
8354 combinedInfo.HasAttachPtr.emplace_back(
false);
8355 combinedInfo.DevicePointers.emplace_back(
8356 mapData.DevicePointers[mapDataIndex]);
8360 combinedInfo.Mappers.emplace_back(
8361 parentMapper && !parentClause.getPartialMap() ? parentMapper :
nullptr);
8363 mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder,
8365 combinedInfo.BasePointers.emplace_back(mapData.BasePointers[mapDataIndex]);
8374 llvm::Value *lowAddr, *highAddr;
8375 if (!parentClause.getPartialMap()) {
8376 lowAddr = builder.CreatePointerCast(mapData.Pointers[mapDataIndex],
8377 builder.getPtrTy());
8378 highAddr = builder.CreatePointerCast(
8379 builder.CreateConstGEP1_32(mapData.BaseType[mapDataIndex],
8380 mapData.Pointers[mapDataIndex], 1),
8381 builder.getPtrTy());
8382 combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIndex]);
8384 auto mapOp = dyn_cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
8387 lowAddr = builder.CreatePointerCast(mapData.BasePointers[firstMemberIdx],
8388 builder.getPtrTy());
8392 auto lastMemberMapInfo =
8393 cast<omp::MapInfoOp>(mapData.MapClause[lastMemberIdx]);
8402 bool isRefPteeMap = bitEnumContainsAll(lastMemberMapInfo.getMapType(),
8403 omp::ClauseMapFlags::ref_ptee) &&
8404 !bitEnumContainsAll(lastMemberMapInfo.getMapType(),
8405 omp::ClauseMapFlags::ref_ptr);
8406 llvm::Type *castType = mapData.BaseType[lastMemberIdx];
8409 moduleTranslation.
convertType(lastMemberMapInfo.getVarPtrType());
8410 highAddr = builder.CreatePointerCast(
8411 builder.CreateGEP(castType, mapData.BasePointers[lastMemberIdx],
8412 builder.getInt64(1)),
8413 builder.getPtrTy());
8414 combinedInfo.Pointers.emplace_back(mapData.BasePointers[firstMemberIdx]);
8417 llvm::Value *size = builder.CreateIntCast(
8418 builder.CreatePtrDiff(builder.getInt8Ty(), highAddr, lowAddr),
8419 builder.getInt64Ty(),
8421 combinedInfo.Sizes.push_back(size);
8429 if (!parentClause.getPartialMap()) {
8434 MapFlags mapFlag = mapData.Types[mapDataIndex];
8435 bool hasMapClose = (MapFlags(mapFlag) & MapFlags::OMP_MAP_CLOSE) ==
8436 MapFlags::OMP_MAP_CLOSE;
8437 ompBuilder.setCorrectMemberOfFlag(mapFlag, memberOfFlag);
8453 if (targetDirective == TargetDirectiveEnumTy::TargetUpdate || hasMapClose ||
8454 overlapIdxs.size() == 1) {
8455 combinedInfo.Types.emplace_back(mapFlag);
8457 combinedInfo.HasAttachPtr.emplace_back(
false);
8458 combinedInfo.DevicePointers.emplace_back(
8459 mapData.DevicePointers[mapDataIndex]);
8461 mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder,
8463 cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]))));
8464 combinedInfo.BasePointers.emplace_back(
8465 mapData.BasePointers[mapDataIndex]);
8466 combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIndex]);
8467 combinedInfo.Sizes.emplace_back(mapData.Sizes[mapDataIndex]);
8468 combinedInfo.Mappers.emplace_back(
nullptr);
8474 lowAddr = builder.CreatePointerCast(mapData.Pointers[mapDataIndex],
8475 builder.getPtrTy());
8476 highAddr = builder.CreatePointerCast(
8477 builder.CreateConstGEP1_32(mapData.BaseType[mapDataIndex],
8478 mapData.Pointers[mapDataIndex], 1),
8479 builder.getPtrTy());
8486 mapFlag &=
~llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
8493 for (
auto v : overlapIdxs) {
8496 cast<omp::MapInfoOp>(parentClause.getMembers()[v].getDefiningOp()));
8498 llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataOverlapIdx]));
8499 combinedInfo.Types.emplace_back(mapFlag);
8501 combinedInfo.HasAttachPtr.emplace_back(
false);
8502 combinedInfo.DevicePointers.emplace_back(
8503 llvm::OpenMPIRBuilder::DeviceInfoTy::None);
8505 mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder,
8507 cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]))));
8508 combinedInfo.BasePointers.emplace_back(
8509 mapData.BasePointers[mapDataIndex]);
8510 combinedInfo.Mappers.emplace_back(
nullptr);
8511 combinedInfo.Pointers.emplace_back(lowAddr);
8512 auto sizeCalc = builder.CreateIntCast(
8513 builder.CreatePtrDiff(builder.getInt8Ty(),
8514 mapData.OriginalValue[mapDataOverlapIdx],
8516 builder.getInt64Ty(),
true);
8521 llvm::DataLayout dataLayout = builder.getDataLayout();
8522 auto sizeSel = builder.CreateSelect(
8523 builder.CreateICmpNE(builder.getInt64(0), sizeCalc), sizeCalc,
8524 isPtrMap ? builder.getInt64(dataLayout.getPointerSize())
8525 : mapData.Sizes[mapDataOverlapIdx]);
8526 combinedInfo.Sizes.emplace_back(sizeSel);
8527 lowAddr = builder.CreateConstGEP1_32(
8528 isPtrMap ? builder.getPtrTy() : mapData.BaseType[mapDataOverlapIdx],
8529 mapData.BasePointers[mapDataOverlapIdx], 1);
8532 combinedInfo.Types.emplace_back(mapFlag);
8534 combinedInfo.HasAttachPtr.emplace_back(
false);
8535 combinedInfo.DevicePointers.emplace_back(
8536 llvm::OpenMPIRBuilder::DeviceInfoTy::None);
8538 mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder,
8540 cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]))));
8541 combinedInfo.BasePointers.emplace_back(
8542 mapData.BasePointers[mapDataIndex]);
8543 combinedInfo.Mappers.emplace_back(
nullptr);
8544 combinedInfo.Pointers.emplace_back(lowAddr);
8545 combinedInfo.Sizes.emplace_back(builder.CreateIntCast(
8546 builder.CreatePtrDiff(builder.getInt8Ty(), highAddr, lowAddr),
8547 builder.getInt64Ty(),
true));
8553 llvm::IRBuilderBase &builder,
8554 llvm::OpenMPIRBuilder &ompBuilder,
8556 MapInfoData &mapData, uint64_t mapDataIndex,
8557 TargetDirectiveEnumTy targetDirective) {
8558 assert(!ompBuilder.Config.isTargetDevice() &&
8559 "function only supported for host device codegen");
8562 llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
8567 if (parentClause.getMembers().size() == 1 && parentClause.getPartialMap()) {
8568 auto memberClause = llvm::cast<omp::MapInfoOp>(
8569 parentClause.getMembers()[0].getDefiningOp());
8582 moduleTranslation, builder, ompBuilder, mapData, memberDataIdx,
8583 combinedInfo, targetDirective,
8584 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE,
8585 true, mapDataIndex);
8589 auto collectMapInfoIdxs =
8592 llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
8594 for (
auto member : parentClause.getMembers())
8596 mapData, llvm::cast<omp::MapInfoOp>(member.getDefiningOp())));
8600 collectMapInfoIdxs(mapInfoIdx);
8602 llvm::omp::OpenMPOffloadMappingFlags memberOfFlag =
8603 ompBuilder.getMemberOfFlag(combinedInfo.Types.size());
8613 bool parentIsPrivatizeableAttach =
8615 for (
auto [i, idx] : llvm::enumerate(mapInfoIdx)) {
8616 bool emitParentMap = i == 0 && !parentIsPrivatizeableAttach;
8617 if (emitParentMap) {
8619 combinedInfo, mapData, idx, memberOfFlag,
8623 moduleTranslation, builder, ompBuilder, mapData, idx, combinedInfo,
8625 parentIsPrivatizeableAttach
8626 ? llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE
8628 false, mapDataIndex);
8640 llvm::IRBuilderBase &builder) {
8642 "function only supported for host device codegen");
8643 for (
size_t i = 0; i < mapData.MapClause.size(); ++i) {
8644 auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[i]);
8647 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH) ==
8648 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
8653 if (!mapData.IsDeclareTarget[i] ||
8654 (mapData.IsDeclareTarget[i] && isAttachMap)) {
8655 omp::VariableCaptureKind captureKind = mapOp.getMapCaptureType();
8665 switch (captureKind) {
8666 case omp::VariableCaptureKind::ByRef: {
8667 llvm::Value *newV = mapData.Pointers[i];
8668 bool isByteOffset =
false;
8670 moduleTranslation, builder, mapData.BaseType[i]->isArrayTy(),
8671 mapOp.getBounds(), isByteOffset);
8673 newV = builder.CreateLoad(builder.getPtrTy(), newV);
8675 if (!offsetIdx.empty())
8676 newV = builder.CreateInBoundsGEP(isByteOffset ? builder.getInt8Ty()
8677 : mapData.BaseType[i],
8678 newV, offsetIdx,
"array_offset");
8679 mapData.Pointers[i] = newV;
8681 case omp::VariableCaptureKind::ByCopy: {
8682 llvm::Type *type = mapData.BaseType[i];
8684 if (mapData.Pointers[i]->getType()->isPointerTy())
8685 newV = builder.CreateLoad(type, mapData.Pointers[i]);
8687 newV = mapData.Pointers[i];
8690 auto curInsert = builder.saveIP();
8691 llvm::DebugLoc DbgLoc = builder.getCurrentDebugLocation();
8693 auto *memTempAlloc =
8694 builder.CreateAlloca(builder.getPtrTy(),
nullptr,
".casted");
8695 builder.SetCurrentDebugLocation(DbgLoc);
8696 builder.restoreIP(curInsert);
8698 builder.CreateStore(newV, memTempAlloc);
8699 newV = builder.CreateLoad(builder.getPtrTy(), memTempAlloc);
8702 mapData.Pointers[i] = newV;
8703 mapData.BasePointers[i] = newV;
8705 case omp::VariableCaptureKind::This:
8706 case omp::VariableCaptureKind::VLAType:
8707 mapData.MapClause[i]->emitOpError(
"Unhandled capture kind");
8718 MapInfoData &mapData,
8719 TargetDirectiveEnumTy targetDirective) {
8721 "function only supported for host device codegen");
8742 for (
size_t i = 0; i < mapData.MapClause.size(); ++i) {
8743 if (mapData.IsAMember[i])
8746 auto mapInfoOp = dyn_cast<omp::MapInfoOp>(mapData.MapClause[i]);
8747 if (!mapInfoOp.getMembers().empty()) {
8749 combinedInfo, mapData, i, targetDirective);
8754 combinedInfo, targetDirective);
8756 if (!combinedInfo.NonContigInfo.Dims.empty())
8757 combinedInfo.NonContigInfo.Dims.resize(combinedInfo.Types.size(), 1);
8760static llvm::Expected<llvm::Function *>
8762 LLVM::ModuleTranslation &moduleTranslation,
8763 llvm::StringRef mapperFuncName,
8764 TargetDirectiveEnumTy targetDirective);
8766static llvm::Expected<llvm::Function *>
8769 TargetDirectiveEnumTy targetDirective) {
8771 "function only supported for host device codegen");
8772 auto declMapperOp = cast<omp::DeclareMapperOp>(op);
8773 std::string mapperFuncName =
8775 ->createPlatformSpecificName(
8776 {
"omp_mapper", declMapperOp.getSymName()});
8778 if (
auto *lookupFunc = moduleTranslation.
lookupFunction(mapperFuncName))
8786 if (llvm::Function *existingFunc =
8787 moduleTranslation.
getLLVMModule()->getFunction(mapperFuncName)) {
8788 moduleTranslation.
mapFunction(mapperFuncName, existingFunc);
8789 return existingFunc;
8793 mapperFuncName, targetDirective);
8802 llvm::BasicBlock &entry = mapperFn.getEntryBlock();
8804 for (llvm::BasicBlock &bb : llvm::drop_begin(mapperFn))
8805 for (llvm::Instruction &inst : bb)
8806 if (
auto *alloca = dyn_cast<llvm::AllocaInst>(&inst))
8807 if (isa<llvm::ConstantInt>(alloca->getArraySize()))
8808 toHoist.push_back(alloca);
8809 for (llvm::AllocaInst *alloca : toHoist)
8810 alloca->moveBefore(entry.getFirstNonPHIOrAlloca());
8813static llvm::Expected<llvm::Function *>
8816 llvm::StringRef mapperFuncName,
8817 TargetDirectiveEnumTy targetDirective) {
8819 "function only supported for host device codegen");
8820 auto declMapperOp = cast<omp::DeclareMapperOp>(op);
8821 auto declMapperInfoOp = declMapperOp.getDeclareMapperInfo();
8823 return llvm::make_error<PreviouslyReportedError>();
8827 llvm::Type *varType = moduleTranslation.
convertType(declMapperOp.getType());
8830 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
8833 MapInfosTy combinedInfo;
8835 [&](InsertPointTy codeGenIP, llvm::Value *ptrPHI,
8836 llvm::Value *unused2) -> llvm::OpenMPIRBuilder::MapInfosOrErrorTy {
8837 builder.restoreIP(codeGenIP);
8838 moduleTranslation.
mapValue(declMapperOp.getSymVal(), ptrPHI);
8839 moduleTranslation.
mapBlock(&declMapperOp.getRegion().front(),
8840 builder.GetInsertBlock());
8841 if (failed(moduleTranslation.
convertBlock(declMapperOp.getRegion().front(),
8844 return llvm::make_error<PreviouslyReportedError>();
8845 MapInfoData mapData;
8872 struct IteratedEntryInfo {
8873 mlir::omp::IteratorOp itersOp;
8874 mlir::omp::MapInfoOp mapInfoOp;
8875 llvm::Type *baseLLVMTy;
8876 llvm::Value *elemSizeVal;
8877 IteratorInfo iterInfo;
8880 for (
mlir::Value iterVal : declMapperInfoOp.getMapIterated()) {
8881 auto itersOp = iterVal.getDefiningOp<mlir::omp::IteratorOp>();
8882 assert(itersOp &&
"map_iterated value must be defined by omp.iterator");
8886 mlir::omp::YieldOp yieldOp = itersOp.getYieldOp();
8887 assert(yieldOp &&
"expected exactly one omp.yield in the iterator body");
8889 yieldOp.getResults()[0].getDefiningOp<mlir::omp::MapInfoOp>();
8890 assert(mapInfoOp &&
"expected an omp.map.info in the map_iterated body");
8892 mlir::Type varPtrMlirTy = mapInfoOp.getVarPtrType();
8896 if (
auto arrTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(varPtrMlirTy))
8898 iteratedEntries.push_back(
8899 {itersOp, mapInfoOp, moduleTranslation.
convertType(varPtrMlirTy),
8900 builder.getInt64(elemSizeInBits / 8),
8901 IteratorInfo(itersOp, moduleTranslation, builder)});
8910 auto genIteratedEntry = [&moduleTranslation](IteratedEntryInfo info,
8911 llvm::IRBuilderBase &
b,
8912 llvm::Value *linearIV)
8915 info.itersOp.getRegion(),
b,
8916 moduleTranslation)))
8917 return llvm::make_error<PreviouslyReportedError>();
8919 moduleTranslation.
lookupValue(info.mapInfoOp.getVarPtr());
8920 bool isByteOffset =
false;
8922 moduleTranslation,
b, info.baseLLVMTy->isArrayTy(),
8923 info.mapInfoOp.getBounds(), isByteOffset);
8924 llvm::Value *addr = base;
8925 if (!offsetIdx.empty())
8926 addr =
b.CreateInBoundsGEP(
8927 isByteOffset ?
b.getInt8Ty() : info.baseLLVMTy, base, offsetIdx);
8930 llvm::Value *elementCount =
b.getInt64(1);
8931 for (
mlir::Value bound : info.mapInfoOp.getBounds()) {
8932 auto boundOp = bound.getDefiningOp<mlir::omp::MapBoundsOp>();
8936 moduleTranslation.
lookupValue(boundOp.getLowerBound());
8938 moduleTranslation.
lookupValue(boundOp.getUpperBound());
8939 elementCount =
b.CreateMul(
8940 elementCount,
b.CreateAdd(
b.CreateSub(
ub, lb),
b.getInt64(1)));
8942 llvm::Value *size =
b.CreateMul(elementCount, info.elemSizeVal);
8949 bool hasIterated = !iteratedEntries.empty();
8950 std::optional<unsigned> iteratedParentIdx;
8953 llvm::Value *anyTrips =
nullptr;
8954 llvm::Value *spanBegin =
nullptr;
8955 llvm::Value *spanEnd =
nullptr;
8956 bool hasStaticParent =
false;
8958 bool mapsWholeVariable =
false;
8959 for (
Value mapVar : mapVars) {
8960 auto mapOp = cast<omp::MapInfoOp>(mapVar.getDefiningOp());
8961 if (mapOp.getVarPtr() != declMapperOp.getSymVal())
8966 if (mapOp.getPartialMap() && mapOp.getMembers().size() == 1)
8968 hasStaticParent =
true;
8969 if (!mapOp.getPartialMap() && mapOp.getBounds().empty())
8970 mapsWholeVariable =
true;
8972 if (!mapsWholeVariable) {
8979 llvm::Type *i64Ty = builder.getInt64Ty();
8980 anyTrips = builder.getFalse();
8981 spanBegin = builder.getInt64(0);
8982 spanEnd = builder.getInt64(0);
8983 llvm::Value *beginSlot =
8984 builder.CreateAlloca(i64Ty,
nullptr,
"omp.iterparent.begin");
8985 llvm::Value *endSlot =
8986 builder.CreateAlloca(i64Ty,
nullptr,
"omp.iterparent.end");
8987 for (IteratedEntryInfo &info : iteratedEntries) {
8988 llvm::Value *trips = info.iterInfo.getTotalTrips();
8989 llvm::Value *hasTrips =
8990 builder.CreateICmpNE(trips, builder.getInt64(0));
8991 builder.CreateStore(builder.getInt64(~0ULL), beginSlot);
8992 builder.CreateStore(builder.getInt64(0), endSlot);
8993 auto spanBodyGen = [&](InsertPointTy bodyIP,
8994 llvm::Value *linearIV) -> llvm::Error {
8995 builder.restoreIP(bodyIP);
8997 genIteratedEntry(info, builder, linearIV);
8999 return entryOrErr.takeError();
9000 llvm::Value *begin =
9001 builder.CreatePtrToInt((*entryOrErr)[1], i64Ty);
9002 llvm::Value *end = builder.CreateAdd(begin, (*entryOrErr)[2]);
9003 builder.CreateStore(builder.CreateBinaryIntrinsic(
9004 llvm::Intrinsic::umin,
9005 builder.CreateLoad(i64Ty, beginSlot),
9008 builder.CreateStore(builder.CreateBinaryIntrinsic(
9009 llvm::Intrinsic::umax,
9010 builder.CreateLoad(i64Ty, endSlot), end),
9012 return llvm::Error::success();
9014 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
9015 ompBuilder->createIteratorLoop(
9016 llvm::OpenMPIRBuilder::LocationDescription(builder), trips,
9017 spanBodyGen,
"mapper.iterspan");
9019 return afterIP.takeError();
9020 builder.restoreIP(*afterIP);
9021 llvm::Value *segBegin = builder.CreateLoad(i64Ty, beginSlot);
9022 llvm::Value *segEnd = builder.CreateLoad(i64Ty, endSlot);
9024 llvm::Value *mergedBegin = builder.CreateSelect(
9026 builder.CreateBinaryIntrinsic(llvm::Intrinsic::umin, spanBegin,
9029 llvm::Value *mergedEnd =
9030 builder.CreateSelect(anyTrips,
9031 builder.CreateBinaryIntrinsic(
9032 llvm::Intrinsic::umax, spanEnd, segEnd),
9034 spanBegin = builder.CreateSelect(hasTrips, mergedBegin, spanBegin);
9035 spanEnd = builder.CreateSelect(hasTrips, mergedEnd, spanEnd);
9036 anyTrips = builder.CreateOr(anyTrips, hasTrips);
9040 ompBuilder->Builder.restoreIP(builder.saveIP());
9042 if (!hasStaticParent) {
9045 iteratedParentIdx = 0;
9046 combinedInfo.BasePointers.push_back(ptrPHI);
9047 combinedInfo.Pointers.push_back(
9048 builder.CreateIntToPtr(spanBegin, builder.getPtrTy()));
9049 combinedInfo.Sizes.push_back(builder.CreateSub(spanEnd, spanBegin));
9050 combinedInfo.Types.push_back(
9051 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE);
9052 combinedInfo.HasAttachPtr.push_back(
false);
9053 combinedInfo.DevicePointers.push_back(
9054 llvm::OpenMPIRBuilder::DeviceInfoTy::None);
9055 combinedInfo.Mappers.push_back(
nullptr);
9057 declMapperOp.getLoc(), *ompBuilder, declMapperOp.getSymName()));
9058 combinedInfo.LeadingParentCond = anyTrips;
9063 genMapInfos(builder, moduleTranslation, dl, combinedInfo, mapData,
9066 llvm::omp::OpenMPOffloadMappingFlags iteratedMemberOf =
9067 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
9069 if (!iteratedParentIdx) {
9073 for (
unsigned i = 0; i < combinedInfo.BasePointers.size(); ++i) {
9074 if (combinedInfo.BasePointers[i] == ptrPHI &&
9075 (combinedInfo.Types[i] &
9076 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF) ==
9077 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE) {
9078 iteratedParentIdx = i;
9083 assert(iteratedParentIdx &&
"no parent component for iterated entries");
9084 if (iteratedParentIdx && spanBegin && hasStaticParent) {
9089 unsigned idx = *iteratedParentIdx;
9090 llvm::Type *i64Ty = builder.getInt64Ty();
9091 llvm::Value *parentBegin =
9092 builder.CreatePtrToInt(combinedInfo.Pointers[idx], i64Ty);
9093 llvm::Value *parentEnd =
9094 builder.CreateAdd(parentBegin, combinedInfo.Sizes[idx]);
9095 llvm::Value *newBegin = builder.CreateSelect(
9097 builder.CreateBinaryIntrinsic(llvm::Intrinsic::umin, parentBegin,
9099 parentBegin,
"omp.iterparent.begin.merged");
9100 llvm::Value *newEnd =
9101 builder.CreateSelect(anyTrips,
9102 builder.CreateBinaryIntrinsic(
9103 llvm::Intrinsic::umax, parentEnd, spanEnd),
9104 parentEnd,
"omp.iterparent.end.merged");
9105 combinedInfo.Pointers[idx] =
9106 builder.CreateIntToPtr(newBegin, builder.getPtrTy());
9107 combinedInfo.Sizes[idx] = builder.CreateSub(newEnd, newBegin);
9109 if (iteratedParentIdx)
9110 iteratedMemberOf = ompBuilder->getMemberOfFlag(*iteratedParentIdx);
9113 for (IteratedEntryInfo &info : iteratedEntries) {
9114 llvm::omp::OpenMPOffloadMappingFlags mapType =
9116 ompBuilder->setCorrectMemberOfFlag(mapType, iteratedMemberOf);
9118 (mapType & llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH) !=
9119 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
9121 combinedInfo.DynamicSegments.push_back(MapInfosTy::DynamicSegment{
9122 info.iterInfo.getTotalTrips(), {}, mapType, hasAttachPtr});
9123 MapInfosTy::DynamicSegment &seg = combinedInfo.DynamicSegments.back();
9124 seg.GenEntry = [genIteratedEntry, info](llvm::IRBuilderBase &
b,
9125 llvm::Value *linearIV) {
9126 return genIteratedEntry(info,
b, linearIV);
9129 if (info.mapInfoOp.getMapperId()) {
9130 auto childMapperOp =
9132 info.mapInfoOp, info.mapInfoOp.getMapperIdAttr());
9137 llvm::IRBuilderBase::InsertPointGuard childMapperIPGuard(builder);
9140 childMapperOp, builder, moduleTranslation, targetDirective);
9142 return childMapperFn.takeError();
9143 seg.ChildMapperFn = *childMapperFn;
9147 return combinedInfo;
9151 if (!combinedInfo.Mappers[i])
9154 moduleTranslation, targetDirective);
9158 genMapInfoCB, varType, mapperFuncName, customMapperCB,
9167 return newFn.takeError();
9169 if ([[maybe_unused]] llvm::Function *mappedFunc =
9171 assert(mappedFunc == *newFn &&
9172 "mapper function mapping disagrees with emitted function");
9174 moduleTranslation.
mapFunction(mapperFuncName, *newFn);
9180 llvm::OpenMPIRBuilder &ompBuilder,
9186 llvm::Function *parentFn = builder.GetInsertBlock()->getParent();
9187 llvm::StringRef fnName = parentFn ? parentFn->getName() :
"";
9189 fileLoc, ompBuilder, fnName, strSize);
9190 return ompBuilder.getOrCreateIdent(srcStr, strSize);
9196 llvm::Value *ifCond =
nullptr;
9197 llvm::Value *deviceID = builder.getInt64(llvm::omp::OMP_DEVICEID_UNDEF);
9201 llvm::omp::RuntimeFunction RTLFn;
9203 TargetDirectiveEnumTy targetDirective = getTargetDirectiveEnumTyFromOp(op);
9206 llvm::OpenMPIRBuilder::TargetDataInfo info(
9210 if (ompBuilder->Config.isTargetDevice())
9211 return op->
emitOpError() <<
"not allowed in a target device";
9213 bool isOffloadEntry = !ompBuilder->Config.TargetTriples.empty();
9215 auto getDeviceID = [&](
mlir::Value dev) -> llvm::Value * {
9216 llvm::Value *v = moduleTranslation.
lookupValue(dev);
9217 return builder.CreateIntCast(v, builder.getInt64Ty(),
true);
9222 .Case([&](omp::TargetDataOp dataOp) {
9226 if (
auto ifVar = dataOp.getIfExpr())
9230 deviceID = getDeviceID(devId);
9232 mapVars = dataOp.getMapVars();
9233 useDevicePtrVars = dataOp.getUseDevicePtrVars();
9234 useDeviceAddrVars = dataOp.getUseDeviceAddrVars();
9237 .Case([&](omp::TargetEnterDataOp enterDataOp) -> LogicalResult {
9241 if (
auto ifVar = enterDataOp.getIfExpr())
9245 deviceID = getDeviceID(devId);
9248 enterDataOp.getNowait()
9249 ? llvm::omp::OMPRTL___tgt_target_data_begin_nowait_mapper
9250 : llvm::omp::OMPRTL___tgt_target_data_begin_mapper;
9251 mapVars = enterDataOp.getMapVars();
9252 info.HasNoWait = enterDataOp.getNowait();
9255 .Case([&](omp::TargetExitDataOp exitDataOp) -> LogicalResult {
9259 if (
auto ifVar = exitDataOp.getIfExpr())
9263 deviceID = getDeviceID(devId);
9265 RTLFn = exitDataOp.getNowait()
9266 ? llvm::omp::OMPRTL___tgt_target_data_end_nowait_mapper
9267 : llvm::omp::OMPRTL___tgt_target_data_end_mapper;
9268 mapVars = exitDataOp.getMapVars();
9269 info.HasNoWait = exitDataOp.getNowait();
9272 .Case([&](omp::TargetUpdateOp updateDataOp) -> LogicalResult {
9276 if (
auto ifVar = updateDataOp.getIfExpr())
9280 deviceID = getDeviceID(devId);
9283 updateDataOp.getNowait()
9284 ? llvm::omp::OMPRTL___tgt_target_data_update_nowait_mapper
9285 : llvm::omp::OMPRTL___tgt_target_data_update_mapper;
9286 mapVars = updateDataOp.getMapVars();
9287 info.HasNoWait = updateDataOp.getNowait();
9290 .DefaultUnreachable(
"unexpected operation");
9295 if (!isOffloadEntry)
9296 ifCond = builder.getFalse();
9298 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
9299 MapInfoData mapData;
9301 builder, useDevicePtrVars, useDeviceAddrVars);
9304 MapInfosTy combinedInfo;
9305 auto genMapInfoCB = [&](InsertPointTy codeGenIP) -> MapInfosTy & {
9306 builder.restoreIP(codeGenIP);
9307 genMapInfos(builder, moduleTranslation, DL, combinedInfo, mapData,
9309 return combinedInfo;
9315 [&moduleTranslation](
9316 llvm::OpenMPIRBuilder::DeviceInfoTy type,
9320 for (
auto [arg, useDevVar] :
9321 llvm::zip_equal(blockArgs, useDeviceVars)) {
9323 auto getMapBasePtr = [](omp::MapInfoOp mapInfoOp) {
9324 return mapInfoOp.getVarPtrPtr() ? mapInfoOp.getVarPtrPtr()
9325 : mapInfoOp.getVarPtr();
9328 auto useDevMap = cast<omp::MapInfoOp>(useDevVar.getDefiningOp());
9329 for (
auto [mapClause, devicePointer, basePointer] : llvm::zip_equal(
9330 mapInfoData.MapClause, mapInfoData.DevicePointers,
9331 mapInfoData.BasePointers)) {
9332 auto mapOp = cast<omp::MapInfoOp>(mapClause);
9333 if (getMapBasePtr(mapOp) != getMapBasePtr(useDevMap) ||
9334 devicePointer != type)
9337 if (llvm::Value *devPtrInfoMap =
9338 mapper ? mapper(basePointer) : basePointer) {
9339 moduleTranslation.
mapValue(arg, devPtrInfoMap);
9346 using BodyGenTy = llvm::OpenMPIRBuilder::BodyGenTy;
9347 auto bodyGenCB = [&](InsertPointTy codeGenIP, BodyGenTy bodyGenType)
9348 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
9351 builder.restoreIP(codeGenIP);
9352 assert(isa<omp::TargetDataOp>(op) &&
9353 "BodyGen requested for non TargetDataOp");
9354 auto blockArgIface = cast<omp::BlockArgOpenMPOpInterface>(op);
9355 Region ®ion = cast<omp::TargetDataOp>(op).getRegion();
9356 switch (bodyGenType) {
9357 case BodyGenTy::Priv:
9359 if (!info.DevicePtrInfoMap.empty()) {
9360 mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Address,
9361 blockArgIface.getUseDeviceAddrBlockArgs(),
9362 useDeviceAddrVars, mapData,
9363 [&](llvm::Value *basePointer) -> llvm::Value * {
9364 if (!info.DevicePtrInfoMap[basePointer].second)
9366 return builder.CreateLoad(
9368 info.DevicePtrInfoMap[basePointer].second);
9370 mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer,
9371 blockArgIface.getUseDevicePtrBlockArgs(), useDevicePtrVars,
9372 mapData, [&](llvm::Value *basePointer) {
9373 return info.DevicePtrInfoMap[basePointer].second;
9377 moduleTranslation)))
9378 return llvm::make_error<PreviouslyReportedError>();
9381 case BodyGenTy::DupNoPriv:
9382 if (info.DevicePtrInfoMap.empty()) {
9385 mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Address,
9386 blockArgIface.getUseDeviceAddrBlockArgs(),
9387 useDeviceAddrVars, mapData);
9388 mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer,
9389 blockArgIface.getUseDevicePtrBlockArgs(), useDevicePtrVars,
9393 case BodyGenTy::NoPriv:
9395 if (info.DevicePtrInfoMap.empty()) {
9397 moduleTranslation)))
9398 return llvm::make_error<PreviouslyReportedError>();
9402 return builder.saveIP();
9405 auto customMapperCB =
9407 if (!combinedInfo.Mappers[i])
9409 info.HasMapper =
true;
9411 moduleTranslation, targetDirective);
9414 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
9416 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
9423 llvm::Value *srcLocOverride =
9427 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP = [&]() {
9428 if (isa<omp::TargetDataOp>(op))
9429 return ompBuilder->createTargetData(
9430 ompLoc, allocaIP, builder.saveIP(), deallocBlocks, deviceID, ifCond,
9431 info, genMapInfoCB, customMapperCB,
9433 nullptr, srcLocOverride);
9434 return ompBuilder->createTargetData(
9435 ompLoc, allocaIP, builder.saveIP(), deallocBlocks, deviceID, ifCond,
9436 info, genMapInfoCB, customMapperCB, &RTLFn,
9438 nullptr, srcLocOverride);
9444 builder.restoreIP(*afterIP);
9452 auto distributeOp = cast<omp::DistributeOp>(opInst);
9459 std::optional<ReductionVarsInfo> distributeRedInfo;
9462 distributeRedInfo.emplace(teamsOp);
9463 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
9467 moduleTranslation, allocaIP,
9468 *distributeRedInfo)))
9472 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
9474 [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
9476 llvm::BasicBlock *allocaBlock = allocaIP.getNodeParent();
9478 builder.restoreIP(codeGenIP);
9479 PrivateVarsInfo privVarsInfo(distributeOp);
9482 distributeOp, builder, moduleTranslation, privVarsInfo, allocaIP);
9484 return llvm::make_error<PreviouslyReportedError>();
9490 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
9495 return llvm::make_error<PreviouslyReportedError>();
9499 distributeOp.getPrivateNeedsBarrier())))
9500 return llvm::make_error<PreviouslyReportedError>();
9503 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
9506 builder, moduleTranslation);
9508 return regionBlock.takeError();
9509 builder.SetInsertPoint((*regionBlock)->begin());
9514 if (!isa_and_present<omp::WsloopOp>(distributeOp.getNestedWrapper())) {
9517 bool hasDistSchedule = distributeOp.getDistScheduleStatic();
9518 auto schedule = hasDistSchedule ? omp::ClauseScheduleKind::Distribute
9519 : omp::ClauseScheduleKind::Static;
9521 bool isOrdered = hasDistSchedule;
9522 std::optional<omp::ScheduleModifier> scheduleMod;
9523 bool isSimd =
false;
9524 llvm::omp::WorksharingLoopType workshareLoopType =
9525 llvm::omp::WorksharingLoopType::DistributeStaticLoop;
9526 bool loopNeedsBarrier =
false;
9527 llvm::Value *chunk = moduleTranslation.
lookupValue(
9528 distributeOp.getDistScheduleChunkSize());
9529 llvm::CanonicalLoopInfo *loopInfo =
9532 allocaIP = allocaBlock->getFirstInsertionPt();
9533 llvm::OpenMPIRBuilder::InsertPointOrErrorTy wsloopIP =
9534 ompBuilder->applyWorkshareLoop(
9535 ompLoc.DL, loopInfo, allocaIP, loopNeedsBarrier,
9536 convertToScheduleKind(schedule), chunk, isSimd,
9537 scheduleMod == omp::ScheduleModifier::monotonic,
9538 scheduleMod == omp::ScheduleModifier::nonmonotonic, isOrdered,
9539 workshareLoopType,
false, hasDistSchedule, chunk);
9542 return wsloopIP.takeError();
9545 distributeOp.getLoc(), privVarsInfo)))
9546 return llvm::make_error<PreviouslyReportedError>();
9548 return llvm::Error::success();
9552 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
9554 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
9555 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
9556 ompBuilder->createDistribute(ompLoc, allocaIP, deallocBlocks, bodyGenCB);
9561 builder.restoreIP(*afterIP);
9563 if (distributeRedInfo) {
9566 allocaIP, *distributeRedInfo,
9579 auto offloadMod = dyn_cast<omp::OffloadModuleInterface>(op);
9581 return op->
emitOpError() <<
"omp flags attached to non offload module op";
9585 if (offloadMod.getIsTargetDevice())
9586 ompBuilder->M.addModuleFlag(llvm::Module::Max,
"openmp-device",
9587 attribute.getOpenmpDeviceVersion());
9590 if (!offloadMod.getIsGPU())
9593 if (attribute.getNoGpuLib())
9596 ompBuilder->createGlobalFlag(attribute.getDebugKind(),
9597 "__omp_rtl_debug_kind");
9598 ompBuilder->createGlobalFlag(attribute.getAssumeTeamsOversubscription(),
9599 "__omp_rtl_assume_teams_oversubscription");
9600 ompBuilder->createGlobalFlag(attribute.getAssumeThreadsOversubscription(),
9601 "__omp_rtl_assume_threads_oversubscription");
9602 ompBuilder->createGlobalFlag(attribute.getAssumeNoThreadState(),
9603 "__omp_rtl_assume_no_thread_state");
9604 ompBuilder->createGlobalFlag(attribute.getAssumeNoNestedParallelism(),
9605 "__omp_rtl_assume_no_nested_parallelism");
9610 omp::TargetOp targetOp,
9611 llvm::OpenMPIRBuilder &ompBuilder,
9612 llvm::vfs::FileSystem &vfs,
9613 llvm::StringRef parentName =
"") {
9614 auto fileLoc = targetOp.getLoc()->findInstanceOf<
FileLineColLoc>();
9615 assert(fileLoc &&
"No file found from location");
9617 auto fileInfoCallBack = [&fileLoc]() {
9618 return std::pair<std::string, uint64_t>(
9619 llvm::StringRef(fileLoc.getFilename()), fileLoc.getLine());
9623 ompBuilder.getTargetEntryUniqueInfo(fileInfoCallBack, vfs, parentName);
9666 omp::TargetOp targetOp, MapInfoData &mapData, llvm::Argument &arg,
9667 llvm::Value *input, llvm::Value *&retVal, llvm::IRBuilderBase &builder,
9668 llvm::OpenMPIRBuilder &ompBuilder,
9670 llvm::IRBuilderBase::InsertPoint allocaIP,
9671 llvm::IRBuilderBase::InsertPoint codeGenIP,
9673 assert(ompBuilder.Config.isTargetDevice() &&
9674 "function only supported for target device codegen");
9675 builder.restoreIP(allocaIP);
9677 omp::VariableCaptureKind capture = omp::VariableCaptureKind::ByRef;
9679 ompBuilder.M.getContext());
9680 unsigned alignmentValue = 0;
9683 cast<omp::BlockArgOpenMPOpInterface>(*targetOp).getBlockArgsPairs(
9686 for (
size_t i = 0; i < mapData.MapClause.size(); ++i) {
9687 if (mapData.OriginalValue[i] == input) {
9688 auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[i]);
9689 capture = mapOp.getMapCaptureType();
9692 mapOp.getVarPtrType(), ompBuilder.M.getDataLayout());
9696 for (
auto &[val, arg] : blockArgsPairs) {
9697 if (mapOp.getResult() == val) {
9702 assert(mlirArg &&
"expected to find entry block argument for map clause");
9707 unsigned int allocaAS = ompBuilder.M.getDataLayout().getAllocaAddrSpace();
9708 unsigned int defaultAS =
9709 ompBuilder.M.getDataLayout().getProgramAddressSpace();
9712 llvm::Value *v =
nullptr;
9720 builder.SetInsertPoint(codeGenIP.getNodeParent()->getFirstInsertionPt());
9721 v = ompBuilder.createOMPAllocShared(builder, arg.getType());
9725 llvm::IRBuilderBase::InsertPointGuard guard(builder);
9726 for (
auto deallocIP : deallocIPs) {
9727 builder.SetInsertPoint(deallocIP);
9728 ompBuilder.createOMPFreeShared(builder, v, arg.getType());
9732 v = builder.CreateAlloca(arg.getType(), allocaAS);
9734 if (allocaAS != defaultAS && arg.getType()->isPointerTy())
9735 v = builder.CreateAddrSpaceCast(v, builder.getPtrTy(defaultAS));
9738 builder.CreateStore(&arg, v);
9740 builder.restoreIP(codeGenIP);
9743 case omp::VariableCaptureKind::ByCopy: {
9747 case omp::VariableCaptureKind::ByRef: {
9748 llvm::LoadInst *loadInst = builder.CreateAlignedLoad(
9750 ompBuilder.M.getDataLayout().getPrefTypeAlign(v->getType()));
9765 if (v->getType()->isPointerTy() && alignmentValue) {
9766 llvm::MDBuilder MDB(builder.getContext());
9767 loadInst->setMetadata(
9768 llvm::LLVMContext::MD_align,
9769 llvm::MDNode::get(builder.getContext(),
9770 MDB.createConstant(llvm::ConstantInt::get(
9771 llvm::Type::getInt64Ty(builder.getContext()),
9778 case omp::VariableCaptureKind::This:
9779 case omp::VariableCaptureKind::VLAType:
9782 assert(
false &&
"Currently unsupported capture kind");
9786 return builder.saveIP();
9803 auto blockArgIface = llvm::cast<omp::BlockArgOpenMPOpInterface>(*targetOp);
9804 for (
auto item : llvm::zip_equal(targetOp.getHostEvalVars(),
9805 blockArgIface.getHostEvalBlockArgs())) {
9806 Value hostEvalVar = std::get<0>(item), blockArg = std::get<1>(item);
9810 .Case([&](omp::TeamsOp teamsOp) {
9811 if (teamsOp.getNumTeamsLower() == blockArg)
9812 numTeamsLower = hostEvalVar;
9813 else if (llvm::is_contained(teamsOp.getNumTeamsUpperVars(),
9815 numTeamsUpper = hostEvalVar;
9816 else if (!teamsOp.getThreadLimitVars().empty() &&
9817 teamsOp.getThreadLimit(0) == blockArg)
9818 threadLimit = hostEvalVar;
9820 llvm_unreachable(
"unsupported host_eval use");
9822 .Case([&](omp::ParallelOp parallelOp) {
9823 if (!parallelOp.getNumThreadsVars().empty() &&
9824 parallelOp.getNumThreads(0) == blockArg)
9825 numThreads = hostEvalVar;
9827 llvm_unreachable(
"unsupported host_eval use");
9829 .Case([&](omp::LoopNestOp loopOp) {
9830 auto processBounds =
9834 for (
auto [i, lb] : llvm::enumerate(opBounds)) {
9835 if (lb == blockArg) {
9838 (*outBounds)[i] = hostEvalVar;
9844 processBounds(loopOp.getLoopLowerBounds(), lowerBounds);
9845 found = processBounds(loopOp.getLoopUpperBounds(), upperBounds) ||
9847 found = processBounds(loopOp.getLoopSteps(), steps) || found;
9849 assert(found &&
"unsupported host_eval use");
9851 .DefaultUnreachable(
"unsupported host_eval use");
9863template <
typename OpTy>
9868 if (OpTy casted = dyn_cast<OpTy>(op))
9871 if (immediateParent)
9872 return dyn_cast_if_present<OpTy>(op->
getParentOp());
9881 return std::nullopt;
9884 if (
auto constAttr = dyn_cast<IntegerAttr>(constOp.getValue()))
9885 return constAttr.getInt();
9887 return std::nullopt;
9892 uint64_t sizeInBytes = sizeInBits / 8;
9896template <
typename OpTy>
9898 if (op.getNumReductionVars() > 0) {
9903 members.reserve(reductions.size());
9904 for (omp::DeclareReductionOp &red : reductions) {
9908 if (red.getByrefElementType())
9909 members.push_back(*red.getByrefElementType());
9911 members.push_back(red.getType());
9914 auto structType = mlir::LLVM::LLVMStructType::getLiteral(
9930 llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &attrs,
9931 bool isTargetDevice,
bool isGPU) {
9934 Value numThreads, numTeamsLower, numTeamsUpper, threadLimit;
9935 if (!isTargetDevice) {
9943 numTeamsLower = teamsOp.getNumTeamsLower();
9945 if (!teamsOp.getNumTeamsUpperVars().empty())
9946 numTeamsUpper = teamsOp.getNumTeams(0);
9947 if (!teamsOp.getThreadLimitVars().empty())
9948 threadLimit = teamsOp.getThreadLimit(0);
9952 if (!parallelOp.getNumThreadsVars().empty())
9953 numThreads = parallelOp.getNumThreads(0);
9959 int32_t minTeamsVal = 1, maxTeamsVal = -1;
9963 if (numTeamsUpper) {
9965 minTeamsVal = maxTeamsVal = *val;
9967 minTeamsVal = maxTeamsVal = 0;
9973 minTeamsVal = maxTeamsVal = 1;
9975 minTeamsVal = maxTeamsVal = -1;
9980 auto setMaxValueFromClause = [](
Value clauseValue, int32_t &
result) {
9994 int32_t targetThreadLimitVal = -1, teamsThreadLimitVal = -1;
9995 if (!targetOp.getThreadLimitVars().empty())
9996 setMaxValueFromClause(targetOp.getThreadLimit(0), targetThreadLimitVal);
9997 setMaxValueFromClause(threadLimit, teamsThreadLimitVal);
10000 int32_t maxThreadsVal = -1;
10002 setMaxValueFromClause(numThreads, maxThreadsVal);
10010 int32_t combinedMaxThreadsVal = targetThreadLimitVal;
10011 if (combinedMaxThreadsVal < 0 ||
10012 (teamsThreadLimitVal >= 0 && teamsThreadLimitVal < combinedMaxThreadsVal))
10013 combinedMaxThreadsVal = teamsThreadLimitVal;
10015 if (combinedMaxThreadsVal < 0 ||
10016 (maxThreadsVal >= 0 && maxThreadsVal < combinedMaxThreadsVal))
10017 combinedMaxThreadsVal = maxThreadsVal;
10019 int32_t reductionDataSize = 0;
10020 if (isGPU && capturedOp) {
10027 omp::TargetExecMode execMode = targetOp.getKernelType();
10028 switch (execMode) {
10029 case omp::TargetExecMode::bare:
10030 attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_BARE;
10032 case omp::TargetExecMode::generic:
10033 attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_GENERIC;
10035 case omp::TargetExecMode::spmd:
10036 attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_SPMD;
10038 case omp::TargetExecMode::spmd_no_loop:
10039 attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_SPMD_NO_LOOP;
10042 attrs.MinTeams.front() = minTeamsVal;
10043 attrs.MaxTeams.front() = maxTeamsVal;
10044 attrs.MinThreads.front() = 1;
10045 attrs.MaxThreads.front() = combinedMaxThreadsVal;
10046 attrs.ReductionDataSize = reductionDataSize;
10058 omp::TargetOp targetOp,
Operation *capturedOp,
10059 llvm::OpenMPIRBuilder::TargetKernelRuntimeAttrs &attrs) {
10061 unsigned numLoops = loopOp ? loopOp.getNumLoops() : 0;
10063 Value numThreads, numTeamsLower, numTeamsUpper, teamsThreadLimit;
10067 teamsThreadLimit, &lowerBounds, &upperBounds, &steps);
10070 if (!targetOp.getThreadLimitVars().empty()) {
10071 Value targetThreadLimit = targetOp.getThreadLimit(0);
10072 attrs.TargetThreadLimit.front() =
10073 moduleTranslation.
lookupValue(targetThreadLimit);
10080 attrs.MinTeams.front() = builder.CreateSExtOrTrunc(
10081 moduleTranslation.
lookupValue(numTeamsLower), builder.getInt32Ty());
10084 attrs.MaxTeams.front() = builder.CreateSExtOrTrunc(
10085 moduleTranslation.
lookupValue(numTeamsUpper), builder.getInt32Ty());
10087 if (teamsThreadLimit)
10088 attrs.TeamsThreadLimit.front() = builder.CreateSExtOrTrunc(
10089 moduleTranslation.
lookupValue(teamsThreadLimit), builder.getInt32Ty());
10092 attrs.MaxThreads.front() = moduleTranslation.
lookupValue(numThreads);
10094 if (targetOp.hasHostEvalTripCount()) {
10096 attrs.LoopTripCount =
nullptr;
10101 for (
auto [loopLower, loopUpper, loopStep] :
10102 llvm::zip_equal(lowerBounds, upperBounds, steps)) {
10103 llvm::Value *lowerBound = moduleTranslation.
lookupValue(loopLower);
10104 llvm::Value *upperBound = moduleTranslation.
lookupValue(loopUpper);
10105 llvm::Value *step = moduleTranslation.
lookupValue(loopStep);
10107 if (!lowerBound || !upperBound || !step) {
10108 attrs.LoopTripCount =
nullptr;
10112 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
10113 llvm::Value *tripCount = ompBuilder->calculateCanonicalLoopTripCount(
10114 loc, lowerBound, upperBound, step,
true,
10115 loopOp.getLoopInclusive());
10117 if (!attrs.LoopTripCount) {
10118 attrs.LoopTripCount = tripCount;
10123 attrs.LoopTripCount = builder.CreateMul(attrs.LoopTripCount, tripCount,
10128 attrs.DeviceID = builder.getInt64(llvm::omp::OMP_DEVICEID_UNDEF);
10130 attrs.DeviceID = moduleTranslation.
lookupValue(devId);
10132 builder.CreateSExtOrTrunc(attrs.DeviceID, builder.getInt64Ty());
10136static llvm::omp::OMPDynGroupprivateFallbackType
10138 omp::FallbackModifier fb = fallbackAttr ? fallbackAttr.getValue()
10139 : omp::FallbackModifier::default_mem;
10141 case omp::FallbackModifier::abort:
10142 return llvm::omp::OMPDynGroupprivateFallbackType::Abort;
10143 case omp::FallbackModifier::null:
10144 return llvm::omp::OMPDynGroupprivateFallbackType::Null;
10145 case omp::FallbackModifier::default_mem:
10146 return llvm::omp::OMPDynGroupprivateFallbackType::DefaultMem;
10149 llvm_unreachable(
"unexpected dyn_groupprivate fallback type");
10152static LogicalResult
10155 auto targetOp = cast<omp::TargetOp>(opInst);
10160 llvm::DebugLoc outlinedFnLoc = builder.getCurrentDebugLocation();
10169 llvm::BasicBlock *parentBB = builder.GetInsertBlock();
10170 assert(parentBB &&
"No insert block is set for the builder");
10171 llvm::Function *parentLLVMFn = parentBB->getParent();
10172 assert(parentLLVMFn &&
"Parent Function must be valid");
10173 if (llvm::DISubprogram *SP = parentLLVMFn->getSubprogram())
10174 builder.SetCurrentDebugLocation(llvm::DILocation::get(
10175 parentLLVMFn->getContext(), outlinedFnLoc.getLine(),
10176 outlinedFnLoc.getCol(), SP, outlinedFnLoc.getInlinedAt()));
10184 llvm::DebugLoc outlinedFnDbgLoc;
10185 if (outlinedFnLoc && parentLLVMFn->getSubprogram())
10186 outlinedFnDbgLoc = outlinedFnLoc;
10189 bool isTargetDevice = ompBuilder->Config.isTargetDevice();
10190 bool isGPU = ompBuilder->Config.isGPU();
10193 auto argIface = cast<omp::BlockArgOpenMPOpInterface>(opInst);
10194 auto &targetRegion = targetOp.getRegion();
10211 llvm::Function *llvmOutlinedFn =
nullptr;
10212 TargetDirectiveEnumTy targetDirective =
10213 getTargetDirectiveEnumTyFromOp(&opInst);
10217 bool isOffloadEntry =
10218 isTargetDevice || !ompBuilder->Config.TargetTriples.empty();
10238 if (!targetOp.getInReductionVars().empty() && !isTargetDevice) {
10239 inRedOrigPtrs.reserve(targetOp.getInReductionVars().size());
10240 inRedMapArgIdx.reserve(targetOp.getInReductionVars().size());
10241 for (
Value v : targetOp.getInReductionVars()) {
10246 std::optional<unsigned> matchIdx;
10247 for (
auto [idx, mapV] : llvm::enumerate(targetOp.getMapVars())) {
10248 auto mapInfo = mapV.getDefiningOp<omp::MapInfoOp>();
10249 if (v != mapInfo.getVarPtr())
10252 return targetOp.emitError()
10253 <<
"in_reduction variable on omp.target has multiple matching "
10254 "map_entries entries; the redirect target is ambiguous";
10260 "TargetOp verifier guarantees a matching map_entries entry for "
10261 "each in_reduction variable");
10262 inRedMapArgIdx.push_back(*matchIdx);
10265 inRedOrigPtrs.push_back(moduleTranslation.
lookupValue(v));
10274 if (!targetOp.getPrivateVars().empty() && !targetOp.getMapVars().empty()) {
10276 std::optional<ArrayAttr> privateSyms = targetOp.getPrivateSyms();
10277 std::optional<DenseI64ArrayAttr> privateMapIndices =
10278 targetOp.getPrivateMapsAttr();
10280 for (
auto [privVarIdx, privVarSymPair] :
10281 llvm::enumerate(llvm::zip_equal(privateVars, *privateSyms))) {
10282 auto privVar = std::get<0>(privVarSymPair);
10283 auto privSym = std::get<1>(privVarSymPair);
10285 SymbolRefAttr privatizerName = llvm::cast<SymbolRefAttr>(privSym);
10286 omp::PrivateClauseOp privatizer =
10289 if (!privatizer.needsMap())
10293 targetOp.getMappedValueForPrivateVar(privVarIdx);
10294 assert(mappedValue &&
"Expected to find mapped value for a privatized "
10295 "variable that needs mapping");
10300 auto mapInfoOp = mappedValue.
getDefiningOp<omp::MapInfoOp>();
10301 [[maybe_unused]]
Type varType = mapInfoOp.getVarPtrType();
10305 if (!isa<LLVM::LLVMPointerType>(privVar.getType()))
10307 varType == privVar.getType() &&
10308 "Type of private var doesn't match the type of the mapped value");
10312 mappedPrivateVars.insert(
10314 targetRegion.getArgument(argIface.getMapBlockArgsStart() +
10315 (*privateMapIndices)[privVarIdx])});
10319 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
10320 auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
10322 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
10323 llvm::IRBuilderBase::InsertPointGuard guard(builder);
10324 builder.SetCurrentDebugLocation(llvm::DebugLoc());
10327 llvm::Function *llvmParentFn =
10329 llvmOutlinedFn = codeGenIP.getNodeParent()->getParent();
10330 assert(llvmParentFn && llvmOutlinedFn &&
10331 "Both parent and outlined functions must exist at this point");
10333 if (outlinedFnLoc && llvmParentFn->getSubprogram())
10334 llvmOutlinedFn->setSubprogram(outlinedFnLoc->getScope()->getSubprogram());
10336 if (
auto attr = llvmParentFn->getFnAttribute(
"target-cpu");
10337 attr.isStringAttribute())
10338 llvmOutlinedFn->addFnAttr(attr);
10340 if (
auto attr = llvmParentFn->getFnAttribute(
"target-features");
10341 attr.isStringAttribute())
10342 llvmOutlinedFn->addFnAttr(attr);
10344 for (
auto [idx, arg] : llvm::enumerate(mapBlockArgs)) {
10350 if (llvm::is_contained(inRedMapArgIdx, idx))
10352 auto mapInfoOp = cast<omp::MapInfoOp>(mapVars[idx].getDefiningOp());
10353 llvm::Value *mapOpValue =
10354 moduleTranslation.
lookupValue(mapInfoOp.getVarPtr());
10355 moduleTranslation.
mapValue(arg, mapOpValue);
10357 for (
auto [arg, mapOp] : llvm::zip_equal(hdaBlockArgs, hdaVars)) {
10358 auto mapInfoOp = cast<omp::MapInfoOp>(mapOp.getDefiningOp());
10359 llvm::Value *mapOpValue =
10360 moduleTranslation.
lookupValue(mapInfoOp.getVarPtr());
10361 moduleTranslation.
mapValue(arg, mapOpValue);
10366 PrivateVarsInfo privateVarsInfo(targetOp);
10370 privateVarsInfo, allocaIP, &mappedPrivateVars);
10372 if (failed(
handleError(afterAllocas, *targetOp)))
10373 return llvm::make_error<PreviouslyReportedError>();
10375 builder.restoreIP(codeGenIP);
10377 &mappedPrivateVars),
10380 return llvm::make_error<PreviouslyReportedError>();
10383 targetOp, builder, moduleTranslation, privateVarsInfo,
10384 targetOp.getPrivateNeedsBarrier(), {},
10385 {}, &mappedPrivateVars)))
10386 return llvm::make_error<PreviouslyReportedError>();
10397 if (!inRedOrigPtrs.empty()) {
10403 inRedResultPtrTys.reserve(inRedMapArgIdx.size());
10404 for (
unsigned mapArgIdx : inRedMapArgIdx)
10405 inRedResultPtrTys.push_back(
10406 moduleTranslation.
convertType(mapBlockArgs[mapArgIdx].getType()));
10408 llvm::OpenMPIRBuilder::LocationDescription bodyLoc(builder);
10409 llvm::OpenMPIRBuilder::InsertPointTy redIP =
10410 ompBuilder->createTargetInReduction(
10411 bodyLoc, inRedOrigPtrs, inRedResultPtrTys,
10412 [&](
unsigned idx, llvm::Value *priv) {
10413 moduleTranslation.
mapValue(mapBlockArgs[inRedMapArgIdx[idx]],
10416 builder.restoreIP(redIP);
10420 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
10422 targetRegion,
"omp.target", builder, moduleTranslation);
10425 return llvm::make_error<PreviouslyReportedError>();
10427 builder.SetInsertPoint(exitBlock.get()->getTerminator());
10430 targetOp.getLoc(), privateVarsInfo)))
10431 return llvm::make_error<PreviouslyReportedError>();
10433 return builder.saveIP();
10436 StringRef parentName = parentFn.getName();
10438 llvm::TargetRegionEntryInfo entryInfo;
10444 MapInfoData mapData;
10449 MapInfosTy combinedInfos;
10450 auto genMapInfoCB =
10451 [&](llvm::OpenMPIRBuilder::InsertPointTy codeGenIP) -> MapInfosTy & {
10452 builder.restoreIP(codeGenIP);
10453 genMapInfos(builder, moduleTranslation, dl, combinedInfos, mapData,
10458 auto *nullPtr = llvm::Constant::getNullValue(builder.getPtrTy());
10459 combinedInfos.BasePointers.push_back(nullPtr);
10460 combinedInfos.Pointers.push_back(nullPtr);
10461 combinedInfos.DevicePointers.push_back(
10462 llvm::OpenMPIRBuilder::DeviceInfoTy::None);
10463 combinedInfos.Sizes.push_back(builder.getInt64(0));
10464 combinedInfos.Types.push_back(
10465 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM |
10466 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL);
10468 combinedInfos.HasAttachPtr.push_back(
false);
10469 if (!combinedInfos.Names.empty())
10470 combinedInfos.Names.push_back(nullPtr);
10471 combinedInfos.Mappers.push_back(
nullptr);
10473 return combinedInfos;
10476 auto argAccessorCB = [&](llvm::Argument &arg, llvm::Value *input,
10477 llvm::Value *&retVal, InsertPointTy allocaIP,
10478 InsertPointTy codeGenIP,
10480 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
10481 llvm::IRBuilderBase::InsertPointGuard guard(builder);
10482 builder.SetCurrentDebugLocation(llvm::DebugLoc());
10488 if (!isTargetDevice) {
10489 retVal = cast<llvm::Value>(&arg);
10494 builder, *ompBuilder, moduleTranslation,
10495 allocaIP, codeGenIP, deallocIPs);
10498 llvm::OpenMPIRBuilder::TargetKernelRuntimeAttrs runtimeAttrs;
10499 llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs defaultAttrs;
10501 cast<omp::ComposableOpInterface>(*targetOp).findCapturedOp();
10503 isTargetDevice, isGPU);
10507 if (!isTargetDevice)
10509 targetCapturedOp, runtimeAttrs);
10517 for (
auto [arg, var] : llvm::zip_equal(hostEvalBlockArgs, hostEvalVars)) {
10518 llvm::Value *value = moduleTranslation.
lookupValue(var);
10519 moduleTranslation.
mapValue(arg, value);
10521 if (!llvm::isa<llvm::Constant>(value))
10522 kernelInput.push_back(value);
10525 for (
size_t i = 0, e = mapData.OriginalValue.size(); i != e; ++i) {
10535 using MapFlags = llvm::omp::OpenMPOffloadMappingFlags;
10536 bool isAttachMap = (mapData.Types[i] & MapFlags::OMP_MAP_ATTACH) ==
10537 MapFlags::OMP_MAP_ATTACH;
10538 bool isPrivateTargetParam =
10539 (mapData.Types[i] &
10540 (MapFlags::OMP_MAP_PRIVATE | MapFlags::OMP_MAP_TARGET_PARAM)) ==
10541 (MapFlags::OMP_MAP_PRIVATE | MapFlags::OMP_MAP_TARGET_PARAM);
10543 if (!mapData.IsDeclareTarget[i] && !mapData.IsAMember[i] &&
10544 (!isAttachMap || (isAttachMap && isPrivateTargetParam)))
10545 kernelInput.push_back(mapData.OriginalValue[i]);
10549 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
10552 llvm::OpenMPIRBuilder::DependenciesInfo dds;
10554 targetOp.getDependVars(), targetOp.getDependKinds(),
10555 targetOp.getDependIterated(), targetOp.getDependIteratedKinds(),
10556 builder, moduleTranslation, dds)))
10559 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
10561 llvm::OpenMPIRBuilder::TargetDataInfo info(
10565 auto customMapperCB =
10567 if (!combinedInfos.Mappers[i])
10569 info.HasMapper =
true;
10571 moduleTranslation, targetDirective);
10574 llvm::Value *ifCond =
nullptr;
10575 if (
Value targetIfCond = targetOp.getIfExpr())
10576 ifCond = moduleTranslation.
lookupValue(targetIfCond);
10578 Value dynGroupPrivateSize = targetOp.getDynGroupprivateSize();
10579 llvm::Value *dynSizeVal =
nullptr;
10580 if (dynGroupPrivateSize) {
10581 dynSizeVal = moduleTranslation.
lookupValue(dynGroupPrivateSize);
10582 dynSizeVal = builder.CreateIntCast(dynSizeVal, builder.getInt32Ty(),
10586 llvm::omp::OMPDynGroupprivateFallbackType fallbackType =
10592 llvm::Value *rtLocOverride =
10593 (!isTargetDevice && isOffloadEntry)
10597 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
10599 ->createTarget(ompLoc, isOffloadEntry, allocaIP, builder.saveIP(),
10600 deallocBlocks, info, entryInfo, defaultAttrs,
10601 runtimeAttrs, ifCond, kernelInput, genMapInfoCB,
10602 bodyCB, argAccessorCB, customMapperCB, dds,
10603 targetOp.getNowait(), dynSizeVal, fallbackType,
10604 outlinedFnDbgLoc, rtLocOverride);
10609 builder.restoreIP(*afterIP);
10612 builder.CreateFree(dds.DepArray);
10617static LogicalResult
10619 llvm::OpenMPIRBuilder *ompBuilder,
10628 if (FunctionOpInterface funcOp = dyn_cast<FunctionOpInterface>(op)) {
10629 if (
auto offloadMod = dyn_cast<omp::OffloadModuleInterface>(
10631 if (!offloadMod.getIsTargetDevice())
10634 omp::DeclareTargetDeviceType declareType = attribute.getDeviceType();
10636 if (declareType == omp::DeclareTargetDeviceType::host) {
10637 llvm::Function *llvmFunc =
10639 llvmFunc->dropAllReferences();
10640 llvmFunc->eraseFromParent();
10644 ompBuilder->Builder.ClearInsertionPoint();
10645 ompBuilder->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
10646 }
else if (llvm::Function *llvmFunc =
10658 if (!llvmFunc->isDeclaration() && llvmFunc->hasExternalLinkage() &&
10659 llvmFunc->getVisibility() == llvm::GlobalValue::DefaultVisibility)
10660 llvmFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
10666 if (LLVM::GlobalOp gOp = dyn_cast<LLVM::GlobalOp>(op)) {
10667 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
10668 if (
auto *gVal = llvmModule->getNamedValue(gOp.getSymName())) {
10669 auto *gVar = cast<llvm::GlobalVariable>(gVal);
10671 bool isDeclaration = gOp.isDeclaration();
10672 bool isExternallyVisible =
10675 llvm::StringRef mangledName = gOp.getSymName();
10676 mlir::omp::DeclareTargetCaptureClause captureClause =
10677 attribute.getCaptureClause();
10680 llvm::StringRef entryMangledName = mangledName;
10681 llvm::Constant *entryAddr = llvm::cast<llvm::Constant>(gVal);
10682 std::function<llvm::GlobalValue::LinkageTypes()> variableLinkage;
10684 bool requiresUSM = ompBuilder->Config.hasRequiresUnifiedSharedMemory();
10686 captureClause == omp::DeclareTargetCaptureClause::to ||
10687 captureClause == omp::DeclareTargetCaptureClause::enter;
10689 attribute.getDeviceType() == omp::DeclareTargetDeviceType::host;
10694 if (isToOrEnter && !isHostOnly && !requiresUSM &&
10695 gVar->hasLocalLinkage()) {
10696 gVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
10697 isExternallyVisible =
true;
10701 if (ompBuilder->Config.isTargetDevice())
10702 gVar->setDSOLocal(
false);
10707 llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseAny &&
10708 !requiresUSM && !isDeclaration &&
10709 (gVal->hasLocalLinkage() || gVal->hasHiddenVisibility())) {
10713 entryNameStorage = (mangledName + llvm::Twine(
"_decl_tgt_entry")).str();
10714 entryMangledName = entryNameStorage;
10715 if (llvm::GlobalValue *existing =
10716 llvmModule->getNamedValue(entryMangledName)) {
10717 entryAddr = llvm::cast<llvm::Constant>(existing);
10719 entryAddr = llvm::GlobalAlias::create(
10720 gVal->getValueType(), gVal->getAddressSpace(),
10721 llvm::GlobalValue::WeakAnyLinkage, entryMangledName, entryAddr,
10723 llvm::cast<llvm::GlobalAlias>(entryAddr)->setVisibility(
10724 llvm::GlobalValue::DefaultVisibility);
10726 variableLinkage = [] {
return llvm::GlobalValue::WeakAnyLinkage; };
10730 std::vector<llvm::GlobalVariable *> generatedRefs;
10732 std::vector<llvm::Triple> targetTriple;
10733 auto targetTripleAttr = dyn_cast_or_null<mlir::StringAttr>(
10735 LLVM::LLVMDialect::getTargetTripleAttrName()));
10736 if (targetTripleAttr)
10737 targetTriple.emplace_back(targetTripleAttr.data());
10739 auto fileInfoCallBack = [&loc]() {
10740 std::string filename =
"";
10741 std::uint64_t lineNo = 0;
10744 filename = loc.getFilename().str();
10745 lineNo = loc.getLine();
10748 return std::pair<std::string, std::uint64_t>(llvm::StringRef(filename),
10752 llvm::vfs::FileSystem &vfs = moduleTranslation.
getFileSystem();
10753 ompBuilder->registerTargetGlobalVariable(
10754 captureClauseKind, deviceClause, isDeclaration, isExternallyVisible,
10755 ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack, vfs),
10756 entryMangledName, generatedRefs,
false, targetTriple,
10757 nullptr, variableLinkage, gVal->getType(),
10760 if (ompBuilder->Config.isTargetDevice() &&
10761 (captureClause == omp::DeclareTargetCaptureClause::link ||
10766 llvm::Type *ptrTy = llvm::PointerType::get(llvmModule->getContext(), 0);
10767 llvm::Constant *refPtr = ompBuilder->getAddrOfDeclareTargetVar(
10768 captureClauseKind, deviceClause, isDeclaration, isExternallyVisible,
10769 ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack, vfs),
10770 mangledName, generatedRefs,
false, targetTriple,
10781 if (!gVar->isDeclaration())
10782 gVar->setLinkage(llvm::GlobalValue::InternalLinkage);
10788 dyn_cast<llvm::GlobalValue>(refPtr->stripPointerCasts()))
10789 ompBuilder->registerDeclareTargetGlobalReplacement(gVal, newGV);
10796 if (ompBuilder->Config.isTargetDevice() && isHostOnly && isToOrEnter) {
10797 gVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
10798 gVar->setInitializer(
nullptr);
10810class OpenMPDialectLLVMIRTranslationInterface
10811 :
public LLVMTranslationDialectInterface {
10813 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
10818 convertOperation(Operation *op, llvm::IRBuilderBase &builder,
10819 LLVM::ModuleTranslation &moduleTranslation)
const final;
10824 amendOperation(Operation *op, ArrayRef<llvm::Instruction *> instructions,
10825 NamedAttribute attribute,
10826 LLVM::ModuleTranslation &moduleTranslation)
const final;
10831 void registerAllocatedPtr(Value var, llvm::Value *ptr)
const {
10832 ompAllocatedPtrs[var] = ptr;
10837 llvm::Value *lookupAllocatedPtr(Value var)
const {
10838 auto it = ompAllocatedPtrs.find(var);
10839 return it != ompAllocatedPtrs.end() ? it->second :
nullptr;
10851LogicalResult OpenMPDialectLLVMIRTranslationInterface::amendOperation(
10852 Operation *op, ArrayRef<llvm::Instruction *> instructions,
10853 NamedAttribute attribute,
10854 LLVM::ModuleTranslation &moduleTranslation)
const {
10855 return llvm::StringSwitch<llvm::function_ref<LogicalResult(Attribute)>>(
10857 .Case(
"omp.is_target_device",
10858 [&](Attribute attr) {
10859 if (
auto deviceAttr = dyn_cast<BoolAttr>(attr)) {
10860 llvm::OpenMPIRBuilderConfig &config =
10862 config.setIsTargetDevice(deviceAttr.getValue());
10867 .Case(
"omp.is_gpu",
10868 [&](Attribute attr) {
10869 if (
auto gpuAttr = dyn_cast<BoolAttr>(attr)) {
10870 llvm::OpenMPIRBuilderConfig &config =
10872 config.setIsGPU(gpuAttr.getValue());
10877 .Case(
"omp.host_ir_filepath",
10878 [&](Attribute attr) {
10879 if (
auto filepathAttr = dyn_cast<StringAttr>(attr)) {
10880 llvm::OpenMPIRBuilder *ompBuilder =
10882 ompBuilder->loadOffloadInfoMetadata(
10883 moduleTranslation.
getFileSystem(), filepathAttr.getValue());
10889 [&](Attribute attr) {
10890 if (
auto rtlAttr = dyn_cast<omp::FlagsAttr>(attr))
10894 .Case(
"omp.version",
10895 [&](Attribute attr) {
10896 if (
auto versionAttr = dyn_cast<omp::VersionAttr>(attr)) {
10897 llvm::OpenMPIRBuilder *ompBuilder =
10899 ompBuilder->M.addModuleFlag(llvm::Module::Max,
"openmp",
10900 versionAttr.getVersion());
10905 .Case(
"omp.declare_target",
10906 [&](Attribute attr) {
10907 if (
auto declareTargetAttr =
10908 dyn_cast<omp::DeclareTargetAttr>(attr)) {
10909 llvm::OpenMPIRBuilder *ompBuilder =
10912 ompBuilder, moduleTranslation);
10916 .Case(
"omp.requires",
10917 [&](Attribute attr) {
10918 if (
auto requiresAttr = dyn_cast<omp::ClauseRequiresAttr>(attr)) {
10919 using Requires = omp::ClauseRequires;
10920 Requires flags = requiresAttr.getValue();
10921 llvm::OpenMPIRBuilderConfig &config =
10923 config.setHasRequiresReverseOffload(
10924 bitEnumContainsAll(flags, Requires::reverse_offload));
10925 config.setHasRequiresUnifiedAddress(
10926 bitEnumContainsAll(flags, Requires::unified_address));
10927 config.setHasRequiresUnifiedSharedMemory(
10928 bitEnumContainsAll(flags, Requires::unified_shared_memory));
10929 config.setHasRequiresDynamicAllocators(
10930 bitEnumContainsAll(flags, Requires::dynamic_allocators));
10935 .Case(
"omp.target_triples",
10936 [&](Attribute attr) {
10937 if (
auto triplesAttr = dyn_cast<ArrayAttr>(attr)) {
10938 llvm::OpenMPIRBuilderConfig &config =
10940 config.TargetTriples.clear();
10941 config.TargetTriples.reserve(triplesAttr.size());
10942 for (Attribute tripleAttr : triplesAttr) {
10943 if (
auto tripleStrAttr = dyn_cast<StringAttr>(tripleAttr))
10944 config.TargetTriples.emplace_back(tripleStrAttr.getValue());
10952 .Case(
"omp.integer_wrap_around",
10953 [&](Attribute attr) {
10954 if (
auto wrapAttr = dyn_cast<omp::IntegerWrapAroundAttr>(attr)) {
10955 llvm::OpenMPIRBuilderConfig &config =
10957 config.setNoSignedWrap(!wrapAttr.getIntegerWrapAround());
10962 .Default([](Attribute) {
10978 if (
auto declareTargetIface =
10979 llvm::dyn_cast<mlir::omp::DeclareTargetInterface>(
10980 parentFn.getOperation())) {
10981 omp::DeclareTargetAttr declareTargetAttr =
10982 declareTargetIface.getDeclareTarget();
10983 if (declareTargetAttr && declareTargetAttr.getDeviceType() !=
10984 mlir::omp::DeclareTargetDeviceType::host)
10995 llvm::Module *llvmModule) {
10996 llvm::Type *i64Ty = builder.getInt64Ty();
10997 llvm::Type *i32Ty = builder.getInt32Ty();
10998 llvm::Type *returnType = builder.getPtrTy(0);
10999 llvm::FunctionType *fnType =
11000 llvm::FunctionType::get(returnType, {i64Ty, i32Ty},
false);
11001 llvm::Function *
func = cast<llvm::Function>(
11002 llvmModule->getOrInsertFunction(
"omp_target_alloc", fnType).getCallee());
11006template <
typename T>
11007static llvm::Value *
11010 llvm::DataLayout dataLayout =
11012 llvm::Type *llvmHeapTy =
11013 moduleTranslation.
convertType(op.getMemElemTypeAttr().getValue());
11015 auto alignment = op.getMemAlignment();
11016 llvm::TypeSize typeSize = llvm::alignTo(
11017 dataLayout.getTypeStoreSize(llvmHeapTy),
11018 alignment ? *alignment : dataLayout.getABITypeAlign(llvmHeapTy).value());
11020 llvm::Value *allocSize = builder.getInt64(typeSize.getFixedValue());
11021 return builder.CreateMul(
11023 builder.CreateIntCast(moduleTranslation.
lookupValue(op.getMemArraySize()),
11024 builder.getInt64Ty(),
11031 omp::TargetAllocMemOp op) {
11032 llvm::DataLayout dataLayout =
11034 llvm::Type *llvmHeapTy = moduleTranslation.
convertType(op.getAllocatedType());
11035 llvm::TypeSize typeSize = dataLayout.getTypeAllocSize(llvmHeapTy);
11036 llvm::Value *allocSize = builder.getInt64(typeSize.getFixedValue());
11037 for (
auto typeParam : op.getTypeparams()) {
11038 allocSize = builder.CreateMul(
11040 builder.CreateIntCast(moduleTranslation.
lookupValue(typeParam),
11041 builder.getInt64Ty(),
11047static LogicalResult
11050 auto allocMemOp = cast<omp::TargetAllocMemOp>(opInst);
11055 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
11059 llvm::Value *llvmDeviceNum = moduleTranslation.
lookupValue(deviceNum);
11061 llvm::Value *allocSize =
11064 llvm::CallInst *call =
11065 builder.CreateCall(ompTargetAllocFunc, {allocSize, llvmDeviceNum});
11066 llvm::Value *resultI64 = builder.CreatePtrToInt(call, builder.getInt64Ty());
11069 moduleTranslation.
mapValue(allocMemOp.getResult(), resultI64);
11073static LogicalResult
11075 llvm::IRBuilderBase &builder,
11079 moduleTranslation.
mapValue(allocMemOp.getResult(),
11080 ompBuilder->createOMPAllocShared(builder, size));
11084static LogicalResult
11087 const OpenMPDialectLLVMIRTranslationInterface &ompIface) {
11088 auto allocateDirOp = cast<omp::AllocateDirOp>(opInst);
11091 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
11092 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
11093 llvm::DataLayout dataLayout = llvmModule->getDataLayout();
11095 std::optional<int64_t> alignAttr = allocateDirOp.getAlign();
11097 llvm::Value *allocator;
11098 if (
auto allocatorVar = allocateDirOp.getAllocator()) {
11099 allocator = moduleTranslation.
lookupValue(allocatorVar);
11100 if (allocator->getType()->isIntegerTy())
11101 allocator = builder.CreateIntToPtr(allocator, builder.getPtrTy());
11102 else if (allocator->getType()->isPointerTy())
11103 allocator = builder.CreatePointerBitCastOrAddrSpaceCast(
11104 allocator, builder.getPtrTy());
11106 allocator = llvm::ConstantPointerNull::get(builder.getPtrTy());
11109 for (
Value var : vars) {
11111 llvm::Type *typeToInspect =
11116 var, baseVar, moduleTranslation, builder, dataLayout)) {
11117 size = *dynamicSize;
11118 }
else if (typeToInspect->isArrayTy()) {
11119 size = builder.getInt64(
11120 dataLayout.getTypeAllocSize(typeToInspect).getFixedValue());
11122 size = builder.getInt64(
11123 dataLayout.getTypeAllocSize(typeToInspect).getFixedValue());
11126 uint64_t alignValue =
11127 alignAttr ? alignAttr.value()
11128 : dataLayout.getABITypeAlign(typeToInspect).value();
11129 llvm::Value *alignConst = builder.getInt64(alignValue);
11131 size = builder.CreateAdd(size, builder.getInt64(alignValue - 1),
"",
true);
11132 size = builder.CreateUDiv(size, alignConst);
11133 size = builder.CreateMul(size, alignConst,
"",
true);
11135 std::string allocName =
11136 ompBuilder->createPlatformSpecificName({
".void.addr"});
11137 llvm::CallInst *allocCall;
11138 if (alignAttr.has_value()) {
11139 allocCall = ompBuilder->createOMPAlignedAlloc(
11140 ompLoc, builder.getInt64(alignAttr.value()), size, allocator,
11144 ompBuilder->createOMPAlloc(ompLoc, size, allocator, allocName);
11147 ompIface.registerAllocatedPtr(var, allocCall);
11149 if (llvm::Value *baseLlvm = moduleTranslation.
lookupValue(baseVar)) {
11150 llvm::Value *boundPtr = builder.CreatePointerBitCastOrAddrSpaceCast(
11151 allocCall, baseLlvm->getType());
11153 }
else if (llvm::Value *varLlvm = moduleTranslation.
lookupValue(var)) {
11154 llvm::Value *boundPtr = builder.CreatePointerBitCastOrAddrSpaceCast(
11155 allocCall, varLlvm->getType());
11163static LogicalResult
11166 const OpenMPDialectLLVMIRTranslationInterface &ompIface) {
11167 auto freeOp = cast<omp::AllocateFreeOp>(opInst);
11169 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
11171 llvm::Value *allocator;
11172 if (
auto allocatorVar = freeOp.getAllocator()) {
11173 allocator = moduleTranslation.
lookupValue(allocatorVar);
11174 if (allocator->getType()->isIntegerTy())
11175 allocator = builder.CreateIntToPtr(allocator, builder.getPtrTy());
11176 else if (allocator->getType()->isPointerTy())
11177 allocator = builder.CreatePointerBitCastOrAddrSpaceCast(
11178 allocator, builder.getPtrTy());
11180 allocator = llvm::ConstantPointerNull::get(builder.getPtrTy());
11185 for (
Value var : llvm::reverse(vars)) {
11186 llvm::Value *allocPtr = ompIface.lookupAllocatedPtr(var);
11188 return opInst.
emitError(
"omp.allocate_free: no allocation recorded");
11189 ompBuilder->createOMPFree(ompLoc, allocPtr, allocator,
"");
11196 llvm::Module *llvmModule) {
11197 llvm::Type *ptrTy = builder.getPtrTy(0);
11198 llvm::Type *i32Ty = builder.getInt32Ty();
11199 llvm::Type *voidTy = builder.getVoidTy();
11200 llvm::FunctionType *fnType =
11201 llvm::FunctionType::get(voidTy, {ptrTy, i32Ty},
false);
11202 llvm::Function *
func = dyn_cast<llvm::Function>(
11203 llvmModule->getOrInsertFunction(
"omp_target_free", fnType).getCallee());
11207static LogicalResult
11210 auto freeMemOp = cast<omp::TargetFreeMemOp>(opInst);
11215 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
11216 llvm::Function *ompTragetFreeFunc =
getOmpTargetFree(builder, llvmModule);
11219 llvm::Value *llvmDeviceNum = moduleTranslation.
lookupValue(deviceNum);
11222 llvm::Value *llvmHeapref = moduleTranslation.
lookupValue(heapref);
11224 llvm::Value *intToPtr =
11225 builder.CreateIntToPtr(llvmHeapref, builder.getPtrTy(0));
11226 builder.CreateCall(ompTragetFreeFunc, {intToPtr, llvmDeviceNum});
11230static LogicalResult
11232 llvm::IRBuilderBase &builder,
11236 ompBuilder->createOMPFreeShared(
11237 builder, moduleTranslation.
lookupValue(freeMemOp.getHeapref()), size);
11242static LogicalResult
11246 auto groupprivateOp = cast<omp::GroupprivateOp>(opInst);
11251 bool isTargetDevice = ompBuilder->Config.isTargetDevice();
11255 bool shouldAllocate =
true;
11256 switch (groupprivateOp.getDeviceType().value_or(
11257 mlir::omp::DeclareTargetDeviceType::any)) {
11258 case mlir::omp::DeclareTargetDeviceType::host:
11259 shouldAllocate = !isTargetDevice;
11261 case mlir::omp::DeclareTargetDeviceType::nohost:
11262 shouldAllocate = isTargetDevice;
11264 case mlir::omp::DeclareTargetDeviceType::any:
11265 shouldAllocate =
true;
11271 &opInst, groupprivateOp.getSymNameAttr());
11274 <<
"expected symbol '" << groupprivateOp.getSymName()
11275 <<
"' to reference an LLVM global variable";
11277 llvm::GlobalValue *globalValue = moduleTranslation.
lookupGlobal(global);
11278 llvm::Type *varType = moduleTranslation.
convertType(global.getType());
11279 std::string varName = globalValue->getName().str();
11281 llvm::Value *resultPtr;
11282 if (shouldAllocate && isTargetDevice) {
11283 llvm::Module *llvmModule = moduleTranslation.
getLLVMModule();
11284 llvm::Triple targetTriple(llvmModule->getTargetTriple());
11285 unsigned sharedAddressSpace;
11286 if (targetTriple.isAMDGCN())
11287 sharedAddressSpace = llvm::AMDGPUAS::LOCAL_ADDRESS;
11288 else if (targetTriple.isNVPTX())
11289 sharedAddressSpace = llvm::NVPTXAS::ADDRESS_SPACE_SHARED;
11291 return opInst.
emitError() <<
"groupprivate is not supported for target: "
11292 << targetTriple.str();
11293 llvm::GlobalVariable *sharedVar =
new llvm::GlobalVariable(
11294 *llvmModule, varType,
false,
11295 llvm::GlobalValue::InternalLinkage, llvm::PoisonValue::get(varType),
11296 varName,
nullptr, llvm::GlobalValue::NotThreadLocal,
11297 sharedAddressSpace,
11299 resultPtr = sharedVar;
11301 if (shouldAllocate && !isTargetDevice)
11302 opInst.
emitWarning(
"groupprivate directive is currently ignored on the "
11303 "host, using original global");
11304 resultPtr = globalValue;
11313LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation(
11314 Operation *op, llvm::IRBuilderBase &builder,
11315 LLVM::ModuleTranslation &moduleTranslation)
const {
11318 if (ompBuilder->Config.isTargetDevice() &&
11319 !isa<omp::TargetOp, omp::MapInfoOp, omp::TerminatorOp, omp::YieldOp>(
11322 return op->
emitOpError() <<
"unsupported host op found in device";
11330 bool isOutermostLoopWrapper =
11331 isa_and_present<omp::LoopWrapperInterface>(op) &&
11332 !dyn_cast_if_present<omp::LoopWrapperInterface>(op->
getParentOp());
11341 if (isa<omp::TaskloopContextOp>(op))
11342 isOutermostLoopWrapper =
true;
11343 else if (isa<omp::TaskloopWrapperOp>(op))
11344 isOutermostLoopWrapper =
false;
11346 if (isOutermostLoopWrapper)
11347 moduleTranslation.
stackPush<OpenMPLoopInfoStackFrame>();
11350 llvm::TypeSwitch<Operation *, LogicalResult>(op)
11351 .Case([&](omp::BarrierOp op) -> LogicalResult {
11355 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
11356 ompBuilder->createBarrier(builder, llvm::omp::OMPD_barrier);
11358 if (res.succeeded()) {
11361 builder.restoreIP(*afterIP);
11365 .Case([&](omp::TaskyieldOp op) {
11369 ompBuilder->createTaskyield(builder);
11372 .Case([&](omp::FlushOp op) {
11384 ompBuilder->createFlush(builder);
11387 .Case([&](omp::ErrorOp op) {
11391 llvm::Value *message =
nullptr;
11392 if (mlir::Value messageExpr = op.getMessageExpr())
11393 message = moduleTranslation.
lookupValue(messageExpr);
11394 else if (std::optional<StringRef> msg = op.getMessage();
11395 msg && !msg->empty())
11396 message = builder.CreateGlobalString(*msg);
11397 ompBuilder->createError(
11398 llvm::OpenMPIRBuilder::LocationDescription(builder),
11399 op.getSeverity() == omp::ClauseSeverity::fatal, message);
11402 .Case([&](omp::ParallelOp op) {
11405 .Case([&](omp::DispatchOp) {
11408 .Case([&](omp::MaskedOp) {
11411 .Case([&](omp::MasterOp) {
11414 .Case([&](omp::CriticalOp) {
11417 .Case([&](omp::OrderedRegionOp) {
11420 .Case([&](omp::OrderedOp) {
11423 .Case([&](omp::WsloopOp) {
11426 .Case([&](omp::SimdOp) {
11429 .Case([&](omp::AtomicReadOp) {
11432 .Case([&](omp::AtomicWriteOp) {
11435 .Case([&](omp::AtomicUpdateOp op) {
11438 .Case([&](omp::AtomicCaptureOp op) {
11441 .Case([&](omp::AtomicCompareOp op) {
11444 .Case([&](omp::CancelOp op) {
11447 .Case([&](omp::CancellationPointOp op) {
11450 .Case([&](omp::SectionsOp) {
11453 .Case([&](omp::ScopeOp op) {
11456 .Case([&](omp::SingleOp op) {
11459 .Case([&](omp::TeamsOp op) {
11462 .Case([&](omp::TaskOp op) {
11465 .Case([&](omp::TaskloopWrapperOp op) {
11468 .Case([&](omp::TaskloopContextOp op) {
11471 .Case([&](omp::TaskgroupOp op) {
11474 .Case([&](omp::TaskwaitOp op) {
11477 .Case([&](omp::InteropInitOp op) {
11480 .Case([&](omp::InteropDestroyOp op) {
11483 .Case([&](omp::InteropUseOp op) {
11486 .Case<omp::YieldOp, omp::TerminatorOp, omp::DeclareMapperOp,
11487 omp::DeclareMapperInfoOp, omp::DeclareReductionOp,
11488 omp::CriticalDeclareOp>([](
auto op) {
11501 .Case([&](omp::ThreadprivateOp) {
11504 .Case<omp::TargetDataOp, omp::TargetEnterDataOp,
11505 omp::TargetExitDataOp, omp::TargetUpdateOp>([&](
auto op) {
11508 .Case([&](omp::TargetOp) {
11511 .Case([&](omp::DistributeOp) {
11514 .Case([&](omp::LoopNestOp) {
11517 .Case<omp::MapInfoOp, omp::MapBoundsOp, omp::PrivateClauseOp,
11518 omp::AffinityEntryOp, omp::IteratorOp>([&](
auto op) {
11524 .Case([&](omp::NewCliOp op) {
11529 .Case([&](omp::CanonicalLoopOp op) {
11532 .Case([&](omp::UnrollHeuristicOp op) {
11541 .Case([&](omp::UnrollFullOp op) {
11544 .Case([&](omp::UnrollPartialOp op) {
11547 .Case([&](omp::TileOp op) {
11548 return applyTile(op, builder, moduleTranslation);
11550 .Case([&](omp::FuseOp op) {
11551 return applyFuse(op, builder, moduleTranslation);
11553 .Case([&](omp::TargetAllocMemOp) {
11556 .Case([&](omp::TargetFreeMemOp) {
11559 .Case([&](omp::AllocateDirOp) {
11562 .Case([&](omp::AllocateFreeOp) {
11566 .Case([&](omp::AllocSharedMemOp op) {
11569 .Case([&](omp::FreeSharedMemOp op) {
11572 .Case([&](omp::GroupprivateOp) {
11575 .Case([&](omp::DeclareSimdOp) {
11582 .Default([&](Operation *inst) {
11584 <<
"not yet implemented: " << inst->
getName();
11587 if (isOutermostLoopWrapper)
11594 static llvm::cl::opt<
bool,
true> option(
11595 "openmp-disable-virtual-collapse", llvm::cl::Hidden,
11596 llvm::cl::desc(
"Disable virtual collapse of eligible host loops"),
11597 llvm::cl::location(disableVirtualCollapse));
11601 registry.
insert<omp::OpenMPDialect>();
11603 dialect->addInterfaces<OpenMPDialectLLVMIRTranslationInterface>();
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static mlir::LogicalResult buildDependData(OperandRange dependVars, std::optional< ArrayAttr > dependKinds, OperandRange dependIterated, std::optional< ArrayAttr > dependIteratedKinds, llvm::IRBuilderBase &builder, mlir::LLVM::ModuleTranslation &moduleTranslation, llvm::OpenMPIRBuilder::DependenciesInfo &taskDeps)
static LogicalResult convertOmpAtomicUpdate(omp::AtomicUpdateOp &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP atomic update operation using OpenMPIRBuilder.
static llvm::omp::OrderKind convertOrderKind(std::optional< omp::ClauseOrderKind > o)
Convert Order attribute to llvm::omp::OrderKind.
static void mapParentWithMembers(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, DataLayout &dl, MapInfosTy &combinedInfo, MapInfoData &mapData, uint64_t mapDataIndex, llvm::omp::OpenMPOffloadMappingFlags memberOfFlag, TargetDirectiveEnumTy targetDirective)
static llvm::OpenMPIRBuilder::CollapseIVMapping selectCollapseIVMapping(omp::LoopNestOp loopOp, bool isTargetDevice)
Select Virtual only for two host worksharing loops.
static llvm::OpenMPIRBuilder::InsertPointTy findAllocInsertPoints(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::SmallVectorImpl< llvm::BasicBlock * > *deallocBlocks=nullptr)
Find the insertion point for allocas given the current insertion point for normal operations in the b...
static void sortMapIndices(llvm::SmallVectorImpl< size_t > &indices, omp::MapInfoOp mapInfo, bool first=true)
static LogicalResult convertOmpAtomicCapture(omp::AtomicCaptureOp atomicCaptureOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertOmpTaskloopContextOp(omp::TaskloopContextOp contextOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static Operation * getGlobalOpFromValue(Value value)
static llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind convertToCaptureClauseKind(mlir::omp::DeclareTargetCaptureClause captureClause)
static omp::MapInfoOp getFirstOrLastMappedMemberPtr(omp::MapInfoOp mapInfo, bool first)
static LogicalResult convertOmpDispatch(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Convert 'dispatch' operation into LLVM IR.
static OpTy castOrGetParentOfType(Operation *op, bool immediateParent=false)
If op is of the given type parameter, return it casted to that type. Otherwise, if its immediate pare...
static LogicalResult convertOmpOrderedRegion(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'ordered_region' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult convertFreeSharedMemOp(omp::FreeSharedMemOp freeMemOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertTargetFreeMemOp(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertOmpAtomicWrite(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an omp.atomic.write operation to LLVM IR.
static OwningAtomicReductionGen makeAtomicReductionGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Create an OpenMPIRBuilder-compatible atomic reduction generator for the given reduction declaration.
static void invalidateOmpLoop(LLVM::ModuleTranslation &moduleTranslation, Value mlir)
Mark an OpenMP loop as having been consumed.
static OwningDataPtrPtrReductionGen makeRefDataPtrGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, bool isByRef)
Create an OpenMPIRBuilder-compatible data_ptr_ptr reduction generator for the given reduction declara...
static llvm::Value * getRefPtrIfDeclareTarget(Value value, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Function * emitTaskReductionCombFn(omp::DeclareReductionOp decl, StringRef baseName, LLVM::ModuleTranslation &moduleTranslation)
Build an outlined combiner helper for a task_reduction declare_reduction op. Signature: void(ptr lhs,...
static LogicalResult convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
static LogicalResult applyUnrollHeuristic(omp::UnrollHeuristicOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp unroll / "!$omp unroll" transformation using the OpenMPIRBuilder.
static LogicalResult convertOmpMaster(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'master' operation into LLVM IR using OpenMPIRBuilder.
static void getAsIntegers(ArrayAttr values, llvm::SmallVector< int64_t > &ints)
static void emitComplexAtomicCmpXchg(llvm::IRBuilderBase &builder, llvm::Value *llvmX, llvm::Type *complexTy, llvm::Value *eVal, llvm::Value *dVal, llvm::AtomicOrdering atomicOrdering, llvm::AtomicOrdering failOrdering, bool isWeak, llvm::Value *&oldComplex, llvm::Value *&cmpOk)
Emit an IEEE-754-correct cmpxchg for a complex (struct-typed) atomic compare with fcmp oeq....
static llvm::Value * findAssociatedValue(Value privateVar, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::DenseMap< Value, Value > *mappedPrivateVars=nullptr)
Return the llvm::Value * corresponding to the privateVar that is being privatized....
static llvm::Expected< llvm::Value * > lookupOrTranslatePureValue(Value value, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder)
Look up the given value in the mapping, and if it's not there, translate its defining operation at th...
static void emitTaskReductionModifierFini(bool isWorksharing, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Emits __kmpc_task_reduction_modifier_fini(loc, gtid, is_ws) at the current builder insertion point,...
static LogicalResult convertOmpInteropUseOp(omp::InteropUseOp useOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertOmpTaskwaitOp(omp::TaskwaitOp twOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult collectAndValidateTaskloopRedDecls(Operation *contextOp, std::optional< ArrayAttr > syms, StringRef opName, StringRef clauseName, SmallVectorImpl< omp::DeclareReductionOp > &out)
Look up and validate the declare_reduction ops referenced by a reduction-like clause on the omp....
static LogicalResult convertOmpLoopNest(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP loop nest into LLVM IR using OpenMPIRBuilder.
static LogicalResult allocAndInitializeReductionVars(Operation &op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::OpenMPIRBuilder::InsertPointTy &allocaIP, ReductionVarsInfo &redInfo)
static mlir::LogicalResult fillIteratorLoop(mlir::omp::IteratorOp itersOp, llvm::IRBuilderBase &builder, mlir::LLVM::ModuleTranslation &moduleTranslation, IteratorInfo &iterInfo, llvm::StringRef loopName, IteratorStoreEntryTy genStoreEntry)
static void createAlteredByCaptureMap(MapInfoData &mapData, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder)
static LogicalResult convertOmpTaskOp(omp::TaskOp taskOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP task construct into LLVM IR using OpenMPIRBuilder.
static void genMapInfos(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl, MapInfosTy &combinedInfo, MapInfoData &mapData, TargetDirectiveEnumTy targetDirective)
static llvm::AtomicOrdering convertAtomicOrdering(std::optional< omp::ClauseMemoryOrderKind > ao)
Convert an Atomic Ordering attribute to llvm::AtomicOrdering.
static LogicalResult convertOmpInteropInitOp(omp::InteropInitOp initOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static void setInsertPointForPossiblyEmptyBlock(llvm::IRBuilderBase &builder, llvm::BasicBlock *block=nullptr)
static void mapInitializationArgs(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, const ReductionVarsInfo::VarInfo &redVarInfo)
Map input arguments to reduction initialization region.
static mlir::LogicalResult convertIteratorRegion(llvm::Value *linearIV, IteratorInfo &iterInfo, mlir::Region &iteratorRegion, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
llvm::function_ref< void(llvm::Value *linearIV, mlir::omp::YieldOp yield)> IteratorStoreEntryTy
static llvm::Function * emitTaskReductionInitFn(omp::DeclareReductionOp decl, StringRef baseName, LLVM::ModuleTranslation &moduleTranslation)
Build an outlined init helper for a task_reduction declare_reduction op. Signature: void(ptr priv,...
static LogicalResult convertOmpSections(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Expected< llvm::BasicBlock * > allocatePrivateVars(T op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, PrivateVarsInfo &privateVarsInfo, llvm::OpenMPIRBuilder::InsertPointTy &allocaIP, llvm::DenseMap< Value, Value > *mappedPrivateVars=nullptr, std::optional< llvm::OpenMPIRBuilder::InsertPointTy > allocatorIP=std::nullopt)
Allocate and initialize delayed private variables. Returns the basic block which comes after all of t...
static LogicalResult applyUnrollPartial(omp::UnrollPartialOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp unroll partial / !$omp unroll partial transformation using the OpenMPIRBuilder.
static void addNonContiguousUpdate(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, MapInfoData &mapData, size_t mapDataIdx, MapInfosTy &combinedInfo)
Describe a bounded update as a set of contiguous pieces. Bounds follow the dialect's normalized faste...
static LogicalResult convertOmpCritical(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'critical' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult convertTargetAllocMemOp(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static omp::DistributeOp getDistributeCapturingTeamsReduction(omp::TeamsOp teamsOp)
static LogicalResult convertOmpCanonicalLoopOp(omp::CanonicalLoopOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Convert an omp.canonical_loop to LLVM-IR.
static LogicalResult convertOmpTargetData(Operation *op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static std::optional< int64_t > extractConstInteger(Value value)
If the given value is defined by an llvm.mlir.constant operation and it is of an integer type,...
static llvm::Expected< llvm::Value * > initPrivateVar(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, omp::PrivateClauseOp &privDecl, llvm::Value *nonPrivateVar, BlockArgument &blockArg, llvm::Value *llvmPrivateVar, llvm::BasicBlock *privInitBlock, llvm::DenseMap< Value, Value > *mappedPrivateVars=nullptr)
Initialize a single (first)private variable. You probably want to use allocateAndInitPrivateVars inst...
static OpenMPTranslationState & getOpenMPState(LLVM::ModuleTranslation &moduleTranslation)
static mlir::LogicalResult buildAffinityData(mlir::omp::TaskOp &taskOp, llvm::IRBuilderBase &builder, mlir::LLVM::ModuleTranslation &moduleTranslation, llvm::OpenMPIRBuilder::AffinityData &ad)
static LogicalResult convertOmpSimd(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP simd loop into LLVM IR using OpenMPIRBuilder.
static void processIndividualMap(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, MapInfoData &mapData, size_t mapDataIdx, MapInfosTy &combinedInfo, TargetDirectiveEnumTy targetDirective, llvm::omp::OpenMPOffloadMappingFlags memberOfFlag=llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE, bool isTargetParam=true, int mapDataParentIdx=-1)
This function handles the insertion of a single item of map data from MapInfoData into the OMPIRBuild...
static LogicalResult convertOmpInteropDestroyOp(omp::InteropDestroyOp destroyOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static void mapOmpLoop(LLVM::ModuleTranslation &moduleTranslation, Value mlir, llvm::CanonicalLoopInfo *llvm)
Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR OpenMPIRBuilder CanonicalLoopInfo...
static LogicalResult convertOmpDistribute(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Value * getAllocationSize(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, T op)
static LogicalResult allocReductionVars(Operation &op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, const llvm::OpenMPIRBuilder::InsertPointTy &allocaIP, ReductionVarsInfo &redInfo)
Allocate space for privatized reduction variables.
static llvm::Function * getOmpTargetAlloc(llvm::IRBuilderBase &builder, llvm::Module *llvmModule)
static llvm::omp::OMPDynGroupprivateFallbackType getDynGroupprivateFallbackType(omp::FallbackModifierAttr fallbackAttr)
static llvm::Expected< llvm::Function * > emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::StringRef mapperFuncName, TargetDirectiveEnumTy targetDirective)
static LogicalResult convertOmpOrdered(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'ordered' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult cleanupPrivateVars(T op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, Location loc, PrivateVarsInfo &privateVarsInfo)
static void processMapWithMembersOf(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, DataLayout &dl, MapInfosTy &combinedInfo, MapInfoData &mapData, uint64_t mapDataIndex, TargetDirectiveEnumTy targetDirective)
static LogicalResult convertOmpMasked(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'masked' operation into LLVM IR using OpenMPIRBuilder.
static llvm::CanonicalLoopInfo * lookupOMPLoop(LLVM::ModuleTranslation &moduleTranslation, Value mlir)
Find the LLVM-IR loop that represents an MLIR loop.
static llvm::AtomicRMWInst::BinOp convertBinOpToAtomic(Operation &op)
Converts an LLVM dialect binary operation to the corresponding enum value for atomicrmw supported bin...
static LogicalResult createReductionsAndCleanup(Operation &op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::OpenMPIRBuilder::InsertPointTy &allocaIP, ReductionVarsInfo &redInfo, bool isNowait=false, bool isTeamsReduction=false)
static LogicalResult convertOmpCancel(omp::CancelOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static int getMapDataMemberIdx(MapInfoData &mapData, omp::MapInfoOp memberOp)
allocatedType moduleTranslation static convertType(allocatedType) LogicalResult inlineOmpRegionCleanup(llvm::SmallVectorImpl< Region * > &cleanupRegions, llvm::ArrayRef< llvm::Value * > privateVariables, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, StringRef regionName, bool shouldLoadCleanupRegionArg=true)
handling of DeclareReductionOp's cleanup region
static LogicalResult applyFuse(omp::FuseOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp fuse / !$omp fuse transformation using the OpenMPIRBuilder.
static llvm::Value * materializeRegionArgValue(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, BlockArgument regionArg, llvm::Value *value)
static LogicalResult convertOmpScope(omp::ScopeOp &scopeOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP scope construct into LLVM IR.
static bool isPrivatizeableAttachMap(omp::ClauseMapFlags mapType)
static llvm::Value * getSizeInBytes(DataLayout &dl, const mlir::Type &type, Operation *clauseOp, llvm::Value *basePointer, llvm::Type *baseType, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Error initPrivateVars(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, PrivateVarsInfo &privateVarsInfo, llvm::DenseMap< Value, Value > *mappedPrivateVars=nullptr)
static LogicalResult convertAllocSharedMemOp(omp::AllocSharedMemOp allocMemOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::CanonicalLoopInfo * findCurrentLoopInfo(LLVM::ModuleTranslation &moduleTranslation)
Find the loop information structure for the loop nest being translated.
static OwningReductionGen makeReductionGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Create an OpenMPIRBuilder-compatible reduction generator for the given reduction declaration.
static void storeAffinityEntry(llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, llvm::Value *affinityList, llvm::Value *index, llvm::Value *addr, llvm::Value *len)
static LogicalResult convertOmpParallel(omp::ParallelOp opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts the OpenMP parallel operation to LLVM IR.
static void pushCancelFinalizationCB(SmallVectorImpl< llvm::UncondBrInst * > &cancelTerminators, llvm::IRBuilderBase &llvmBuilder, llvm::OpenMPIRBuilder &ompBuilder, mlir::Operation *op, llvm::omp::Directive cancelDirective)
Shared implementation of a callback which adds a termiator for the new block created for the branch t...
static LogicalResult inlineConvertOmpRegions(Region ®ion, StringRef blockName, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, SmallVectorImpl< llvm::Value * > *continuationBlockArgs=nullptr)
Translates the blocks contained in the given region and appends them to at the current insertion poin...
static void getTargetEntryUniqueInfo(llvm::TargetRegionEntryInfo &targetInfo, omp::TargetOp targetOp, llvm::OpenMPIRBuilder &ompBuilder, llvm::vfs::FileSystem &vfs, llvm::StringRef parentName="")
static LogicalResult convertOmpThreadprivate(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP Threadprivate operation into LLVM IR using OpenMPIRBuilder.
static omp::PrivateClauseOp findPrivatizer(Operation *from, SymbolRefAttr symbolName)
Looks up from the operation from and returns the PrivateClauseOp with name symbolName.
static llvm::OpenMPIRBuilder * getOpenMPBuilder(LLVM::ModuleTranslation &moduleTranslation)
Returns the OpenMP IR builder associated with the LLVM IR module being constructed.
static LogicalResult applyUnrollFull(omp::UnrollFullOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp unroll full / !$omp unroll full transformation using the OpenMPIRBuilder.
static LogicalResult convertOmpGroupprivate(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP groupprivate operation into LLVM IR.
static llvm::Expected< llvm::Function * > getOrCreateUserDefinedMapperFunc(Operation *op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, TargetDirectiveEnumTy targetDirective)
static llvm::Value * getSourceLocIdentFromOp(llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, Operation *op)
static uint64_t getTypeByteSize(mlir::Type type, const DataLayout &dl)
static llvm::SmallString< 64 > getDeclareTargetRefPtrSuffix(LLVM::GlobalOp globalOp, llvm::OpenMPIRBuilder &ompBuilder, llvm::vfs::FileSystem &vfs)
static LogicalResult completePrivateVars(mlir::Operation *op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, const PrivateVarsInfo &privateVarsInfo, bool insertBarrier, ArrayRef< llvm::Value * > moldVars={}, ArrayRef< llvm::Value * > llvmPrivateVars={}, DenseMap< Value, Value > *mappedPrivateVars=nullptr)
Applies the firstprivate copy region for each variable, pairing the mold values with the private allo...
static void extractHostEvalClauses(omp::TargetOp targetOp, Value &numThreads, Value &numTeamsLower, Value &numTeamsUpper, Value &threadLimit, llvm::SmallVectorImpl< Value > *lowerBounds=nullptr, llvm::SmallVectorImpl< Value > *upperBounds=nullptr, llvm::SmallVectorImpl< Value > *steps=nullptr)
Follow uses of host_eval-defined block arguments of the given omp.target operation and populate outpu...
static llvm::Expected< llvm::BasicBlock * > convertOmpOpRegions(Region ®ion, StringRef blockName, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, SmallVectorImpl< llvm::PHINode * > *continuationBlockPHIs=nullptr)
Converts the given region that appears within an OpenMP dialect operation to LLVM IR,...
static LogicalResult extractAtomicComparePattern(Block &block, llvm::function_ref< llvm::Value *(mlir::Value)> materializeValue, omp::AtomicCompareOp atomicCompareOp, AtomicComparePatternInfo &info)
Extract comparison predicate, expected value (e), desired value (d), and related flags from an atomic...
static LogicalResult convertOmpAtomicCompare(omp::AtomicCompareOp atomicCompareOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an omp.atomic.compare operation to LLVM IR.
static void hoistMapperAllocasToEntry(llvm::Function &mapperFn)
The mapper body (and any iterator regions in it) is emitted inside the mapper's per-element loop,...
static LogicalResult convertAllocateDirOp(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, const OpenMPDialectLLVMIRTranslationInterface &ompIface)
static bool constructIsCancellable(Operation *op)
Returns true if the construct contains omp.cancel or omp.cancellation_point.
static llvm::omp::OpenMPOffloadMappingFlags convertClauseMapFlags(omp::ClauseMapFlags mlirFlags)
static LogicalResult convertAllocatorVars(Operation &op, ValueRange allocatorVars, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, PrivateVarsInfo &privateVarsInfo)
static void buildDependDataLocator(std::optional< ArrayAttr > dependKinds, OperandRange dependVars, LLVM::ModuleTranslation &moduleTranslation, SmallVectorImpl< llvm::OpenMPIRBuilder::DependData > &dds)
static std::optional< llvm::omp::OMPAtomicCompareOp > convertFCmpPredicateToAtomicCompareOp(LLVM::FCmpPredicate predicate)
Helper to extract the OMPAtomicCompareOp from a floating-point comparison predicate....
static llvm::Value * emitTaskReductionInitCall(ArrayRef< omp::DeclareReductionOp > redDecls, ArrayRef< llvm::Value * > origPtrs, StringRef helperNamePrefix, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP, LLVM::ModuleTranslation &moduleTranslation, bool isModifier=false, bool isWorksharing=false)
Emit the per-taskgroup task_reduction descriptor array and the __kmpc_taskred_init runtime call....
static llvm::Expected< llvm::Value * > getPrivateDataAddress(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, omp::PrivateClauseOp privatizer, llvm::Value *var)
Returns the address of the data in var, via the data_address region.
static llvm::omp::ProcBindKind getProcBindKind(omp::ClauseProcBindKind kind)
Convert ProcBindKind from MLIR-generated enum to LLVM enum.
static void fillAffinityLocators(Operation::operand_range affinityVars, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::Value *affinityList)
static LogicalResult convertOmpTaskloopWrapperOp(omp::TaskloopWrapperOp loopWrapperOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
The correct entry point is convertOmpTaskloopContextOp. This gets called whilst lowering the body of ...
static void getOverlappedMembers(llvm::SmallVectorImpl< size_t > &overlapMapDataIdxs, omp::MapInfoOp parentOp)
static LogicalResult convertOmpSingle(omp::SingleOp &singleOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP single construct into LLVM IR using OpenMPIRBuilder.
static bool isDeclareTargetTo(Value value)
static uint64_t getArrayElementSizeInBits(LLVM::LLVMArrayType arrTy, DataLayout &dl)
static void popCancelFinalizationCB(const ArrayRef< llvm::UncondBrInst * > cancelTerminators, llvm::OpenMPIRBuilder &ompBuilder, llvm::BasicBlock *afterBB)
If we cancelled the construct, we should branch to the finalization block of that construct....
static void collectReductionDecls(T op, SmallVectorImpl< omp::DeclareReductionOp > &reductions)
Populates reductions with reduction declarations used in the given op.
static LogicalResult handleError(llvm::Error error, Operation &op)
static LogicalResult convertOmpTarget(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseKind convertToDeviceClauseKind(mlir::omp::DeclareTargetDeviceType deviceClause)
static std::optional< llvm::omp::OMPAtomicCompareOp > convertICmpPredicateToAtomicCompareOp(LLVM::ICmpPredicate predicate)
Helper to extract the OMPAtomicCompareOp from an integer comparison predicate. Returns std::nullopt f...
static llvm::Error computeTaskloopBounds(omp::LoopNestOp loopOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::Value *&lbVal, llvm::Value *&ubVal, llvm::Value *&stepVal)
static LogicalResult checkImplementationStatus(Operation &op)
Check whether translation to LLVM IR for the given operation is currently supported.
static llvm::IRBuilderBase::InsertPoint createDeviceArgumentAccessor(omp::TargetOp targetOp, MapInfoData &mapData, llvm::Argument &arg, llvm::Value *input, llvm::Value *&retVal, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase::InsertPoint allocaIP, llvm::IRBuilderBase::InsertPoint codeGenIP, llvm::ArrayRef< llvm::IRBuilderBase::InsertPoint > deallocIPs)
static LogicalResult convertOmpCancellationPoint(omp::CancellationPointOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::omp::AtomicControl extractAtomicControlFlags(omp::AtomicUpdateOp atomicUpdateOp)
static uint64_t getReductionDataSize(OpTy &op)
static bool opMightBeSafeForBarriers(mlir::Operation *op)
A compiler-generated barrier is unsafe when only part of the current team can reach it....
static LogicalResult convertOmpAtomicRead(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Convert omp.atomic.read operation to LLVM IR.
static llvm::omp::Directive convertCancellationConstructType(omp::ClauseCancellationConstructType directive)
static void initTargetDefaultAttrs(omp::TargetOp targetOp, Operation *capturedOp, llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &attrs, bool isTargetDevice, bool isGPU)
Populate default MinTeams, MaxTeams and MaxThreads to their default values as stated by the correspon...
static llvm::AtomicOrdering getAtomicCompareFailureOrdering(omp::AtomicCompareOp atomicCompareOp, llvm::AtomicOrdering atomicOrdering)
Compute the cmpxchg failure ordering for an atomic compare op: use the fail clause ordering when pres...
static llvm::Value * emitTaskReductionModifierInitCall(OpTy op, ArrayRef< omp::DeclareReductionOp > reductionDecls, ArrayRef< llvm::Value * > privateReductionVariables, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP, LLVM::ModuleTranslation &moduleTranslation, bool isWorksharing)
Register only the task-modified items. All items still participate in the enclosing construct's ordin...
static llvm::omp::RTLDependenceKindTy convertDependKind(mlir::omp::ClauseTaskDepend kind)
static void initTargetRuntimeAttrs(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, omp::TargetOp targetOp, Operation *capturedOp, llvm::OpenMPIRBuilder::TargetKernelRuntimeAttrs &attrs)
Gather LLVM runtime values for all clauses evaluated in the host that are passed to the kernel invoca...
static LogicalResult emitPrivatizationBarrier(mlir::Operation *op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static ComplexComparePattern detectComplexCompareEq(Block &block)
Detect a decomposed complex equality comparison in an atomic compare region: re_x = llvm....
static LogicalResult convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static Value getBaseValueForTypeLookup(Value value)
static bool isHostDeviceOp(Operation *op)
static LogicalResult convertDeclareTargetAttr(Operation *op, mlir::omp::DeclareTargetAttr attribute, llvm::OpenMPIRBuilder *ompBuilder, LLVM::ModuleTranslation &moduleTranslation)
static bool isDeclareTargetLink(Value value)
static LogicalResult convertFlagsAttr(Operation *op, mlir::omp::FlagsAttr attribute, LLVM::ModuleTranslation &moduleTranslation)
Lowers the FlagsAttr which is applied to the module when offloading. This attribute contains OpenMP R...
static bool checkIfPointerMap(omp::MapInfoOp mapOp)
static llvm::Type * getAllocatedLlvmTypeForVariable(Value var, Value baseVar, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult applyTile(omp::TileOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp tile / !$omp tile transformation using the OpenMPIRBuilder.
static LogicalResult convertAllocateFreeOp(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, const OpenMPDialectLLVMIRTranslationInterface &ompIface)
static StringRef getMapClauseName(omp::MapInfoOp mapOp)
static std::vector< llvm::Value * > calculateBoundsOffset(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, bool isArrayTy, OperandRange bounds, bool &isByteOffset)
This function calculates the array/pointer offset for map data provided with bounds operations,...
static llvm::Function * getOmpTargetFree(llvm::IRBuilderBase &builder, llvm::Module *llvmModule)
static LogicalResult convertOmpTaskgroupOp(omp::TaskgroupOp tgOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP taskgroup construct into LLVM IR using OpenMPIRBuilder.
static std::optional< llvm::Value * > getDynamicAllocatedSize(Value var, Value baseVar, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, const llvm::DataLayout &dataLayout)
static void collectMapDataFromMapOperands(MapInfoData &mapData, SmallVectorImpl< Value > &mapVars, LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl, llvm::IRBuilderBase &builder, ArrayRef< Value > useDevPtrOperands={}, ArrayRef< Value > useDevAddrOperands={}, ArrayRef< Value > hasDevAddrOperands={})
static Operation * genLoop(CodegenEnv &env, OpBuilder &builder, LoopId curr, unsigned numCases, bool needsUniv, ArrayRef< TensorLevel > tidLvls)
Generates a for-loop or a while-loop, depending on whether it implements singleton iteration or co-it...
#define MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CLASS_NAME)
Attributes are known-constant values of operations.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
OpListType & getOperations()
Operation * getTerminator()
Get the terminator operation of this block.
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
The main mechanism for performing data layout queries.
llvm::TypeSize getTypeSize(Type t) const
Returns the size of the given type in the current scope.
llvm::TypeSize getTypeSizeInBits(Type t) const
Returns the size in bits of the given type in the current scope.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
An instance of this location represents a tuple of file, line number, and column number.
Base class for state that lives as long as the module translation.
Implementation class for module translation.
llvm::BasicBlock * lookupBlock(Block *block) const
Finds an LLVM IR basic block that corresponds to the given MLIR block.
WalkResult stackWalk(llvm::function_ref< WalkResult(T &)> callback)
Calls callback for every ModuleTranslation stack frame of type T starting from the top of the stack.
void stackPush(Args &&...args)
Creates a stack frame of type T on ModuleTranslation stack.
LogicalResult convertBlock(Block &bb, bool ignoreArguments, llvm::IRBuilderBase &builder)
Translates the contents of the given block to LLVM IR using this translator.
SmallVector< llvm::Value * > lookupValues(ValueRange values)
Looks up remapped a list of remapped values.
void mapFunction(StringRef name, llvm::Function *func)
Stores the mapping between a function name and its LLVM IR representation.
T & getOrCreateExtension(Args &&...args)
Returns the extension of type T, constructing it from args on first use.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
SymbolTableCollection & symbolTable()
llvm::Type * convertType(Type type)
Converts the type from MLIR LLVM dialect to LLVM.
llvm::vfs::FileSystem & getFileSystem()
Returns the virtual filesystem to use for file operations.
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
SaveStateStack< T, ModuleTranslation > SaveStack
RAII object calling stackPush/stackPop on construction/destruction.
void remapAllValuesWith(llvm::Value *oldValue, llvm::Value *newValue)
Remap old value with new value in the MLIR-to-LLVM value map so later translations use the replacemen...
LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder)
Converts the given MLIR operation into LLVM IR using this translator.
llvm::Function * lookupFunction(StringRef name) const
Finds an LLVM IR function by its name.
void mapBlock(Block *mlir, llvm::BasicBlock *llvm)
Stores the mapping between an MLIR block and LLVM IR basic block.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
void stackPop()
Pops the last element from the ModuleTranslation stack.
void forgetMapping(Region ®ion)
Removes the mapping for blocks contained in the region and values defined in these blocks.
void mapValue(Value mlir, llvm::Value *llvm)
Stores the mapping between an MLIR value and its LLVM IR counterpart.
llvm::LLVMContext & getLLVMContext() const
Returns the LLVM context in which the IR is being constructed.
Utility class to translate MLIR LLVM dialect types to LLVM IR.
unsigned getPreferredAlignment(Type type, const llvm::DataLayout &layout)
Returns the preferred alignment for the type given the data layout.
T findInstanceOf()
Return an instance of the given location type if one is nested under the current location.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
void appendDialectRegistry(const DialectRegistry ®istry)
Append the contents of the given dialect registry to the registry associated with this context.
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
This class implements the operand iterators for the Operation class.
StringAttr getIdentifier() const
Return the name of this operation as a StringAttr.
Operation is the basic unit of execution within MLIR.
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Value getOperand(unsigned idx)
InFlightDiagnostic emitWarning(const Twine &message={})
Emit a warning about this operation, reporting up to any diagnostic handlers that may be listening.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
unsigned getNumOperands()
OperandRange operand_range
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
OperationName getName()
The name of an operation is the key identifier for it.
operand_range getOperands()
Returns an iterator on the underlying Value's.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
user_range getUsers()
Returns a range of all users.
result_range getResults()
MLIRContext * getContext()
Return the context this operation is associated with.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
BlockArgListType getArguments()
unsigned getNumArguments()
Operation * getParentOp()
Return the parent operation this region is attached to.
BlockListType & getBlocks()
bool hasOneBlock()
Return true if this region has exactly one block.
Concrete CRTP base class for StateStack frames.
@ Private
The symbol is private and may only be referenced by SymbolRefAttrs local to the operations within the...
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
user_range getUsers() const
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
bool wasInterrupted() const
Returns true if the walk was interrupted.
static WalkResult interrupt()
The OpAsmOpInterface, see OpAsmInterface.td for more details.
void connectPHINodes(Region ®ion, const ModuleTranslation &state)
For all blocks in the region that were converted to LLVM IR using the given ModuleTranslation,...
llvm::Constant * createMappingInformation(Location loc, llvm::OpenMPIRBuilder &builder, StringRef mapName={})
Create a constant string representing the mapping information extracted from the MLIR location inform...
llvm::Constant * createSourceLocStrFromLocation(Location loc, llvm::OpenMPIRBuilder &builder, StringRef name, uint32_t &strLen, bool ForOffloadMap=false)
Create a constant string location from the MLIR Location information.
int64_t getOpenMPVersionAttribute(ModuleOp module, int64_t fallback=-1)
Returns the value of the omp.version attribute, if present, or the fallback.
bool opInSharedDeviceContext(Operation &op)
Check whether the given operation is located in a context where an allocation to be used by multiple ...
bool allocaUsesRequireSharedMem(Value alloc)
Check whether the value representing an allocation, assumed to have been defined in a shared device c...
auto getDims(VectorType vType)
Returns a range over the dims (size and scalability) of a VectorType.
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
SetVector< Block * > getBlocksSortedByDominance(Region ®ion)
Gets a list of blocks that is sorted according to dominance.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
void registerOpenMPDialectTranslation(DialectRegistry ®istry)
Register the OpenMP dialect and the translation from it to the LLVM IR in the given registry;.
llvm::SetVector< T, Vector, Set, N > SetVector
SmallVector< Loops, 8 > tile(ArrayRef< scf::ForOp > forOps, ArrayRef< Value > sizes, ArrayRef< scf::ForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
void registerOpenMPTranslationCLOptions()
Register OpenMP translation command-line options before parsing them.
Holds the extracted comparison pattern information from an atomic compare region.
llvm::omp::OMPAtomicCompareOp compareOp
Result of matching the decomposed complex equality pattern inside an atomic compare region.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.