1 //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This provides a class for OpenMP runtime code generation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGCXXABI.h" 14 #include "CGCleanup.h" 15 #include "CGOpenMPRuntime.h" 16 #include "CGRecordLayout.h" 17 #include "CodeGenFunction.h" 18 #include "clang/CodeGen/ConstantInitBuilder.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/StmtOpenMP.h" 21 #include "clang/Basic/BitmaskEnum.h" 22 #include "llvm/ADT/ArrayRef.h" 23 #include "llvm/Bitcode/BitcodeReader.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/GlobalValue.h" 26 #include "llvm/IR/Value.h" 27 #include "llvm/Support/Format.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include <cassert> 30 31 using namespace clang; 32 using namespace CodeGen; 33 34 namespace { 35 /// Base class for handling code generation inside OpenMP regions. 36 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo { 37 public: 38 /// Kinds of OpenMP regions used in codegen. 39 enum CGOpenMPRegionKind { 40 /// Region with outlined function for standalone 'parallel' 41 /// directive. 42 ParallelOutlinedRegion, 43 /// Region with outlined function for standalone 'task' directive. 44 TaskOutlinedRegion, 45 /// Region for constructs that do not require function outlining, 46 /// like 'for', 'sections', 'atomic' etc. directives. 47 InlinedRegion, 48 /// Region with outlined function for standalone 'target' directive. 49 TargetRegion, 50 }; 51 52 CGOpenMPRegionInfo(const CapturedStmt &CS, 53 const CGOpenMPRegionKind RegionKind, 54 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind, 55 bool HasCancel) 56 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind), 57 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {} 58 59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind, 60 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind, 61 bool HasCancel) 62 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen), 63 Kind(Kind), HasCancel(HasCancel) {} 64 65 /// Get a variable or parameter for storing global thread id 66 /// inside OpenMP construct. 67 virtual const VarDecl *getThreadIDVariable() const = 0; 68 69 /// Emit the captured statement body. 70 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override; 71 72 /// Get an LValue for the current ThreadID variable. 73 /// \return LValue for thread id variable. This LValue always has type int32*. 74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF); 75 76 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {} 77 78 CGOpenMPRegionKind getRegionKind() const { return RegionKind; } 79 80 OpenMPDirectiveKind getDirectiveKind() const { return Kind; } 81 82 bool hasCancel() const { return HasCancel; } 83 84 static bool classof(const CGCapturedStmtInfo *Info) { 85 return Info->getKind() == CR_OpenMP; 86 } 87 88 ~CGOpenMPRegionInfo() override = default; 89 90 protected: 91 CGOpenMPRegionKind RegionKind; 92 RegionCodeGenTy CodeGen; 93 OpenMPDirectiveKind Kind; 94 bool HasCancel; 95 }; 96 97 /// API for captured statement code generation in OpenMP constructs. 98 class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo { 99 public: 100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar, 101 const RegionCodeGenTy &CodeGen, 102 OpenMPDirectiveKind Kind, bool HasCancel, 103 StringRef HelperName) 104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind, 105 HasCancel), 106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) { 107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region."); 108 } 109 110 /// Get a variable or parameter for storing global thread id 111 /// inside OpenMP construct. 112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; } 113 114 /// Get the name of the capture helper. 115 StringRef getHelperName() const override { return HelperName; } 116 117 static bool classof(const CGCapturedStmtInfo *Info) { 118 return CGOpenMPRegionInfo::classof(Info) && 119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == 120 ParallelOutlinedRegion; 121 } 122 123 private: 124 /// A variable or parameter storing global thread id for OpenMP 125 /// constructs. 126 const VarDecl *ThreadIDVar; 127 StringRef HelperName; 128 }; 129 130 /// API for captured statement code generation in OpenMP constructs. 131 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo { 132 public: 133 class UntiedTaskActionTy final : public PrePostActionTy { 134 bool Untied; 135 const VarDecl *PartIDVar; 136 const RegionCodeGenTy UntiedCodeGen; 137 llvm::SwitchInst *UntiedSwitch = nullptr; 138 139 public: 140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar, 141 const RegionCodeGenTy &UntiedCodeGen) 142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {} 143 void Enter(CodeGenFunction &CGF) override { 144 if (Untied) { 145 // Emit task switching point. 146 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue( 147 CGF.GetAddrOfLocalVar(PartIDVar), 148 PartIDVar->getType()->castAs<PointerType>()); 149 llvm::Value *Res = 150 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation()); 151 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done."); 152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB); 153 CGF.EmitBlock(DoneBB); 154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock); 155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp.")); 156 UntiedSwitch->addCase(CGF.Builder.getInt32(0), 157 CGF.Builder.GetInsertBlock()); 158 emitUntiedSwitch(CGF); 159 } 160 } 161 void emitUntiedSwitch(CodeGenFunction &CGF) const { 162 if (Untied) { 163 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue( 164 CGF.GetAddrOfLocalVar(PartIDVar), 165 PartIDVar->getType()->castAs<PointerType>()); 166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()), 167 PartIdLVal); 168 UntiedCodeGen(CGF); 169 CodeGenFunction::JumpDest CurPoint = 170 CGF.getJumpDestInCurrentScope(".untied.next."); 171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock); 172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp.")); 173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()), 174 CGF.Builder.GetInsertBlock()); 175 CGF.EmitBranchThroughCleanup(CurPoint); 176 CGF.EmitBlock(CurPoint.getBlock()); 177 } 178 } 179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); } 180 }; 181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS, 182 const VarDecl *ThreadIDVar, 183 const RegionCodeGenTy &CodeGen, 184 OpenMPDirectiveKind Kind, bool HasCancel, 185 const UntiedTaskActionTy &Action) 186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel), 187 ThreadIDVar(ThreadIDVar), Action(Action) { 188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region."); 189 } 190 191 /// Get a variable or parameter for storing global thread id 192 /// inside OpenMP construct. 193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; } 194 195 /// Get an LValue for the current ThreadID variable. 196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override; 197 198 /// Get the name of the capture helper. 199 StringRef getHelperName() const override { return ".omp_outlined."; } 200 201 void emitUntiedSwitch(CodeGenFunction &CGF) override { 202 Action.emitUntiedSwitch(CGF); 203 } 204 205 static bool classof(const CGCapturedStmtInfo *Info) { 206 return CGOpenMPRegionInfo::classof(Info) && 207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == 208 TaskOutlinedRegion; 209 } 210 211 private: 212 /// A variable or parameter storing global thread id for OpenMP 213 /// constructs. 214 const VarDecl *ThreadIDVar; 215 /// Action for emitting code for untied tasks. 216 const UntiedTaskActionTy &Action; 217 }; 218 219 /// API for inlined captured statement code generation in OpenMP 220 /// constructs. 221 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo { 222 public: 223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI, 224 const RegionCodeGenTy &CodeGen, 225 OpenMPDirectiveKind Kind, bool HasCancel) 226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel), 227 OldCSI(OldCSI), 228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {} 229 230 // Retrieve the value of the context parameter. 231 llvm::Value *getContextValue() const override { 232 if (OuterRegionInfo) 233 return OuterRegionInfo->getContextValue(); 234 llvm_unreachable("No context value for inlined OpenMP region"); 235 } 236 237 void setContextValue(llvm::Value *V) override { 238 if (OuterRegionInfo) { 239 OuterRegionInfo->setContextValue(V); 240 return; 241 } 242 llvm_unreachable("No context value for inlined OpenMP region"); 243 } 244 245 /// Lookup the captured field decl for a variable. 246 const FieldDecl *lookup(const VarDecl *VD) const override { 247 if (OuterRegionInfo) 248 return OuterRegionInfo->lookup(VD); 249 // If there is no outer outlined region,no need to lookup in a list of 250 // captured variables, we can use the original one. 251 return nullptr; 252 } 253 254 FieldDecl *getThisFieldDecl() const override { 255 if (OuterRegionInfo) 256 return OuterRegionInfo->getThisFieldDecl(); 257 return nullptr; 258 } 259 260 /// Get a variable or parameter for storing global thread id 261 /// inside OpenMP construct. 262 const VarDecl *getThreadIDVariable() const override { 263 if (OuterRegionInfo) 264 return OuterRegionInfo->getThreadIDVariable(); 265 return nullptr; 266 } 267 268 /// Get an LValue for the current ThreadID variable. 269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override { 270 if (OuterRegionInfo) 271 return OuterRegionInfo->getThreadIDVariableLValue(CGF); 272 llvm_unreachable("No LValue for inlined OpenMP construct"); 273 } 274 275 /// Get the name of the capture helper. 276 StringRef getHelperName() const override { 277 if (auto *OuterRegionInfo = getOldCSI()) 278 return OuterRegionInfo->getHelperName(); 279 llvm_unreachable("No helper name for inlined OpenMP construct"); 280 } 281 282 void emitUntiedSwitch(CodeGenFunction &CGF) override { 283 if (OuterRegionInfo) 284 OuterRegionInfo->emitUntiedSwitch(CGF); 285 } 286 287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; } 288 289 static bool classof(const CGCapturedStmtInfo *Info) { 290 return CGOpenMPRegionInfo::classof(Info) && 291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion; 292 } 293 294 ~CGOpenMPInlinedRegionInfo() override = default; 295 296 private: 297 /// CodeGen info about outer OpenMP region. 298 CodeGenFunction::CGCapturedStmtInfo *OldCSI; 299 CGOpenMPRegionInfo *OuterRegionInfo; 300 }; 301 302 /// API for captured statement code generation in OpenMP target 303 /// constructs. For this captures, implicit parameters are used instead of the 304 /// captured fields. The name of the target region has to be unique in a given 305 /// application so it is provided by the client, because only the client has 306 /// the information to generate that. 307 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo { 308 public: 309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS, 310 const RegionCodeGenTy &CodeGen, StringRef HelperName) 311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target, 312 /*HasCancel=*/false), 313 HelperName(HelperName) {} 314 315 /// This is unused for target regions because each starts executing 316 /// with a single thread. 317 const VarDecl *getThreadIDVariable() const override { return nullptr; } 318 319 /// Get the name of the capture helper. 320 StringRef getHelperName() const override { return HelperName; } 321 322 static bool classof(const CGCapturedStmtInfo *Info) { 323 return CGOpenMPRegionInfo::classof(Info) && 324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion; 325 } 326 327 private: 328 StringRef HelperName; 329 }; 330 331 static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) { 332 llvm_unreachable("No codegen for expressions"); 333 } 334 /// API for generation of expressions captured in a innermost OpenMP 335 /// region. 336 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo { 337 public: 338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS) 339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen, 340 OMPD_unknown, 341 /*HasCancel=*/false), 342 PrivScope(CGF) { 343 // Make sure the globals captured in the provided statement are local by 344 // using the privatization logic. We assume the same variable is not 345 // captured more than once. 346 for (const auto &C : CS.captures()) { 347 if (!C.capturesVariable() && !C.capturesVariableByCopy()) 348 continue; 349 350 const VarDecl *VD = C.getCapturedVar(); 351 if (VD->isLocalVarDeclOrParm()) 352 continue; 353 354 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD), 355 /*RefersToEnclosingVariableOrCapture=*/false, 356 VD->getType().getNonReferenceType(), VK_LValue, 357 C.getLocation()); 358 PrivScope.addPrivate( 359 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); }); 360 } 361 (void)PrivScope.Privatize(); 362 } 363 364 /// Lookup the captured field decl for a variable. 365 const FieldDecl *lookup(const VarDecl *VD) const override { 366 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD)) 367 return FD; 368 return nullptr; 369 } 370 371 /// Emit the captured statement body. 372 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override { 373 llvm_unreachable("No body for expressions"); 374 } 375 376 /// Get a variable or parameter for storing global thread id 377 /// inside OpenMP construct. 378 const VarDecl *getThreadIDVariable() const override { 379 llvm_unreachable("No thread id for expressions"); 380 } 381 382 /// Get the name of the capture helper. 383 StringRef getHelperName() const override { 384 llvm_unreachable("No helper name for expressions"); 385 } 386 387 static bool classof(const CGCapturedStmtInfo *Info) { return false; } 388 389 private: 390 /// Private scope to capture global variables. 391 CodeGenFunction::OMPPrivateScope PrivScope; 392 }; 393 394 /// RAII for emitting code of OpenMP constructs. 395 class InlinedOpenMPRegionRAII { 396 CodeGenFunction &CGF; 397 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 398 FieldDecl *LambdaThisCaptureField = nullptr; 399 const CodeGen::CGBlockInfo *BlockInfo = nullptr; 400 401 public: 402 /// Constructs region for combined constructs. 403 /// \param CodeGen Code generation sequence for combined directives. Includes 404 /// a list of functions used for code generation of implicitly inlined 405 /// regions. 406 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen, 407 OpenMPDirectiveKind Kind, bool HasCancel) 408 : CGF(CGF) { 409 // Start emission for the construct. 410 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo( 411 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel); 412 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields); 413 LambdaThisCaptureField = CGF.LambdaThisCaptureField; 414 CGF.LambdaThisCaptureField = nullptr; 415 BlockInfo = CGF.BlockInfo; 416 CGF.BlockInfo = nullptr; 417 } 418 419 ~InlinedOpenMPRegionRAII() { 420 // Restore original CapturedStmtInfo only if we're done with code emission. 421 auto *OldCSI = 422 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI(); 423 delete CGF.CapturedStmtInfo; 424 CGF.CapturedStmtInfo = OldCSI; 425 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields); 426 CGF.LambdaThisCaptureField = LambdaThisCaptureField; 427 CGF.BlockInfo = BlockInfo; 428 } 429 }; 430 431 /// Values for bit flags used in the ident_t to describe the fields. 432 /// All enumeric elements are named and described in accordance with the code 433 /// from https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h 434 enum OpenMPLocationFlags : unsigned { 435 /// Use trampoline for internal microtask. 436 OMP_IDENT_IMD = 0x01, 437 /// Use c-style ident structure. 438 OMP_IDENT_KMPC = 0x02, 439 /// Atomic reduction option for kmpc_reduce. 440 OMP_ATOMIC_REDUCE = 0x10, 441 /// Explicit 'barrier' directive. 442 OMP_IDENT_BARRIER_EXPL = 0x20, 443 /// Implicit barrier in code. 444 OMP_IDENT_BARRIER_IMPL = 0x40, 445 /// Implicit barrier in 'for' directive. 446 OMP_IDENT_BARRIER_IMPL_FOR = 0x40, 447 /// Implicit barrier in 'sections' directive. 448 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0, 449 /// Implicit barrier in 'single' directive. 450 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140, 451 /// Call of __kmp_for_static_init for static loop. 452 OMP_IDENT_WORK_LOOP = 0x200, 453 /// Call of __kmp_for_static_init for sections. 454 OMP_IDENT_WORK_SECTIONS = 0x400, 455 /// Call of __kmp_for_static_init for distribute. 456 OMP_IDENT_WORK_DISTRIBUTE = 0x800, 457 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE) 458 }; 459 460 /// Describes ident structure that describes a source location. 461 /// All descriptions are taken from 462 /// https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h 463 /// Original structure: 464 /// typedef struct ident { 465 /// kmp_int32 reserved_1; /**< might be used in Fortran; 466 /// see above */ 467 /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags; 468 /// KMP_IDENT_KMPC identifies this union 469 /// member */ 470 /// kmp_int32 reserved_2; /**< not really used in Fortran any more; 471 /// see above */ 472 ///#if USE_ITT_BUILD 473 /// /* but currently used for storing 474 /// region-specific ITT */ 475 /// /* contextual information. */ 476 ///#endif /* USE_ITT_BUILD */ 477 /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for 478 /// C++ */ 479 /// char const *psource; /**< String describing the source location. 480 /// The string is composed of semi-colon separated 481 // fields which describe the source file, 482 /// the function and a pair of line numbers that 483 /// delimit the construct. 484 /// */ 485 /// } ident_t; 486 enum IdentFieldIndex { 487 /// might be used in Fortran 488 IdentField_Reserved_1, 489 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member. 490 IdentField_Flags, 491 /// Not really used in Fortran any more 492 IdentField_Reserved_2, 493 /// Source[4] in Fortran, do not use for C++ 494 IdentField_Reserved_3, 495 /// String describing the source location. The string is composed of 496 /// semi-colon separated fields which describe the source file, the function 497 /// and a pair of line numbers that delimit the construct. 498 IdentField_PSource 499 }; 500 501 /// Schedule types for 'omp for' loops (these enumerators are taken from 502 /// the enum sched_type in kmp.h). 503 enum OpenMPSchedType { 504 /// Lower bound for default (unordered) versions. 505 OMP_sch_lower = 32, 506 OMP_sch_static_chunked = 33, 507 OMP_sch_static = 34, 508 OMP_sch_dynamic_chunked = 35, 509 OMP_sch_guided_chunked = 36, 510 OMP_sch_runtime = 37, 511 OMP_sch_auto = 38, 512 /// static with chunk adjustment (e.g., simd) 513 OMP_sch_static_balanced_chunked = 45, 514 /// Lower bound for 'ordered' versions. 515 OMP_ord_lower = 64, 516 OMP_ord_static_chunked = 65, 517 OMP_ord_static = 66, 518 OMP_ord_dynamic_chunked = 67, 519 OMP_ord_guided_chunked = 68, 520 OMP_ord_runtime = 69, 521 OMP_ord_auto = 70, 522 OMP_sch_default = OMP_sch_static, 523 /// dist_schedule types 524 OMP_dist_sch_static_chunked = 91, 525 OMP_dist_sch_static = 92, 526 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers. 527 /// Set if the monotonic schedule modifier was present. 528 OMP_sch_modifier_monotonic = (1 << 29), 529 /// Set if the nonmonotonic schedule modifier was present. 530 OMP_sch_modifier_nonmonotonic = (1 << 30), 531 }; 532 533 enum OpenMPRTLFunction { 534 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, 535 /// kmpc_micro microtask, ...); 536 OMPRTL__kmpc_fork_call, 537 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc, 538 /// kmp_int32 global_tid, void *data, size_t size, void ***cache); 539 OMPRTL__kmpc_threadprivate_cached, 540 /// Call to void __kmpc_threadprivate_register( ident_t *, 541 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor); 542 OMPRTL__kmpc_threadprivate_register, 543 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc); 544 OMPRTL__kmpc_global_thread_num, 545 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid, 546 // kmp_critical_name *crit); 547 OMPRTL__kmpc_critical, 548 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 549 // global_tid, kmp_critical_name *crit, uintptr_t hint); 550 OMPRTL__kmpc_critical_with_hint, 551 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid, 552 // kmp_critical_name *crit); 553 OMPRTL__kmpc_end_critical, 554 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32 555 // global_tid); 556 OMPRTL__kmpc_cancel_barrier, 557 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid); 558 OMPRTL__kmpc_barrier, 559 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid); 560 OMPRTL__kmpc_for_static_fini, 561 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 562 // global_tid); 563 OMPRTL__kmpc_serialized_parallel, 564 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 565 // global_tid); 566 OMPRTL__kmpc_end_serialized_parallel, 567 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, 568 // kmp_int32 num_threads); 569 OMPRTL__kmpc_push_num_threads, 570 // Call to void __kmpc_flush(ident_t *loc); 571 OMPRTL__kmpc_flush, 572 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid); 573 OMPRTL__kmpc_master, 574 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid); 575 OMPRTL__kmpc_end_master, 576 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid, 577 // int end_part); 578 OMPRTL__kmpc_omp_taskyield, 579 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid); 580 OMPRTL__kmpc_single, 581 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid); 582 OMPRTL__kmpc_end_single, 583 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid, 584 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 585 // kmp_routine_entry_t *task_entry); 586 OMPRTL__kmpc_omp_task_alloc, 587 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t * 588 // new_task); 589 OMPRTL__kmpc_omp_task, 590 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid, 591 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *), 592 // kmp_int32 didit); 593 OMPRTL__kmpc_copyprivate, 594 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid, 595 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void 596 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck); 597 OMPRTL__kmpc_reduce, 598 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32 599 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, 600 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name 601 // *lck); 602 OMPRTL__kmpc_reduce_nowait, 603 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid, 604 // kmp_critical_name *lck); 605 OMPRTL__kmpc_end_reduce, 606 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid, 607 // kmp_critical_name *lck); 608 OMPRTL__kmpc_end_reduce_nowait, 609 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid, 610 // kmp_task_t * new_task); 611 OMPRTL__kmpc_omp_task_begin_if0, 612 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid, 613 // kmp_task_t * new_task); 614 OMPRTL__kmpc_omp_task_complete_if0, 615 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid); 616 OMPRTL__kmpc_ordered, 617 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid); 618 OMPRTL__kmpc_end_ordered, 619 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 620 // global_tid); 621 OMPRTL__kmpc_omp_taskwait, 622 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid); 623 OMPRTL__kmpc_taskgroup, 624 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid); 625 OMPRTL__kmpc_end_taskgroup, 626 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, 627 // int proc_bind); 628 OMPRTL__kmpc_push_proc_bind, 629 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32 630 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t 631 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list); 632 OMPRTL__kmpc_omp_task_with_deps, 633 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32 634 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 635 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); 636 OMPRTL__kmpc_omp_wait_deps, 637 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32 638 // global_tid, kmp_int32 cncl_kind); 639 OMPRTL__kmpc_cancellationpoint, 640 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid, 641 // kmp_int32 cncl_kind); 642 OMPRTL__kmpc_cancel, 643 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid, 644 // kmp_int32 num_teams, kmp_int32 thread_limit); 645 OMPRTL__kmpc_push_num_teams, 646 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro 647 // microtask, ...); 648 OMPRTL__kmpc_fork_teams, 649 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int 650 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int 651 // sched, kmp_uint64 grainsize, void *task_dup); 652 OMPRTL__kmpc_taskloop, 653 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32 654 // num_dims, struct kmp_dim *dims); 655 OMPRTL__kmpc_doacross_init, 656 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid); 657 OMPRTL__kmpc_doacross_fini, 658 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64 659 // *vec); 660 OMPRTL__kmpc_doacross_post, 661 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64 662 // *vec); 663 OMPRTL__kmpc_doacross_wait, 664 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void 665 // *data); 666 OMPRTL__kmpc_task_reduction_init, 667 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void 668 // *d); 669 OMPRTL__kmpc_task_reduction_get_th_data, 670 671 // 672 // Offloading related calls 673 // 674 // Call to void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64 675 // size); 676 OMPRTL__kmpc_push_target_tripcount, 677 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t 678 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 679 // *arg_types); 680 OMPRTL__tgt_target, 681 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr, 682 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 683 // *arg_types); 684 OMPRTL__tgt_target_nowait, 685 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr, 686 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 687 // *arg_types, int32_t num_teams, int32_t thread_limit); 688 OMPRTL__tgt_target_teams, 689 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void 690 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t 691 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit); 692 OMPRTL__tgt_target_teams_nowait, 693 // Call to void __tgt_register_lib(__tgt_bin_desc *desc); 694 OMPRTL__tgt_register_lib, 695 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc); 696 OMPRTL__tgt_unregister_lib, 697 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num, 698 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 699 OMPRTL__tgt_target_data_begin, 700 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t 701 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 702 // *arg_types); 703 OMPRTL__tgt_target_data_begin_nowait, 704 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num, 705 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 706 OMPRTL__tgt_target_data_end, 707 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t 708 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 709 // *arg_types); 710 OMPRTL__tgt_target_data_end_nowait, 711 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num, 712 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 713 OMPRTL__tgt_target_data_update, 714 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t 715 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 716 // *arg_types); 717 OMPRTL__tgt_target_data_update_nowait, 718 }; 719 720 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP 721 /// region. 722 class CleanupTy final : public EHScopeStack::Cleanup { 723 PrePostActionTy *Action; 724 725 public: 726 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {} 727 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { 728 if (!CGF.HaveInsertPoint()) 729 return; 730 Action->Exit(CGF); 731 } 732 }; 733 734 } // anonymous namespace 735 736 void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const { 737 CodeGenFunction::RunCleanupsScope Scope(CGF); 738 if (PrePostAction) { 739 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction); 740 Callback(CodeGen, CGF, *PrePostAction); 741 } else { 742 PrePostActionTy Action; 743 Callback(CodeGen, CGF, Action); 744 } 745 } 746 747 /// Check if the combiner is a call to UDR combiner and if it is so return the 748 /// UDR decl used for reduction. 749 static const OMPDeclareReductionDecl * 750 getReductionInit(const Expr *ReductionOp) { 751 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) 752 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) 753 if (const auto *DRE = 754 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) 755 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) 756 return DRD; 757 return nullptr; 758 } 759 760 static void emitInitWithReductionInitializer(CodeGenFunction &CGF, 761 const OMPDeclareReductionDecl *DRD, 762 const Expr *InitOp, 763 Address Private, Address Original, 764 QualType Ty) { 765 if (DRD->getInitializer()) { 766 std::pair<llvm::Function *, llvm::Function *> Reduction = 767 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); 768 const auto *CE = cast<CallExpr>(InitOp); 769 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee()); 770 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 771 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 772 const auto *LHSDRE = 773 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr()); 774 const auto *RHSDRE = 775 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr()); 776 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 777 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()), 778 [=]() { return Private; }); 779 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()), 780 [=]() { return Original; }); 781 (void)PrivateScope.Privatize(); 782 RValue Func = RValue::get(Reduction.second); 783 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); 784 CGF.EmitIgnoredExpr(InitOp); 785 } else { 786 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty); 787 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"}); 788 auto *GV = new llvm::GlobalVariable( 789 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true, 790 llvm::GlobalValue::PrivateLinkage, Init, Name); 791 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty); 792 RValue InitRVal; 793 switch (CGF.getEvaluationKind(Ty)) { 794 case TEK_Scalar: 795 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation()); 796 break; 797 case TEK_Complex: 798 InitRVal = 799 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation())); 800 break; 801 case TEK_Aggregate: 802 InitRVal = RValue::getAggregate(LV.getAddress()); 803 break; 804 } 805 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue); 806 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal); 807 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(), 808 /*IsInitializer=*/false); 809 } 810 } 811 812 /// Emit initialization of arrays of complex types. 813 /// \param DestAddr Address of the array. 814 /// \param Type Type of array. 815 /// \param Init Initial expression of array. 816 /// \param SrcAddr Address of the original array. 817 static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr, 818 QualType Type, bool EmitDeclareReductionInit, 819 const Expr *Init, 820 const OMPDeclareReductionDecl *DRD, 821 Address SrcAddr = Address::invalid()) { 822 // Perform element-by-element initialization. 823 QualType ElementTy; 824 825 // Drill down to the base element type on both arrays. 826 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe(); 827 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr); 828 DestAddr = 829 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType()); 830 if (DRD) 831 SrcAddr = 832 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); 833 834 llvm::Value *SrcBegin = nullptr; 835 if (DRD) 836 SrcBegin = SrcAddr.getPointer(); 837 llvm::Value *DestBegin = DestAddr.getPointer(); 838 // Cast from pointer to array type to pointer to single element. 839 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements); 840 // The basic structure here is a while-do loop. 841 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body"); 842 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done"); 843 llvm::Value *IsEmpty = 844 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty"); 845 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 846 847 // Enter the loop body, making that address the current address. 848 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); 849 CGF.EmitBlock(BodyBB); 850 851 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); 852 853 llvm::PHINode *SrcElementPHI = nullptr; 854 Address SrcElementCurrent = Address::invalid(); 855 if (DRD) { 856 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2, 857 "omp.arraycpy.srcElementPast"); 858 SrcElementPHI->addIncoming(SrcBegin, EntryBB); 859 SrcElementCurrent = 860 Address(SrcElementPHI, 861 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 862 } 863 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI( 864 DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); 865 DestElementPHI->addIncoming(DestBegin, EntryBB); 866 Address DestElementCurrent = 867 Address(DestElementPHI, 868 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 869 870 // Emit copy. 871 { 872 CodeGenFunction::RunCleanupsScope InitScope(CGF); 873 if (EmitDeclareReductionInit) { 874 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent, 875 SrcElementCurrent, ElementTy); 876 } else 877 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(), 878 /*IsInitializer=*/false); 879 } 880 881 if (DRD) { 882 // Shift the address forward by one element. 883 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32( 884 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 885 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock()); 886 } 887 888 // Shift the address forward by one element. 889 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32( 890 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 891 // Check whether we've reached the end. 892 llvm::Value *Done = 893 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 894 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); 895 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock()); 896 897 // Done. 898 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 899 } 900 901 LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) { 902 return CGF.EmitOMPSharedLValue(E); 903 } 904 905 LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF, 906 const Expr *E) { 907 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E)) 908 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false); 909 return LValue(); 910 } 911 912 void ReductionCodeGen::emitAggregateInitialization( 913 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal, 914 const OMPDeclareReductionDecl *DRD) { 915 // Emit VarDecl with copy init for arrays. 916 // Get the address of the original variable captured in current 917 // captured region. 918 const auto *PrivateVD = 919 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 920 bool EmitDeclareReductionInit = 921 DRD && (DRD->getInitializer() || !PrivateVD->hasInit()); 922 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(), 923 EmitDeclareReductionInit, 924 EmitDeclareReductionInit ? ClausesData[N].ReductionOp 925 : PrivateVD->getInit(), 926 DRD, SharedLVal.getAddress()); 927 } 928 929 ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds, 930 ArrayRef<const Expr *> Privates, 931 ArrayRef<const Expr *> ReductionOps) { 932 ClausesData.reserve(Shareds.size()); 933 SharedAddresses.reserve(Shareds.size()); 934 Sizes.reserve(Shareds.size()); 935 BaseDecls.reserve(Shareds.size()); 936 auto IPriv = Privates.begin(); 937 auto IRed = ReductionOps.begin(); 938 for (const Expr *Ref : Shareds) { 939 ClausesData.emplace_back(Ref, *IPriv, *IRed); 940 std::advance(IPriv, 1); 941 std::advance(IRed, 1); 942 } 943 } 944 945 void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) { 946 assert(SharedAddresses.size() == N && 947 "Number of generated lvalues must be exactly N."); 948 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref); 949 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref); 950 SharedAddresses.emplace_back(First, Second); 951 } 952 953 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) { 954 const auto *PrivateVD = 955 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 956 QualType PrivateType = PrivateVD->getType(); 957 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref); 958 if (!PrivateType->isVariablyModifiedType()) { 959 Sizes.emplace_back( 960 CGF.getTypeSize( 961 SharedAddresses[N].first.getType().getNonReferenceType()), 962 nullptr); 963 return; 964 } 965 llvm::Value *Size; 966 llvm::Value *SizeInChars; 967 auto *ElemType = 968 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType()) 969 ->getElementType(); 970 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType); 971 if (AsArraySection) { 972 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(), 973 SharedAddresses[N].first.getPointer()); 974 Size = CGF.Builder.CreateNUWAdd( 975 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1)); 976 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf); 977 } else { 978 SizeInChars = CGF.getTypeSize( 979 SharedAddresses[N].first.getType().getNonReferenceType()); 980 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf); 981 } 982 Sizes.emplace_back(SizeInChars, Size); 983 CodeGenFunction::OpaqueValueMapping OpaqueMap( 984 CGF, 985 cast<OpaqueValueExpr>( 986 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()), 987 RValue::get(Size)); 988 CGF.EmitVariablyModifiedType(PrivateType); 989 } 990 991 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N, 992 llvm::Value *Size) { 993 const auto *PrivateVD = 994 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 995 QualType PrivateType = PrivateVD->getType(); 996 if (!PrivateType->isVariablyModifiedType()) { 997 assert(!Size && !Sizes[N].second && 998 "Size should be nullptr for non-variably modified reduction " 999 "items."); 1000 return; 1001 } 1002 CodeGenFunction::OpaqueValueMapping OpaqueMap( 1003 CGF, 1004 cast<OpaqueValueExpr>( 1005 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()), 1006 RValue::get(Size)); 1007 CGF.EmitVariablyModifiedType(PrivateType); 1008 } 1009 1010 void ReductionCodeGen::emitInitialization( 1011 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal, 1012 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) { 1013 assert(SharedAddresses.size() > N && "No variable was generated"); 1014 const auto *PrivateVD = 1015 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 1016 const OMPDeclareReductionDecl *DRD = 1017 getReductionInit(ClausesData[N].ReductionOp); 1018 QualType PrivateType = PrivateVD->getType(); 1019 PrivateAddr = CGF.Builder.CreateElementBitCast( 1020 PrivateAddr, CGF.ConvertTypeForMem(PrivateType)); 1021 QualType SharedType = SharedAddresses[N].first.getType(); 1022 SharedLVal = CGF.MakeAddrLValue( 1023 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(), 1024 CGF.ConvertTypeForMem(SharedType)), 1025 SharedType, SharedAddresses[N].first.getBaseInfo(), 1026 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType)); 1027 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) { 1028 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD); 1029 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) { 1030 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp, 1031 PrivateAddr, SharedLVal.getAddress(), 1032 SharedLVal.getType()); 1033 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() && 1034 !CGF.isTrivialInitializer(PrivateVD->getInit())) { 1035 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr, 1036 PrivateVD->getType().getQualifiers(), 1037 /*IsInitializer=*/false); 1038 } 1039 } 1040 1041 bool ReductionCodeGen::needCleanups(unsigned N) { 1042 const auto *PrivateVD = 1043 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 1044 QualType PrivateType = PrivateVD->getType(); 1045 QualType::DestructionKind DTorKind = PrivateType.isDestructedType(); 1046 return DTorKind != QualType::DK_none; 1047 } 1048 1049 void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N, 1050 Address PrivateAddr) { 1051 const auto *PrivateVD = 1052 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 1053 QualType PrivateType = PrivateVD->getType(); 1054 QualType::DestructionKind DTorKind = PrivateType.isDestructedType(); 1055 if (needCleanups(N)) { 1056 PrivateAddr = CGF.Builder.CreateElementBitCast( 1057 PrivateAddr, CGF.ConvertTypeForMem(PrivateType)); 1058 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType); 1059 } 1060 } 1061 1062 static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, 1063 LValue BaseLV) { 1064 BaseTy = BaseTy.getNonReferenceType(); 1065 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && 1066 !CGF.getContext().hasSameType(BaseTy, ElTy)) { 1067 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) { 1068 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy); 1069 } else { 1070 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy); 1071 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal); 1072 } 1073 BaseTy = BaseTy->getPointeeType(); 1074 } 1075 return CGF.MakeAddrLValue( 1076 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(), 1077 CGF.ConvertTypeForMem(ElTy)), 1078 BaseLV.getType(), BaseLV.getBaseInfo(), 1079 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType())); 1080 } 1081 1082 static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, 1083 llvm::Type *BaseLVType, CharUnits BaseLVAlignment, 1084 llvm::Value *Addr) { 1085 Address Tmp = Address::invalid(); 1086 Address TopTmp = Address::invalid(); 1087 Address MostTopTmp = Address::invalid(); 1088 BaseTy = BaseTy.getNonReferenceType(); 1089 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && 1090 !CGF.getContext().hasSameType(BaseTy, ElTy)) { 1091 Tmp = CGF.CreateMemTemp(BaseTy); 1092 if (TopTmp.isValid()) 1093 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp); 1094 else 1095 MostTopTmp = Tmp; 1096 TopTmp = Tmp; 1097 BaseTy = BaseTy->getPointeeType(); 1098 } 1099 llvm::Type *Ty = BaseLVType; 1100 if (Tmp.isValid()) 1101 Ty = Tmp.getElementType(); 1102 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty); 1103 if (Tmp.isValid()) { 1104 CGF.Builder.CreateStore(Addr, Tmp); 1105 return MostTopTmp; 1106 } 1107 return Address(Addr, BaseLVAlignment); 1108 } 1109 1110 static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) { 1111 const VarDecl *OrigVD = nullptr; 1112 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) { 1113 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 1114 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 1115 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 1116 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 1117 Base = TempASE->getBase()->IgnoreParenImpCasts(); 1118 DE = cast<DeclRefExpr>(Base); 1119 OrigVD = cast<VarDecl>(DE->getDecl()); 1120 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) { 1121 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 1122 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 1123 Base = TempASE->getBase()->IgnoreParenImpCasts(); 1124 DE = cast<DeclRefExpr>(Base); 1125 OrigVD = cast<VarDecl>(DE->getDecl()); 1126 } 1127 return OrigVD; 1128 } 1129 1130 Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, 1131 Address PrivateAddr) { 1132 const DeclRefExpr *DE; 1133 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) { 1134 BaseDecls.emplace_back(OrigVD); 1135 LValue OriginalBaseLValue = CGF.EmitLValue(DE); 1136 LValue BaseLValue = 1137 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(), 1138 OriginalBaseLValue); 1139 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff( 1140 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer()); 1141 llvm::Value *PrivatePointer = 1142 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 1143 PrivateAddr.getPointer(), 1144 SharedAddresses[N].first.getAddress().getType()); 1145 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment); 1146 return castToBase(CGF, OrigVD->getType(), 1147 SharedAddresses[N].first.getType(), 1148 OriginalBaseLValue.getAddress().getType(), 1149 OriginalBaseLValue.getAlignment(), Ptr); 1150 } 1151 BaseDecls.emplace_back( 1152 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl())); 1153 return PrivateAddr; 1154 } 1155 1156 bool ReductionCodeGen::usesReductionInitializer(unsigned N) const { 1157 const OMPDeclareReductionDecl *DRD = 1158 getReductionInit(ClausesData[N].ReductionOp); 1159 return DRD && DRD->getInitializer(); 1160 } 1161 1162 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) { 1163 return CGF.EmitLoadOfPointerLValue( 1164 CGF.GetAddrOfLocalVar(getThreadIDVariable()), 1165 getThreadIDVariable()->getType()->castAs<PointerType>()); 1166 } 1167 1168 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) { 1169 if (!CGF.HaveInsertPoint()) 1170 return; 1171 // 1.2.2 OpenMP Language Terminology 1172 // Structured block - An executable statement with a single entry at the 1173 // top and a single exit at the bottom. 1174 // The point of exit cannot be a branch out of the structured block. 1175 // longjmp() and throw() must not violate the entry/exit criteria. 1176 CGF.EHStack.pushTerminate(); 1177 CodeGen(CGF); 1178 CGF.EHStack.popTerminate(); 1179 } 1180 1181 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue( 1182 CodeGenFunction &CGF) { 1183 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()), 1184 getThreadIDVariable()->getType(), 1185 AlignmentSource::Decl); 1186 } 1187 1188 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC, 1189 QualType FieldTy) { 1190 auto *Field = FieldDecl::Create( 1191 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy, 1192 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()), 1193 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit); 1194 Field->setAccess(AS_public); 1195 DC->addDecl(Field); 1196 return Field; 1197 } 1198 1199 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator, 1200 StringRef Separator) 1201 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator), 1202 OffloadEntriesInfoManager(CGM) { 1203 ASTContext &C = CGM.getContext(); 1204 RecordDecl *RD = C.buildImplicitRecord("ident_t"); 1205 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1206 RD->startDefinition(); 1207 // reserved_1 1208 addFieldToRecordDecl(C, RD, KmpInt32Ty); 1209 // flags 1210 addFieldToRecordDecl(C, RD, KmpInt32Ty); 1211 // reserved_2 1212 addFieldToRecordDecl(C, RD, KmpInt32Ty); 1213 // reserved_3 1214 addFieldToRecordDecl(C, RD, KmpInt32Ty); 1215 // psource 1216 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 1217 RD->completeDefinition(); 1218 IdentQTy = C.getRecordType(RD); 1219 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD); 1220 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8); 1221 1222 loadOffloadInfoMetadata(); 1223 } 1224 1225 void CGOpenMPRuntime::clear() { 1226 InternalVars.clear(); 1227 // Clean non-target variable declarations possibly used only in debug info. 1228 for (const auto &Data : EmittedNonTargetVariables) { 1229 if (!Data.getValue().pointsToAliveValue()) 1230 continue; 1231 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue()); 1232 if (!GV) 1233 continue; 1234 if (!GV->isDeclaration() || GV->getNumUses() > 0) 1235 continue; 1236 GV->eraseFromParent(); 1237 } 1238 } 1239 1240 std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const { 1241 SmallString<128> Buffer; 1242 llvm::raw_svector_ostream OS(Buffer); 1243 StringRef Sep = FirstSeparator; 1244 for (StringRef Part : Parts) { 1245 OS << Sep << Part; 1246 Sep = Separator; 1247 } 1248 return OS.str(); 1249 } 1250 1251 static llvm::Function * 1252 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty, 1253 const Expr *CombinerInitializer, const VarDecl *In, 1254 const VarDecl *Out, bool IsCombiner) { 1255 // void .omp_combiner.(Ty *in, Ty *out); 1256 ASTContext &C = CGM.getContext(); 1257 QualType PtrTy = C.getPointerType(Ty).withRestrict(); 1258 FunctionArgList Args; 1259 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(), 1260 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other); 1261 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(), 1262 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other); 1263 Args.push_back(&OmpOutParm); 1264 Args.push_back(&OmpInParm); 1265 const CGFunctionInfo &FnInfo = 1266 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 1267 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 1268 std::string Name = CGM.getOpenMPRuntime().getName( 1269 {IsCombiner ? "omp_combiner" : "omp_initializer", ""}); 1270 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, 1271 Name, &CGM.getModule()); 1272 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); 1273 Fn->removeFnAttr(llvm::Attribute::NoInline); 1274 Fn->removeFnAttr(llvm::Attribute::OptimizeNone); 1275 Fn->addFnAttr(llvm::Attribute::AlwaysInline); 1276 CodeGenFunction CGF(CGM); 1277 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions. 1278 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions. 1279 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(), 1280 Out->getLocation()); 1281 CodeGenFunction::OMPPrivateScope Scope(CGF); 1282 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm); 1283 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() { 1284 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>()) 1285 .getAddress(); 1286 }); 1287 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm); 1288 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() { 1289 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>()) 1290 .getAddress(); 1291 }); 1292 (void)Scope.Privatize(); 1293 if (!IsCombiner && Out->hasInit() && 1294 !CGF.isTrivialInitializer(Out->getInit())) { 1295 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out), 1296 Out->getType().getQualifiers(), 1297 /*IsInitializer=*/true); 1298 } 1299 if (CombinerInitializer) 1300 CGF.EmitIgnoredExpr(CombinerInitializer); 1301 Scope.ForceCleanup(); 1302 CGF.FinishFunction(); 1303 return Fn; 1304 } 1305 1306 void CGOpenMPRuntime::emitUserDefinedReduction( 1307 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) { 1308 if (UDRMap.count(D) > 0) 1309 return; 1310 llvm::Function *Combiner = emitCombinerOrInitializer( 1311 CGM, D->getType(), D->getCombiner(), 1312 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()), 1313 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()), 1314 /*IsCombiner=*/true); 1315 llvm::Function *Initializer = nullptr; 1316 if (const Expr *Init = D->getInitializer()) { 1317 Initializer = emitCombinerOrInitializer( 1318 CGM, D->getType(), 1319 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init 1320 : nullptr, 1321 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()), 1322 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()), 1323 /*IsCombiner=*/false); 1324 } 1325 UDRMap.try_emplace(D, Combiner, Initializer); 1326 if (CGF) { 1327 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn); 1328 Decls.second.push_back(D); 1329 } 1330 } 1331 1332 std::pair<llvm::Function *, llvm::Function *> 1333 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) { 1334 auto I = UDRMap.find(D); 1335 if (I != UDRMap.end()) 1336 return I->second; 1337 emitUserDefinedReduction(/*CGF=*/nullptr, D); 1338 return UDRMap.lookup(D); 1339 } 1340 1341 static llvm::Function *emitParallelOrTeamsOutlinedFunction( 1342 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS, 1343 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, 1344 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) { 1345 assert(ThreadIDVar->getType()->isPointerType() && 1346 "thread id variable must be of type kmp_int32 *"); 1347 CodeGenFunction CGF(CGM, true); 1348 bool HasCancel = false; 1349 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D)) 1350 HasCancel = OPD->hasCancel(); 1351 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D)) 1352 HasCancel = OPSD->hasCancel(); 1353 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D)) 1354 HasCancel = OPFD->hasCancel(); 1355 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D)) 1356 HasCancel = OPFD->hasCancel(); 1357 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D)) 1358 HasCancel = OPFD->hasCancel(); 1359 else if (const auto *OPFD = 1360 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D)) 1361 HasCancel = OPFD->hasCancel(); 1362 else if (const auto *OPFD = 1363 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D)) 1364 HasCancel = OPFD->hasCancel(); 1365 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind, 1366 HasCancel, OutlinedHelperName); 1367 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 1368 return CGF.GenerateOpenMPCapturedStmtFunction(*CS); 1369 } 1370 1371 llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction( 1372 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1373 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { 1374 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel); 1375 return emitParallelOrTeamsOutlinedFunction( 1376 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen); 1377 } 1378 1379 llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction( 1380 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1381 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { 1382 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams); 1383 return emitParallelOrTeamsOutlinedFunction( 1384 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen); 1385 } 1386 1387 llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction( 1388 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1389 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 1390 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1391 bool Tied, unsigned &NumberOfParts) { 1392 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF, 1393 PrePostActionTy &) { 1394 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc()); 1395 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc()); 1396 llvm::Value *TaskArgs[] = { 1397 UpLoc, ThreadID, 1398 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar), 1399 TaskTVar->getType()->castAs<PointerType>()) 1400 .getPointer()}; 1401 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs); 1402 }; 1403 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar, 1404 UntiedCodeGen); 1405 CodeGen.setAction(Action); 1406 assert(!ThreadIDVar->getType()->isPointerType() && 1407 "thread id variable must be of type kmp_int32 for tasks"); 1408 const OpenMPDirectiveKind Region = 1409 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop 1410 : OMPD_task; 1411 const CapturedStmt *CS = D.getCapturedStmt(Region); 1412 const auto *TD = dyn_cast<OMPTaskDirective>(&D); 1413 CodeGenFunction CGF(CGM, true); 1414 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, 1415 InnermostKind, 1416 TD ? TD->hasCancel() : false, Action); 1417 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 1418 llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS); 1419 if (!Tied) 1420 NumberOfParts = Action.getNumberOfParts(); 1421 return Res; 1422 } 1423 1424 static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM, 1425 const RecordDecl *RD, const CGRecordLayout &RL, 1426 ArrayRef<llvm::Constant *> Data) { 1427 llvm::StructType *StructTy = RL.getLLVMType(); 1428 unsigned PrevIdx = 0; 1429 ConstantInitBuilder CIBuilder(CGM); 1430 auto DI = Data.begin(); 1431 for (const FieldDecl *FD : RD->fields()) { 1432 unsigned Idx = RL.getLLVMFieldNo(FD); 1433 // Fill the alignment. 1434 for (unsigned I = PrevIdx; I < Idx; ++I) 1435 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I))); 1436 PrevIdx = Idx + 1; 1437 Fields.add(*DI); 1438 ++DI; 1439 } 1440 } 1441 1442 template <class... As> 1443 static llvm::GlobalVariable * 1444 createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant, 1445 ArrayRef<llvm::Constant *> Data, const Twine &Name, 1446 As &&... Args) { 1447 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl()); 1448 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD); 1449 ConstantInitBuilder CIBuilder(CGM); 1450 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType()); 1451 buildStructValue(Fields, CGM, RD, RL, Data); 1452 return Fields.finishAndCreateGlobal( 1453 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant, 1454 std::forward<As>(Args)...); 1455 } 1456 1457 template <typename T> 1458 static void 1459 createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty, 1460 ArrayRef<llvm::Constant *> Data, 1461 T &Parent) { 1462 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl()); 1463 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD); 1464 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType()); 1465 buildStructValue(Fields, CGM, RD, RL, Data); 1466 Fields.finishAndAddTo(Parent); 1467 } 1468 1469 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) { 1470 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy); 1471 unsigned Reserved2Flags = getDefaultLocationReserved2Flags(); 1472 FlagsTy FlagsKey(Flags, Reserved2Flags); 1473 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(FlagsKey); 1474 if (!Entry) { 1475 if (!DefaultOpenMPPSource) { 1476 // Initialize default location for psource field of ident_t structure of 1477 // all ident_t objects. Format is ";file;function;line;column;;". 1478 // Taken from 1479 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp_str.cpp 1480 DefaultOpenMPPSource = 1481 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer(); 1482 DefaultOpenMPPSource = 1483 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy); 1484 } 1485 1486 llvm::Constant *Data[] = { 1487 llvm::ConstantInt::getNullValue(CGM.Int32Ty), 1488 llvm::ConstantInt::get(CGM.Int32Ty, Flags), 1489 llvm::ConstantInt::get(CGM.Int32Ty, Reserved2Flags), 1490 llvm::ConstantInt::getNullValue(CGM.Int32Ty), DefaultOpenMPPSource}; 1491 llvm::GlobalValue *DefaultOpenMPLocation = 1492 createGlobalStruct(CGM, IdentQTy, isDefaultLocationConstant(), Data, "", 1493 llvm::GlobalValue::PrivateLinkage); 1494 DefaultOpenMPLocation->setUnnamedAddr( 1495 llvm::GlobalValue::UnnamedAddr::Global); 1496 1497 OpenMPDefaultLocMap[FlagsKey] = Entry = DefaultOpenMPLocation; 1498 } 1499 return Address(Entry, Align); 1500 } 1501 1502 void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF, 1503 bool AtCurrentPoint) { 1504 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); 1505 assert(!Elem.second.ServiceInsertPt && "Insert point is set already."); 1506 1507 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty); 1508 if (AtCurrentPoint) { 1509 Elem.second.ServiceInsertPt = new llvm::BitCastInst( 1510 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock()); 1511 } else { 1512 Elem.second.ServiceInsertPt = 1513 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt"); 1514 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt); 1515 } 1516 } 1517 1518 void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) { 1519 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); 1520 if (Elem.second.ServiceInsertPt) { 1521 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt; 1522 Elem.second.ServiceInsertPt = nullptr; 1523 Ptr->eraseFromParent(); 1524 } 1525 } 1526 1527 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF, 1528 SourceLocation Loc, 1529 unsigned Flags) { 1530 Flags |= OMP_IDENT_KMPC; 1531 // If no debug info is generated - return global default location. 1532 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo || 1533 Loc.isInvalid()) 1534 return getOrCreateDefaultLocation(Flags).getPointer(); 1535 1536 assert(CGF.CurFn && "No function in current CodeGenFunction."); 1537 1538 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy); 1539 Address LocValue = Address::invalid(); 1540 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn); 1541 if (I != OpenMPLocThreadIDMap.end()) 1542 LocValue = Address(I->second.DebugLoc, Align); 1543 1544 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if 1545 // GetOpenMPThreadID was called before this routine. 1546 if (!LocValue.isValid()) { 1547 // Generate "ident_t .kmpc_loc.addr;" 1548 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr"); 1549 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); 1550 Elem.second.DebugLoc = AI.getPointer(); 1551 LocValue = AI; 1552 1553 if (!Elem.second.ServiceInsertPt) 1554 setLocThreadIdInsertPt(CGF); 1555 CGBuilderTy::InsertPointGuard IPG(CGF.Builder); 1556 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt); 1557 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags), 1558 CGF.getTypeSize(IdentQTy)); 1559 } 1560 1561 // char **psource = &.kmpc_loc_<flags>.addr.psource; 1562 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy); 1563 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin(); 1564 LValue PSource = 1565 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource)); 1566 1567 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding()); 1568 if (OMPDebugLoc == nullptr) { 1569 SmallString<128> Buffer2; 1570 llvm::raw_svector_ostream OS2(Buffer2); 1571 // Build debug location 1572 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc); 1573 OS2 << ";" << PLoc.getFilename() << ";"; 1574 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) 1575 OS2 << FD->getQualifiedNameAsString(); 1576 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;"; 1577 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str()); 1578 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc; 1579 } 1580 // *psource = ";<File>;<Function>;<Line>;<Column>;;"; 1581 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource); 1582 1583 // Our callers always pass this to a runtime function, so for 1584 // convenience, go ahead and return a naked pointer. 1585 return LocValue.getPointer(); 1586 } 1587 1588 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF, 1589 SourceLocation Loc) { 1590 assert(CGF.CurFn && "No function in current CodeGenFunction."); 1591 1592 llvm::Value *ThreadID = nullptr; 1593 // Check whether we've already cached a load of the thread id in this 1594 // function. 1595 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn); 1596 if (I != OpenMPLocThreadIDMap.end()) { 1597 ThreadID = I->second.ThreadID; 1598 if (ThreadID != nullptr) 1599 return ThreadID; 1600 } 1601 // If exceptions are enabled, do not use parameter to avoid possible crash. 1602 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions || 1603 !CGF.getLangOpts().CXXExceptions || 1604 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) { 1605 if (auto *OMPRegionInfo = 1606 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { 1607 if (OMPRegionInfo->getThreadIDVariable()) { 1608 // Check if this an outlined function with thread id passed as argument. 1609 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF); 1610 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc); 1611 // If value loaded in entry block, cache it and use it everywhere in 1612 // function. 1613 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) { 1614 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); 1615 Elem.second.ThreadID = ThreadID; 1616 } 1617 return ThreadID; 1618 } 1619 } 1620 } 1621 1622 // This is not an outlined function region - need to call __kmpc_int32 1623 // kmpc_global_thread_num(ident_t *loc). 1624 // Generate thread id value and cache this value for use across the 1625 // function. 1626 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); 1627 if (!Elem.second.ServiceInsertPt) 1628 setLocThreadIdInsertPt(CGF); 1629 CGBuilderTy::InsertPointGuard IPG(CGF.Builder); 1630 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt); 1631 llvm::CallInst *Call = CGF.Builder.CreateCall( 1632 createRuntimeFunction(OMPRTL__kmpc_global_thread_num), 1633 emitUpdateLocation(CGF, Loc)); 1634 Call->setCallingConv(CGF.getRuntimeCC()); 1635 Elem.second.ThreadID = Call; 1636 return Call; 1637 } 1638 1639 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) { 1640 assert(CGF.CurFn && "No function in current CodeGenFunction."); 1641 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) { 1642 clearLocThreadIdInsertPt(CGF); 1643 OpenMPLocThreadIDMap.erase(CGF.CurFn); 1644 } 1645 if (FunctionUDRMap.count(CGF.CurFn) > 0) { 1646 for(auto *D : FunctionUDRMap[CGF.CurFn]) 1647 UDRMap.erase(D); 1648 FunctionUDRMap.erase(CGF.CurFn); 1649 } 1650 } 1651 1652 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() { 1653 return IdentTy->getPointerTo(); 1654 } 1655 1656 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() { 1657 if (!Kmpc_MicroTy) { 1658 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...) 1659 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty), 1660 llvm::PointerType::getUnqual(CGM.Int32Ty)}; 1661 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true); 1662 } 1663 return llvm::PointerType::getUnqual(Kmpc_MicroTy); 1664 } 1665 1666 llvm::FunctionCallee CGOpenMPRuntime::createRuntimeFunction(unsigned Function) { 1667 llvm::FunctionCallee RTLFn = nullptr; 1668 switch (static_cast<OpenMPRTLFunction>(Function)) { 1669 case OMPRTL__kmpc_fork_call: { 1670 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro 1671 // microtask, ...); 1672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1673 getKmpc_MicroPointerTy()}; 1674 auto *FnTy = 1675 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true); 1676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call"); 1677 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) { 1678 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) { 1679 llvm::LLVMContext &Ctx = F->getContext(); 1680 llvm::MDBuilder MDB(Ctx); 1681 // Annotate the callback behavior of the __kmpc_fork_call: 1682 // - The callback callee is argument number 2 (microtask). 1683 // - The first two arguments of the callback callee are unknown (-1). 1684 // - All variadic arguments to the __kmpc_fork_call are passed to the 1685 // callback callee. 1686 F->addMetadata( 1687 llvm::LLVMContext::MD_callback, 1688 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 1689 2, {-1, -1}, 1690 /* VarArgsArePassed */ true)})); 1691 } 1692 } 1693 break; 1694 } 1695 case OMPRTL__kmpc_global_thread_num: { 1696 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc); 1697 llvm::Type *TypeParams[] = {getIdentTyPointerTy()}; 1698 auto *FnTy = 1699 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 1700 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num"); 1701 break; 1702 } 1703 case OMPRTL__kmpc_threadprivate_cached: { 1704 // Build void *__kmpc_threadprivate_cached(ident_t *loc, 1705 // kmp_int32 global_tid, void *data, size_t size, void ***cache); 1706 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1707 CGM.VoidPtrTy, CGM.SizeTy, 1708 CGM.VoidPtrTy->getPointerTo()->getPointerTo()}; 1709 auto *FnTy = 1710 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false); 1711 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached"); 1712 break; 1713 } 1714 case OMPRTL__kmpc_critical: { 1715 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid, 1716 // kmp_critical_name *crit); 1717 llvm::Type *TypeParams[] = { 1718 getIdentTyPointerTy(), CGM.Int32Ty, 1719 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1720 auto *FnTy = 1721 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1722 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical"); 1723 break; 1724 } 1725 case OMPRTL__kmpc_critical_with_hint: { 1726 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid, 1727 // kmp_critical_name *crit, uintptr_t hint); 1728 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1729 llvm::PointerType::getUnqual(KmpCriticalNameTy), 1730 CGM.IntPtrTy}; 1731 auto *FnTy = 1732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint"); 1734 break; 1735 } 1736 case OMPRTL__kmpc_threadprivate_register: { 1737 // Build void __kmpc_threadprivate_register(ident_t *, void *data, 1738 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor); 1739 // typedef void *(*kmpc_ctor)(void *); 1740 auto *KmpcCtorTy = 1741 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy, 1742 /*isVarArg*/ false)->getPointerTo(); 1743 // typedef void *(*kmpc_cctor)(void *, void *); 1744 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 1745 auto *KmpcCopyCtorTy = 1746 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs, 1747 /*isVarArg*/ false) 1748 ->getPointerTo(); 1749 // typedef void (*kmpc_dtor)(void *); 1750 auto *KmpcDtorTy = 1751 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false) 1752 ->getPointerTo(); 1753 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy, 1754 KmpcCopyCtorTy, KmpcDtorTy}; 1755 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs, 1756 /*isVarArg*/ false); 1757 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register"); 1758 break; 1759 } 1760 case OMPRTL__kmpc_end_critical: { 1761 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid, 1762 // kmp_critical_name *crit); 1763 llvm::Type *TypeParams[] = { 1764 getIdentTyPointerTy(), CGM.Int32Ty, 1765 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1766 auto *FnTy = 1767 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1768 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical"); 1769 break; 1770 } 1771 case OMPRTL__kmpc_cancel_barrier: { 1772 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32 1773 // global_tid); 1774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1775 auto *FnTy = 1776 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier"); 1778 break; 1779 } 1780 case OMPRTL__kmpc_barrier: { 1781 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid); 1782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1783 auto *FnTy = 1784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier"); 1786 break; 1787 } 1788 case OMPRTL__kmpc_for_static_fini: { 1789 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid); 1790 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1791 auto *FnTy = 1792 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1793 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini"); 1794 break; 1795 } 1796 case OMPRTL__kmpc_push_num_threads: { 1797 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, 1798 // kmp_int32 num_threads) 1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1800 CGM.Int32Ty}; 1801 auto *FnTy = 1802 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1803 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads"); 1804 break; 1805 } 1806 case OMPRTL__kmpc_serialized_parallel: { 1807 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 1808 // global_tid); 1809 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1810 auto *FnTy = 1811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel"); 1813 break; 1814 } 1815 case OMPRTL__kmpc_end_serialized_parallel: { 1816 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 1817 // global_tid); 1818 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1819 auto *FnTy = 1820 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1821 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel"); 1822 break; 1823 } 1824 case OMPRTL__kmpc_flush: { 1825 // Build void __kmpc_flush(ident_t *loc); 1826 llvm::Type *TypeParams[] = {getIdentTyPointerTy()}; 1827 auto *FnTy = 1828 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1829 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush"); 1830 break; 1831 } 1832 case OMPRTL__kmpc_master: { 1833 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid); 1834 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1835 auto *FnTy = 1836 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1837 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master"); 1838 break; 1839 } 1840 case OMPRTL__kmpc_end_master: { 1841 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid); 1842 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1843 auto *FnTy = 1844 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1845 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master"); 1846 break; 1847 } 1848 case OMPRTL__kmpc_omp_taskyield: { 1849 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid, 1850 // int end_part); 1851 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy}; 1852 auto *FnTy = 1853 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1854 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield"); 1855 break; 1856 } 1857 case OMPRTL__kmpc_single: { 1858 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid); 1859 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1860 auto *FnTy = 1861 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1862 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single"); 1863 break; 1864 } 1865 case OMPRTL__kmpc_end_single: { 1866 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid); 1867 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1868 auto *FnTy = 1869 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1870 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single"); 1871 break; 1872 } 1873 case OMPRTL__kmpc_omp_task_alloc: { 1874 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid, 1875 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1876 // kmp_routine_entry_t *task_entry); 1877 assert(KmpRoutineEntryPtrTy != nullptr && 1878 "Type kmp_routine_entry_t must be created."); 1879 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, 1880 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy}; 1881 // Return void * and then cast to particular kmp_task_t type. 1882 auto *FnTy = 1883 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false); 1884 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc"); 1885 break; 1886 } 1887 case OMPRTL__kmpc_omp_task: { 1888 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t 1889 // *new_task); 1890 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1891 CGM.VoidPtrTy}; 1892 auto *FnTy = 1893 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1894 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task"); 1895 break; 1896 } 1897 case OMPRTL__kmpc_copyprivate: { 1898 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid, 1899 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *), 1900 // kmp_int32 didit); 1901 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 1902 auto *CpyFnTy = 1903 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false); 1904 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy, 1905 CGM.VoidPtrTy, CpyFnTy->getPointerTo(), 1906 CGM.Int32Ty}; 1907 auto *FnTy = 1908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate"); 1910 break; 1911 } 1912 case OMPRTL__kmpc_reduce: { 1913 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid, 1914 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void 1915 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck); 1916 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 1917 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams, 1918 /*isVarArg=*/false); 1919 llvm::Type *TypeParams[] = { 1920 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy, 1921 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(), 1922 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1923 auto *FnTy = 1924 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1925 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce"); 1926 break; 1927 } 1928 case OMPRTL__kmpc_reduce_nowait: { 1929 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32 1930 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, 1931 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name 1932 // *lck); 1933 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 1934 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams, 1935 /*isVarArg=*/false); 1936 llvm::Type *TypeParams[] = { 1937 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy, 1938 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(), 1939 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1940 auto *FnTy = 1941 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1942 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait"); 1943 break; 1944 } 1945 case OMPRTL__kmpc_end_reduce: { 1946 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid, 1947 // kmp_critical_name *lck); 1948 llvm::Type *TypeParams[] = { 1949 getIdentTyPointerTy(), CGM.Int32Ty, 1950 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1951 auto *FnTy = 1952 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1953 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce"); 1954 break; 1955 } 1956 case OMPRTL__kmpc_end_reduce_nowait: { 1957 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid, 1958 // kmp_critical_name *lck); 1959 llvm::Type *TypeParams[] = { 1960 getIdentTyPointerTy(), CGM.Int32Ty, 1961 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1962 auto *FnTy = 1963 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1964 RTLFn = 1965 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait"); 1966 break; 1967 } 1968 case OMPRTL__kmpc_omp_task_begin_if0: { 1969 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t 1970 // *new_task); 1971 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1972 CGM.VoidPtrTy}; 1973 auto *FnTy = 1974 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1975 RTLFn = 1976 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0"); 1977 break; 1978 } 1979 case OMPRTL__kmpc_omp_task_complete_if0: { 1980 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t 1981 // *new_task); 1982 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1983 CGM.VoidPtrTy}; 1984 auto *FnTy = 1985 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1986 RTLFn = CGM.CreateRuntimeFunction(FnTy, 1987 /*Name=*/"__kmpc_omp_task_complete_if0"); 1988 break; 1989 } 1990 case OMPRTL__kmpc_ordered: { 1991 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid); 1992 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1993 auto *FnTy = 1994 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1995 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered"); 1996 break; 1997 } 1998 case OMPRTL__kmpc_end_ordered: { 1999 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid); 2000 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 2001 auto *FnTy = 2002 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2003 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered"); 2004 break; 2005 } 2006 case OMPRTL__kmpc_omp_taskwait: { 2007 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid); 2008 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 2009 auto *FnTy = 2010 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 2011 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait"); 2012 break; 2013 } 2014 case OMPRTL__kmpc_taskgroup: { 2015 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid); 2016 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 2017 auto *FnTy = 2018 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2019 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup"); 2020 break; 2021 } 2022 case OMPRTL__kmpc_end_taskgroup: { 2023 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid); 2024 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 2025 auto *FnTy = 2026 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2027 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup"); 2028 break; 2029 } 2030 case OMPRTL__kmpc_push_proc_bind: { 2031 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, 2032 // int proc_bind) 2033 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy}; 2034 auto *FnTy = 2035 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2036 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind"); 2037 break; 2038 } 2039 case OMPRTL__kmpc_omp_task_with_deps: { 2040 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid, 2041 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list, 2042 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list); 2043 llvm::Type *TypeParams[] = { 2044 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty, 2045 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy}; 2046 auto *FnTy = 2047 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 2048 RTLFn = 2049 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps"); 2050 break; 2051 } 2052 case OMPRTL__kmpc_omp_wait_deps: { 2053 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid, 2054 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias, 2055 // kmp_depend_info_t *noalias_dep_list); 2056 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 2057 CGM.Int32Ty, CGM.VoidPtrTy, 2058 CGM.Int32Ty, CGM.VoidPtrTy}; 2059 auto *FnTy = 2060 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2061 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps"); 2062 break; 2063 } 2064 case OMPRTL__kmpc_cancellationpoint: { 2065 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32 2066 // global_tid, kmp_int32 cncl_kind) 2067 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy}; 2068 auto *FnTy = 2069 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2070 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint"); 2071 break; 2072 } 2073 case OMPRTL__kmpc_cancel: { 2074 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid, 2075 // kmp_int32 cncl_kind) 2076 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy}; 2077 auto *FnTy = 2078 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2079 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel"); 2080 break; 2081 } 2082 case OMPRTL__kmpc_push_num_teams: { 2083 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid, 2084 // kmp_int32 num_teams, kmp_int32 num_threads) 2085 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, 2086 CGM.Int32Ty}; 2087 auto *FnTy = 2088 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2089 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams"); 2090 break; 2091 } 2092 case OMPRTL__kmpc_fork_teams: { 2093 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro 2094 // microtask, ...); 2095 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 2096 getKmpc_MicroPointerTy()}; 2097 auto *FnTy = 2098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true); 2099 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams"); 2100 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) { 2101 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) { 2102 llvm::LLVMContext &Ctx = F->getContext(); 2103 llvm::MDBuilder MDB(Ctx); 2104 // Annotate the callback behavior of the __kmpc_fork_teams: 2105 // - The callback callee is argument number 2 (microtask). 2106 // - The first two arguments of the callback callee are unknown (-1). 2107 // - All variadic arguments to the __kmpc_fork_teams are passed to the 2108 // callback callee. 2109 F->addMetadata( 2110 llvm::LLVMContext::MD_callback, 2111 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2112 2, {-1, -1}, 2113 /* VarArgsArePassed */ true)})); 2114 } 2115 } 2116 break; 2117 } 2118 case OMPRTL__kmpc_taskloop: { 2119 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int 2120 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int 2121 // sched, kmp_uint64 grainsize, void *task_dup); 2122 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), 2123 CGM.IntTy, 2124 CGM.VoidPtrTy, 2125 CGM.IntTy, 2126 CGM.Int64Ty->getPointerTo(), 2127 CGM.Int64Ty->getPointerTo(), 2128 CGM.Int64Ty, 2129 CGM.IntTy, 2130 CGM.IntTy, 2131 CGM.Int64Ty, 2132 CGM.VoidPtrTy}; 2133 auto *FnTy = 2134 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2135 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop"); 2136 break; 2137 } 2138 case OMPRTL__kmpc_doacross_init: { 2139 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32 2140 // num_dims, struct kmp_dim *dims); 2141 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), 2142 CGM.Int32Ty, 2143 CGM.Int32Ty, 2144 CGM.VoidPtrTy}; 2145 auto *FnTy = 2146 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2147 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init"); 2148 break; 2149 } 2150 case OMPRTL__kmpc_doacross_fini: { 2151 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid); 2152 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 2153 auto *FnTy = 2154 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2155 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini"); 2156 break; 2157 } 2158 case OMPRTL__kmpc_doacross_post: { 2159 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64 2160 // *vec); 2161 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 2162 CGM.Int64Ty->getPointerTo()}; 2163 auto *FnTy = 2164 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2165 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post"); 2166 break; 2167 } 2168 case OMPRTL__kmpc_doacross_wait: { 2169 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64 2170 // *vec); 2171 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 2172 CGM.Int64Ty->getPointerTo()}; 2173 auto *FnTy = 2174 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2175 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait"); 2176 break; 2177 } 2178 case OMPRTL__kmpc_task_reduction_init: { 2179 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void 2180 // *data); 2181 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy}; 2182 auto *FnTy = 2183 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false); 2184 RTLFn = 2185 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init"); 2186 break; 2187 } 2188 case OMPRTL__kmpc_task_reduction_get_th_data: { 2189 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void 2190 // *d); 2191 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy}; 2192 auto *FnTy = 2193 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false); 2194 RTLFn = CGM.CreateRuntimeFunction( 2195 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data"); 2196 break; 2197 } 2198 case OMPRTL__kmpc_push_target_tripcount: { 2199 // Build void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64 2200 // size); 2201 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int64Ty}; 2202 llvm::FunctionType *FnTy = 2203 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2204 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_target_tripcount"); 2205 break; 2206 } 2207 case OMPRTL__tgt_target: { 2208 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t 2209 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 2210 // *arg_types); 2211 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2212 CGM.VoidPtrTy, 2213 CGM.Int32Ty, 2214 CGM.VoidPtrPtrTy, 2215 CGM.VoidPtrPtrTy, 2216 CGM.SizeTy->getPointerTo(), 2217 CGM.Int64Ty->getPointerTo()}; 2218 auto *FnTy = 2219 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2220 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target"); 2221 break; 2222 } 2223 case OMPRTL__tgt_target_nowait: { 2224 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr, 2225 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, 2226 // int64_t *arg_types); 2227 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2228 CGM.VoidPtrTy, 2229 CGM.Int32Ty, 2230 CGM.VoidPtrPtrTy, 2231 CGM.VoidPtrPtrTy, 2232 CGM.SizeTy->getPointerTo(), 2233 CGM.Int64Ty->getPointerTo()}; 2234 auto *FnTy = 2235 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2236 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait"); 2237 break; 2238 } 2239 case OMPRTL__tgt_target_teams: { 2240 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr, 2241 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, 2242 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit); 2243 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2244 CGM.VoidPtrTy, 2245 CGM.Int32Ty, 2246 CGM.VoidPtrPtrTy, 2247 CGM.VoidPtrPtrTy, 2248 CGM.SizeTy->getPointerTo(), 2249 CGM.Int64Ty->getPointerTo(), 2250 CGM.Int32Ty, 2251 CGM.Int32Ty}; 2252 auto *FnTy = 2253 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2254 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams"); 2255 break; 2256 } 2257 case OMPRTL__tgt_target_teams_nowait: { 2258 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void 2259 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t 2260 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit); 2261 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2262 CGM.VoidPtrTy, 2263 CGM.Int32Ty, 2264 CGM.VoidPtrPtrTy, 2265 CGM.VoidPtrPtrTy, 2266 CGM.SizeTy->getPointerTo(), 2267 CGM.Int64Ty->getPointerTo(), 2268 CGM.Int32Ty, 2269 CGM.Int32Ty}; 2270 auto *FnTy = 2271 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2272 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait"); 2273 break; 2274 } 2275 case OMPRTL__tgt_register_lib: { 2276 // Build void __tgt_register_lib(__tgt_bin_desc *desc); 2277 QualType ParamTy = 2278 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy()); 2279 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)}; 2280 auto *FnTy = 2281 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2282 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib"); 2283 break; 2284 } 2285 case OMPRTL__tgt_unregister_lib: { 2286 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc); 2287 QualType ParamTy = 2288 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy()); 2289 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)}; 2290 auto *FnTy = 2291 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2292 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib"); 2293 break; 2294 } 2295 case OMPRTL__tgt_target_data_begin: { 2296 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num, 2297 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 2298 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2299 CGM.Int32Ty, 2300 CGM.VoidPtrPtrTy, 2301 CGM.VoidPtrPtrTy, 2302 CGM.SizeTy->getPointerTo(), 2303 CGM.Int64Ty->getPointerTo()}; 2304 auto *FnTy = 2305 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2306 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin"); 2307 break; 2308 } 2309 case OMPRTL__tgt_target_data_begin_nowait: { 2310 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t 2311 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 2312 // *arg_types); 2313 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2314 CGM.Int32Ty, 2315 CGM.VoidPtrPtrTy, 2316 CGM.VoidPtrPtrTy, 2317 CGM.SizeTy->getPointerTo(), 2318 CGM.Int64Ty->getPointerTo()}; 2319 auto *FnTy = 2320 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2321 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait"); 2322 break; 2323 } 2324 case OMPRTL__tgt_target_data_end: { 2325 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num, 2326 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 2327 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2328 CGM.Int32Ty, 2329 CGM.VoidPtrPtrTy, 2330 CGM.VoidPtrPtrTy, 2331 CGM.SizeTy->getPointerTo(), 2332 CGM.Int64Ty->getPointerTo()}; 2333 auto *FnTy = 2334 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2335 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end"); 2336 break; 2337 } 2338 case OMPRTL__tgt_target_data_end_nowait: { 2339 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t 2340 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 2341 // *arg_types); 2342 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2343 CGM.Int32Ty, 2344 CGM.VoidPtrPtrTy, 2345 CGM.VoidPtrPtrTy, 2346 CGM.SizeTy->getPointerTo(), 2347 CGM.Int64Ty->getPointerTo()}; 2348 auto *FnTy = 2349 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2350 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait"); 2351 break; 2352 } 2353 case OMPRTL__tgt_target_data_update: { 2354 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num, 2355 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 2356 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2357 CGM.Int32Ty, 2358 CGM.VoidPtrPtrTy, 2359 CGM.VoidPtrPtrTy, 2360 CGM.SizeTy->getPointerTo(), 2361 CGM.Int64Ty->getPointerTo()}; 2362 auto *FnTy = 2363 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2364 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update"); 2365 break; 2366 } 2367 case OMPRTL__tgt_target_data_update_nowait: { 2368 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t 2369 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 2370 // *arg_types); 2371 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2372 CGM.Int32Ty, 2373 CGM.VoidPtrPtrTy, 2374 CGM.VoidPtrPtrTy, 2375 CGM.SizeTy->getPointerTo(), 2376 CGM.Int64Ty->getPointerTo()}; 2377 auto *FnTy = 2378 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2379 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait"); 2380 break; 2381 } 2382 } 2383 assert(RTLFn && "Unable to find OpenMP runtime function"); 2384 return RTLFn; 2385 } 2386 2387 llvm::FunctionCallee 2388 CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned) { 2389 assert((IVSize == 32 || IVSize == 64) && 2390 "IV size is not compatible with the omp runtime"); 2391 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4" 2392 : "__kmpc_for_static_init_4u") 2393 : (IVSigned ? "__kmpc_for_static_init_8" 2394 : "__kmpc_for_static_init_8u"); 2395 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; 2396 auto *PtrTy = llvm::PointerType::getUnqual(ITy); 2397 llvm::Type *TypeParams[] = { 2398 getIdentTyPointerTy(), // loc 2399 CGM.Int32Ty, // tid 2400 CGM.Int32Ty, // schedtype 2401 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter 2402 PtrTy, // p_lower 2403 PtrTy, // p_upper 2404 PtrTy, // p_stride 2405 ITy, // incr 2406 ITy // chunk 2407 }; 2408 auto *FnTy = 2409 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2410 return CGM.CreateRuntimeFunction(FnTy, Name); 2411 } 2412 2413 llvm::FunctionCallee 2414 CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) { 2415 assert((IVSize == 32 || IVSize == 64) && 2416 "IV size is not compatible with the omp runtime"); 2417 StringRef Name = 2418 IVSize == 32 2419 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u") 2420 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u"); 2421 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; 2422 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc 2423 CGM.Int32Ty, // tid 2424 CGM.Int32Ty, // schedtype 2425 ITy, // lower 2426 ITy, // upper 2427 ITy, // stride 2428 ITy // chunk 2429 }; 2430 auto *FnTy = 2431 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2432 return CGM.CreateRuntimeFunction(FnTy, Name); 2433 } 2434 2435 llvm::FunctionCallee 2436 CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) { 2437 assert((IVSize == 32 || IVSize == 64) && 2438 "IV size is not compatible with the omp runtime"); 2439 StringRef Name = 2440 IVSize == 32 2441 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u") 2442 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u"); 2443 llvm::Type *TypeParams[] = { 2444 getIdentTyPointerTy(), // loc 2445 CGM.Int32Ty, // tid 2446 }; 2447 auto *FnTy = 2448 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2449 return CGM.CreateRuntimeFunction(FnTy, Name); 2450 } 2451 2452 llvm::FunctionCallee 2453 CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) { 2454 assert((IVSize == 32 || IVSize == 64) && 2455 "IV size is not compatible with the omp runtime"); 2456 StringRef Name = 2457 IVSize == 32 2458 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u") 2459 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u"); 2460 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; 2461 auto *PtrTy = llvm::PointerType::getUnqual(ITy); 2462 llvm::Type *TypeParams[] = { 2463 getIdentTyPointerTy(), // loc 2464 CGM.Int32Ty, // tid 2465 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter 2466 PtrTy, // p_lower 2467 PtrTy, // p_upper 2468 PtrTy // p_stride 2469 }; 2470 auto *FnTy = 2471 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2472 return CGM.CreateRuntimeFunction(FnTy, Name); 2473 } 2474 2475 Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) { 2476 if (CGM.getLangOpts().OpenMPSimd) 2477 return Address::invalid(); 2478 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2479 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2480 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 2481 SmallString<64> PtrName; 2482 { 2483 llvm::raw_svector_ostream OS(PtrName); 2484 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr"; 2485 } 2486 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName); 2487 if (!Ptr) { 2488 QualType PtrTy = CGM.getContext().getPointerType(VD->getType()); 2489 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy), 2490 PtrName); 2491 if (!CGM.getLangOpts().OpenMPIsDevice) { 2492 auto *GV = cast<llvm::GlobalVariable>(Ptr); 2493 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 2494 GV->setInitializer(CGM.GetAddrOfGlobal(VD)); 2495 } 2496 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr)); 2497 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr)); 2498 } 2499 return Address(Ptr, CGM.getContext().getDeclAlign(VD)); 2500 } 2501 return Address::invalid(); 2502 } 2503 2504 llvm::Constant * 2505 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) { 2506 assert(!CGM.getLangOpts().OpenMPUseTLS || 2507 !CGM.getContext().getTargetInfo().isTLSSupported()); 2508 // Lookup the entry, lazily creating it if necessary. 2509 std::string Suffix = getName({"cache", ""}); 2510 return getOrCreateInternalVariable( 2511 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix)); 2512 } 2513 2514 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF, 2515 const VarDecl *VD, 2516 Address VDAddr, 2517 SourceLocation Loc) { 2518 if (CGM.getLangOpts().OpenMPUseTLS && 2519 CGM.getContext().getTargetInfo().isTLSSupported()) 2520 return VDAddr; 2521 2522 llvm::Type *VarTy = VDAddr.getElementType(); 2523 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 2524 CGF.Builder.CreatePointerCast(VDAddr.getPointer(), 2525 CGM.Int8PtrTy), 2526 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)), 2527 getOrCreateThreadPrivateCache(VD)}; 2528 return Address(CGF.EmitRuntimeCall( 2529 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args), 2530 VDAddr.getAlignment()); 2531 } 2532 2533 void CGOpenMPRuntime::emitThreadPrivateVarInit( 2534 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor, 2535 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) { 2536 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime 2537 // library. 2538 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc); 2539 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num), 2540 OMPLoc); 2541 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor) 2542 // to register constructor/destructor for variable. 2543 llvm::Value *Args[] = { 2544 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy), 2545 Ctor, CopyCtor, Dtor}; 2546 CGF.EmitRuntimeCall( 2547 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args); 2548 } 2549 2550 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition( 2551 const VarDecl *VD, Address VDAddr, SourceLocation Loc, 2552 bool PerformInit, CodeGenFunction *CGF) { 2553 if (CGM.getLangOpts().OpenMPUseTLS && 2554 CGM.getContext().getTargetInfo().isTLSSupported()) 2555 return nullptr; 2556 2557 VD = VD->getDefinition(CGM.getContext()); 2558 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) { 2559 QualType ASTTy = VD->getType(); 2560 2561 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr; 2562 const Expr *Init = VD->getAnyInitializer(); 2563 if (CGM.getLangOpts().CPlusPlus && PerformInit) { 2564 // Generate function that re-emits the declaration's initializer into the 2565 // threadprivate copy of the variable VD 2566 CodeGenFunction CtorCGF(CGM); 2567 FunctionArgList Args; 2568 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc, 2569 /*Id=*/nullptr, CGM.getContext().VoidPtrTy, 2570 ImplicitParamDecl::Other); 2571 Args.push_back(&Dst); 2572 2573 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( 2574 CGM.getContext().VoidPtrTy, Args); 2575 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 2576 std::string Name = getName({"__kmpc_global_ctor_", ""}); 2577 llvm::Function *Fn = 2578 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc); 2579 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI, 2580 Args, Loc, Loc); 2581 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar( 2582 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false, 2583 CGM.getContext().VoidPtrTy, Dst.getLocation()); 2584 Address Arg = Address(ArgVal, VDAddr.getAlignment()); 2585 Arg = CtorCGF.Builder.CreateElementBitCast( 2586 Arg, CtorCGF.ConvertTypeForMem(ASTTy)); 2587 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(), 2588 /*IsInitializer=*/true); 2589 ArgVal = CtorCGF.EmitLoadOfScalar( 2590 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false, 2591 CGM.getContext().VoidPtrTy, Dst.getLocation()); 2592 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue); 2593 CtorCGF.FinishFunction(); 2594 Ctor = Fn; 2595 } 2596 if (VD->getType().isDestructedType() != QualType::DK_none) { 2597 // Generate function that emits destructor call for the threadprivate copy 2598 // of the variable VD 2599 CodeGenFunction DtorCGF(CGM); 2600 FunctionArgList Args; 2601 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc, 2602 /*Id=*/nullptr, CGM.getContext().VoidPtrTy, 2603 ImplicitParamDecl::Other); 2604 Args.push_back(&Dst); 2605 2606 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( 2607 CGM.getContext().VoidTy, Args); 2608 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 2609 std::string Name = getName({"__kmpc_global_dtor_", ""}); 2610 llvm::Function *Fn = 2611 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc); 2612 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF); 2613 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args, 2614 Loc, Loc); 2615 // Create a scope with an artificial location for the body of this function. 2616 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF); 2617 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar( 2618 DtorCGF.GetAddrOfLocalVar(&Dst), 2619 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation()); 2620 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy, 2621 DtorCGF.getDestroyer(ASTTy.isDestructedType()), 2622 DtorCGF.needsEHCleanup(ASTTy.isDestructedType())); 2623 DtorCGF.FinishFunction(); 2624 Dtor = Fn; 2625 } 2626 // Do not emit init function if it is not required. 2627 if (!Ctor && !Dtor) 2628 return nullptr; 2629 2630 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 2631 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs, 2632 /*isVarArg=*/false) 2633 ->getPointerTo(); 2634 // Copying constructor for the threadprivate variable. 2635 // Must be NULL - reserved by runtime, but currently it requires that this 2636 // parameter is always NULL. Otherwise it fires assertion. 2637 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy); 2638 if (Ctor == nullptr) { 2639 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy, 2640 /*isVarArg=*/false) 2641 ->getPointerTo(); 2642 Ctor = llvm::Constant::getNullValue(CtorTy); 2643 } 2644 if (Dtor == nullptr) { 2645 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, 2646 /*isVarArg=*/false) 2647 ->getPointerTo(); 2648 Dtor = llvm::Constant::getNullValue(DtorTy); 2649 } 2650 if (!CGF) { 2651 auto *InitFunctionTy = 2652 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false); 2653 std::string Name = getName({"__omp_threadprivate_init_", ""}); 2654 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction( 2655 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction()); 2656 CodeGenFunction InitCGF(CGM); 2657 FunctionArgList ArgList; 2658 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction, 2659 CGM.getTypes().arrangeNullaryFunction(), ArgList, 2660 Loc, Loc); 2661 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc); 2662 InitCGF.FinishFunction(); 2663 return InitFunction; 2664 } 2665 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc); 2666 } 2667 return nullptr; 2668 } 2669 2670 /// Obtain information that uniquely identifies a target entry. This 2671 /// consists of the file and device IDs as well as line number associated with 2672 /// the relevant entry source location. 2673 static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc, 2674 unsigned &DeviceID, unsigned &FileID, 2675 unsigned &LineNum) { 2676 SourceManager &SM = C.getSourceManager(); 2677 2678 // The loc should be always valid and have a file ID (the user cannot use 2679 // #pragma directives in macros) 2680 2681 assert(Loc.isValid() && "Source location is expected to be always valid."); 2682 2683 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2684 assert(PLoc.isValid() && "Source location is expected to be always valid."); 2685 2686 llvm::sys::fs::UniqueID ID; 2687 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 2688 SM.getDiagnostics().Report(diag::err_cannot_open_file) 2689 << PLoc.getFilename() << EC.message(); 2690 2691 DeviceID = ID.getDevice(); 2692 FileID = ID.getFile(); 2693 LineNum = PLoc.getLine(); 2694 } 2695 2696 bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD, 2697 llvm::GlobalVariable *Addr, 2698 bool PerformInit) { 2699 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2700 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2701 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) 2702 return CGM.getLangOpts().OpenMPIsDevice; 2703 VD = VD->getDefinition(CGM.getContext()); 2704 if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second) 2705 return CGM.getLangOpts().OpenMPIsDevice; 2706 2707 QualType ASTTy = VD->getType(); 2708 2709 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc(); 2710 // Produce the unique prefix to identify the new target regions. We use 2711 // the source location of the variable declaration which we know to not 2712 // conflict with any target region. 2713 unsigned DeviceID; 2714 unsigned FileID; 2715 unsigned Line; 2716 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line); 2717 SmallString<128> Buffer, Out; 2718 { 2719 llvm::raw_svector_ostream OS(Buffer); 2720 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID) 2721 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line; 2722 } 2723 2724 const Expr *Init = VD->getAnyInitializer(); 2725 if (CGM.getLangOpts().CPlusPlus && PerformInit) { 2726 llvm::Constant *Ctor; 2727 llvm::Constant *ID; 2728 if (CGM.getLangOpts().OpenMPIsDevice) { 2729 // Generate function that re-emits the declaration's initializer into 2730 // the threadprivate copy of the variable VD 2731 CodeGenFunction CtorCGF(CGM); 2732 2733 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); 2734 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 2735 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction( 2736 FTy, Twine(Buffer, "_ctor"), FI, Loc); 2737 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF); 2738 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, 2739 FunctionArgList(), Loc, Loc); 2740 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF); 2741 CtorCGF.EmitAnyExprToMem(Init, 2742 Address(Addr, CGM.getContext().getDeclAlign(VD)), 2743 Init->getType().getQualifiers(), 2744 /*IsInitializer=*/true); 2745 CtorCGF.FinishFunction(); 2746 Ctor = Fn; 2747 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); 2748 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor)); 2749 } else { 2750 Ctor = new llvm::GlobalVariable( 2751 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, 2752 llvm::GlobalValue::PrivateLinkage, 2753 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor")); 2754 ID = Ctor; 2755 } 2756 2757 // Register the information for the entry associated with the constructor. 2758 Out.clear(); 2759 OffloadEntriesInfoManager.registerTargetRegionEntryInfo( 2760 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor, 2761 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor); 2762 } 2763 if (VD->getType().isDestructedType() != QualType::DK_none) { 2764 llvm::Constant *Dtor; 2765 llvm::Constant *ID; 2766 if (CGM.getLangOpts().OpenMPIsDevice) { 2767 // Generate function that emits destructor call for the threadprivate 2768 // copy of the variable VD 2769 CodeGenFunction DtorCGF(CGM); 2770 2771 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); 2772 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 2773 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction( 2774 FTy, Twine(Buffer, "_dtor"), FI, Loc); 2775 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF); 2776 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, 2777 FunctionArgList(), Loc, Loc); 2778 // Create a scope with an artificial location for the body of this 2779 // function. 2780 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF); 2781 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)), 2782 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()), 2783 DtorCGF.needsEHCleanup(ASTTy.isDestructedType())); 2784 DtorCGF.FinishFunction(); 2785 Dtor = Fn; 2786 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); 2787 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor)); 2788 } else { 2789 Dtor = new llvm::GlobalVariable( 2790 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, 2791 llvm::GlobalValue::PrivateLinkage, 2792 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor")); 2793 ID = Dtor; 2794 } 2795 // Register the information for the entry associated with the destructor. 2796 Out.clear(); 2797 OffloadEntriesInfoManager.registerTargetRegionEntryInfo( 2798 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor, 2799 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor); 2800 } 2801 return CGM.getLangOpts().OpenMPIsDevice; 2802 } 2803 2804 Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, 2805 QualType VarType, 2806 StringRef Name) { 2807 std::string Suffix = getName({"artificial", ""}); 2808 std::string CacheSuffix = getName({"cache", ""}); 2809 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType); 2810 llvm::Value *GAddr = 2811 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix)); 2812 llvm::Value *Args[] = { 2813 emitUpdateLocation(CGF, SourceLocation()), 2814 getThreadID(CGF, SourceLocation()), 2815 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy), 2816 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy, 2817 /*IsSigned=*/false), 2818 getOrCreateInternalVariable( 2819 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))}; 2820 return Address( 2821 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 2822 CGF.EmitRuntimeCall( 2823 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args), 2824 VarLVType->getPointerTo(/*AddrSpace=*/0)), 2825 CGM.getPointerAlign()); 2826 } 2827 2828 void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond, 2829 const RegionCodeGenTy &ThenGen, 2830 const RegionCodeGenTy &ElseGen) { 2831 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange()); 2832 2833 // If the condition constant folds and can be elided, try to avoid emitting 2834 // the condition and the dead arm of the if/else. 2835 bool CondConstant; 2836 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) { 2837 if (CondConstant) 2838 ThenGen(CGF); 2839 else 2840 ElseGen(CGF); 2841 return; 2842 } 2843 2844 // Otherwise, the condition did not fold, or we couldn't elide it. Just 2845 // emit the conditional branch. 2846 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then"); 2847 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else"); 2848 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end"); 2849 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0); 2850 2851 // Emit the 'then' code. 2852 CGF.EmitBlock(ThenBlock); 2853 ThenGen(CGF); 2854 CGF.EmitBranch(ContBlock); 2855 // Emit the 'else' code if present. 2856 // There is no need to emit line number for unconditional branch. 2857 (void)ApplyDebugLocation::CreateEmpty(CGF); 2858 CGF.EmitBlock(ElseBlock); 2859 ElseGen(CGF); 2860 // There is no need to emit line number for unconditional branch. 2861 (void)ApplyDebugLocation::CreateEmpty(CGF); 2862 CGF.EmitBranch(ContBlock); 2863 // Emit the continuation block for code after the if. 2864 CGF.EmitBlock(ContBlock, /*IsFinished=*/true); 2865 } 2866 2867 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, 2868 llvm::Function *OutlinedFn, 2869 ArrayRef<llvm::Value *> CapturedVars, 2870 const Expr *IfCond) { 2871 if (!CGF.HaveInsertPoint()) 2872 return; 2873 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc); 2874 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF, 2875 PrePostActionTy &) { 2876 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn); 2877 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 2878 llvm::Value *Args[] = { 2879 RTLoc, 2880 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars 2881 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())}; 2882 llvm::SmallVector<llvm::Value *, 16> RealArgs; 2883 RealArgs.append(std::begin(Args), std::end(Args)); 2884 RealArgs.append(CapturedVars.begin(), CapturedVars.end()); 2885 2886 llvm::FunctionCallee RTLFn = 2887 RT.createRuntimeFunction(OMPRTL__kmpc_fork_call); 2888 CGF.EmitRuntimeCall(RTLFn, RealArgs); 2889 }; 2890 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF, 2891 PrePostActionTy &) { 2892 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 2893 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc); 2894 // Build calls: 2895 // __kmpc_serialized_parallel(&Loc, GTid); 2896 llvm::Value *Args[] = {RTLoc, ThreadID}; 2897 CGF.EmitRuntimeCall( 2898 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args); 2899 2900 // OutlinedFn(>id, &zero, CapturedStruct); 2901 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, 2902 /*Name*/ ".zero.addr"); 2903 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0)); 2904 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; 2905 // ThreadId for serialized parallels is 0. 2906 OutlinedFnArgs.push_back(ZeroAddr.getPointer()); 2907 OutlinedFnArgs.push_back(ZeroAddr.getPointer()); 2908 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); 2909 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs); 2910 2911 // __kmpc_end_serialized_parallel(&Loc, GTid); 2912 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID}; 2913 CGF.EmitRuntimeCall( 2914 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), 2915 EndArgs); 2916 }; 2917 if (IfCond) { 2918 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen); 2919 } else { 2920 RegionCodeGenTy ThenRCG(ThenGen); 2921 ThenRCG(CGF); 2922 } 2923 } 2924 2925 // If we're inside an (outlined) parallel region, use the region info's 2926 // thread-ID variable (it is passed in a first argument of the outlined function 2927 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in 2928 // regular serial code region, get thread ID by calling kmp_int32 2929 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and 2930 // return the address of that temp. 2931 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF, 2932 SourceLocation Loc) { 2933 if (auto *OMPRegionInfo = 2934 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) 2935 if (OMPRegionInfo->getThreadIDVariable()) 2936 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress(); 2937 2938 llvm::Value *ThreadID = getThreadID(CGF, Loc); 2939 QualType Int32Ty = 2940 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true); 2941 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp."); 2942 CGF.EmitStoreOfScalar(ThreadID, 2943 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty)); 2944 2945 return ThreadIDTemp; 2946 } 2947 2948 llvm::Constant *CGOpenMPRuntime::getOrCreateInternalVariable( 2949 llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) { 2950 SmallString<256> Buffer; 2951 llvm::raw_svector_ostream Out(Buffer); 2952 Out << Name; 2953 StringRef RuntimeName = Out.str(); 2954 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first; 2955 if (Elem.second) { 2956 assert(Elem.second->getType()->getPointerElementType() == Ty && 2957 "OMP internal variable has different type than requested"); 2958 return &*Elem.second; 2959 } 2960 2961 return Elem.second = new llvm::GlobalVariable( 2962 CGM.getModule(), Ty, /*IsConstant*/ false, 2963 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty), 2964 Elem.first(), /*InsertBefore=*/nullptr, 2965 llvm::GlobalValue::NotThreadLocal, AddressSpace); 2966 } 2967 2968 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) { 2969 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str(); 2970 std::string Name = getName({Prefix, "var"}); 2971 return getOrCreateInternalVariable(KmpCriticalNameTy, Name); 2972 } 2973 2974 namespace { 2975 /// Common pre(post)-action for different OpenMP constructs. 2976 class CommonActionTy final : public PrePostActionTy { 2977 llvm::FunctionCallee EnterCallee; 2978 ArrayRef<llvm::Value *> EnterArgs; 2979 llvm::FunctionCallee ExitCallee; 2980 ArrayRef<llvm::Value *> ExitArgs; 2981 bool Conditional; 2982 llvm::BasicBlock *ContBlock = nullptr; 2983 2984 public: 2985 CommonActionTy(llvm::FunctionCallee EnterCallee, 2986 ArrayRef<llvm::Value *> EnterArgs, 2987 llvm::FunctionCallee ExitCallee, 2988 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false) 2989 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee), 2990 ExitArgs(ExitArgs), Conditional(Conditional) {} 2991 void Enter(CodeGenFunction &CGF) override { 2992 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs); 2993 if (Conditional) { 2994 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes); 2995 auto *ThenBlock = CGF.createBasicBlock("omp_if.then"); 2996 ContBlock = CGF.createBasicBlock("omp_if.end"); 2997 // Generate the branch (If-stmt) 2998 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock); 2999 CGF.EmitBlock(ThenBlock); 3000 } 3001 } 3002 void Done(CodeGenFunction &CGF) { 3003 // Emit the rest of blocks/branches 3004 CGF.EmitBranch(ContBlock); 3005 CGF.EmitBlock(ContBlock, true); 3006 } 3007 void Exit(CodeGenFunction &CGF) override { 3008 CGF.EmitRuntimeCall(ExitCallee, ExitArgs); 3009 } 3010 }; 3011 } // anonymous namespace 3012 3013 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF, 3014 StringRef CriticalName, 3015 const RegionCodeGenTy &CriticalOpGen, 3016 SourceLocation Loc, const Expr *Hint) { 3017 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]); 3018 // CriticalOpGen(); 3019 // __kmpc_end_critical(ident_t *, gtid, Lock); 3020 // Prepare arguments and build a call to __kmpc_critical 3021 if (!CGF.HaveInsertPoint()) 3022 return; 3023 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 3024 getCriticalRegionLock(CriticalName)}; 3025 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), 3026 std::end(Args)); 3027 if (Hint) { 3028 EnterArgs.push_back(CGF.Builder.CreateIntCast( 3029 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false)); 3030 } 3031 CommonActionTy Action( 3032 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint 3033 : OMPRTL__kmpc_critical), 3034 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args); 3035 CriticalOpGen.setAction(Action); 3036 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen); 3037 } 3038 3039 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF, 3040 const RegionCodeGenTy &MasterOpGen, 3041 SourceLocation Loc) { 3042 if (!CGF.HaveInsertPoint()) 3043 return; 3044 // if(__kmpc_master(ident_t *, gtid)) { 3045 // MasterOpGen(); 3046 // __kmpc_end_master(ident_t *, gtid); 3047 // } 3048 // Prepare arguments and build a call to __kmpc_master 3049 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 3050 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args, 3051 createRuntimeFunction(OMPRTL__kmpc_end_master), Args, 3052 /*Conditional=*/true); 3053 MasterOpGen.setAction(Action); 3054 emitInlinedDirective(CGF, OMPD_master, MasterOpGen); 3055 Action.Done(CGF); 3056 } 3057 3058 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF, 3059 SourceLocation Loc) { 3060 if (!CGF.HaveInsertPoint()) 3061 return; 3062 // Build call __kmpc_omp_taskyield(loc, thread_id, 0); 3063 llvm::Value *Args[] = { 3064 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 3065 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)}; 3066 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args); 3067 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) 3068 Region->emitUntiedSwitch(CGF); 3069 } 3070 3071 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF, 3072 const RegionCodeGenTy &TaskgroupOpGen, 3073 SourceLocation Loc) { 3074 if (!CGF.HaveInsertPoint()) 3075 return; 3076 // __kmpc_taskgroup(ident_t *, gtid); 3077 // TaskgroupOpGen(); 3078 // __kmpc_end_taskgroup(ident_t *, gtid); 3079 // Prepare arguments and build a call to __kmpc_taskgroup 3080 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 3081 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args, 3082 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup), 3083 Args); 3084 TaskgroupOpGen.setAction(Action); 3085 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen); 3086 } 3087 3088 /// Given an array of pointers to variables, project the address of a 3089 /// given variable. 3090 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array, 3091 unsigned Index, const VarDecl *Var) { 3092 // Pull out the pointer to the variable. 3093 Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index); 3094 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr); 3095 3096 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var)); 3097 Addr = CGF.Builder.CreateElementBitCast( 3098 Addr, CGF.ConvertTypeForMem(Var->getType())); 3099 return Addr; 3100 } 3101 3102 static llvm::Value *emitCopyprivateCopyFunction( 3103 CodeGenModule &CGM, llvm::Type *ArgsType, 3104 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, 3105 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps, 3106 SourceLocation Loc) { 3107 ASTContext &C = CGM.getContext(); 3108 // void copy_func(void *LHSArg, void *RHSArg); 3109 FunctionArgList Args; 3110 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 3111 ImplicitParamDecl::Other); 3112 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 3113 ImplicitParamDecl::Other); 3114 Args.push_back(&LHSArg); 3115 Args.push_back(&RHSArg); 3116 const auto &CGFI = 3117 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 3118 std::string Name = 3119 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"}); 3120 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI), 3121 llvm::GlobalValue::InternalLinkage, Name, 3122 &CGM.getModule()); 3123 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); 3124 Fn->setDoesNotRecurse(); 3125 CodeGenFunction CGF(CGM); 3126 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); 3127 // Dest = (void*[n])(LHSArg); 3128 // Src = (void*[n])(RHSArg); 3129 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 3130 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)), 3131 ArgsType), CGF.getPointerAlign()); 3132 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 3133 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)), 3134 ArgsType), CGF.getPointerAlign()); 3135 // *(Type0*)Dst[0] = *(Type0*)Src[0]; 3136 // *(Type1*)Dst[1] = *(Type1*)Src[1]; 3137 // ... 3138 // *(Typen*)Dst[n] = *(Typen*)Src[n]; 3139 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) { 3140 const auto *DestVar = 3141 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()); 3142 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar); 3143 3144 const auto *SrcVar = 3145 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()); 3146 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar); 3147 3148 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl(); 3149 QualType Type = VD->getType(); 3150 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]); 3151 } 3152 CGF.FinishFunction(); 3153 return Fn; 3154 } 3155 3156 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF, 3157 const RegionCodeGenTy &SingleOpGen, 3158 SourceLocation Loc, 3159 ArrayRef<const Expr *> CopyprivateVars, 3160 ArrayRef<const Expr *> SrcExprs, 3161 ArrayRef<const Expr *> DstExprs, 3162 ArrayRef<const Expr *> AssignmentOps) { 3163 if (!CGF.HaveInsertPoint()) 3164 return; 3165 assert(CopyprivateVars.size() == SrcExprs.size() && 3166 CopyprivateVars.size() == DstExprs.size() && 3167 CopyprivateVars.size() == AssignmentOps.size()); 3168 ASTContext &C = CGM.getContext(); 3169 // int32 did_it = 0; 3170 // if(__kmpc_single(ident_t *, gtid)) { 3171 // SingleOpGen(); 3172 // __kmpc_end_single(ident_t *, gtid); 3173 // did_it = 1; 3174 // } 3175 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, 3176 // <copy_func>, did_it); 3177 3178 Address DidIt = Address::invalid(); 3179 if (!CopyprivateVars.empty()) { 3180 // int32 did_it = 0; 3181 QualType KmpInt32Ty = 3182 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 3183 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it"); 3184 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt); 3185 } 3186 // Prepare arguments and build a call to __kmpc_single 3187 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 3188 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args, 3189 createRuntimeFunction(OMPRTL__kmpc_end_single), Args, 3190 /*Conditional=*/true); 3191 SingleOpGen.setAction(Action); 3192 emitInlinedDirective(CGF, OMPD_single, SingleOpGen); 3193 if (DidIt.isValid()) { 3194 // did_it = 1; 3195 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt); 3196 } 3197 Action.Done(CGF); 3198 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, 3199 // <copy_func>, did_it); 3200 if (DidIt.isValid()) { 3201 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size()); 3202 QualType CopyprivateArrayTy = 3203 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal, 3204 /*IndexTypeQuals=*/0); 3205 // Create a list of all private variables for copyprivate. 3206 Address CopyprivateList = 3207 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list"); 3208 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) { 3209 Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I); 3210 CGF.Builder.CreateStore( 3211 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 3212 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy), 3213 Elem); 3214 } 3215 // Build function that copies private values from single region to all other 3216 // threads in the corresponding parallel region. 3217 llvm::Value *CpyFn = emitCopyprivateCopyFunction( 3218 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(), 3219 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc); 3220 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy); 3221 Address CL = 3222 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList, 3223 CGF.VoidPtrTy); 3224 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt); 3225 llvm::Value *Args[] = { 3226 emitUpdateLocation(CGF, Loc), // ident_t *<loc> 3227 getThreadID(CGF, Loc), // i32 <gtid> 3228 BufSize, // size_t <buf_size> 3229 CL.getPointer(), // void *<copyprivate list> 3230 CpyFn, // void (*) (void *, void *) <copy_func> 3231 DidItVal // i32 did_it 3232 }; 3233 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args); 3234 } 3235 } 3236 3237 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF, 3238 const RegionCodeGenTy &OrderedOpGen, 3239 SourceLocation Loc, bool IsThreads) { 3240 if (!CGF.HaveInsertPoint()) 3241 return; 3242 // __kmpc_ordered(ident_t *, gtid); 3243 // OrderedOpGen(); 3244 // __kmpc_end_ordered(ident_t *, gtid); 3245 // Prepare arguments and build a call to __kmpc_ordered 3246 if (IsThreads) { 3247 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 3248 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args, 3249 createRuntimeFunction(OMPRTL__kmpc_end_ordered), 3250 Args); 3251 OrderedOpGen.setAction(Action); 3252 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen); 3253 return; 3254 } 3255 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen); 3256 } 3257 3258 unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) { 3259 unsigned Flags; 3260 if (Kind == OMPD_for) 3261 Flags = OMP_IDENT_BARRIER_IMPL_FOR; 3262 else if (Kind == OMPD_sections) 3263 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS; 3264 else if (Kind == OMPD_single) 3265 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE; 3266 else if (Kind == OMPD_barrier) 3267 Flags = OMP_IDENT_BARRIER_EXPL; 3268 else 3269 Flags = OMP_IDENT_BARRIER_IMPL; 3270 return Flags; 3271 } 3272 3273 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, 3274 OpenMPDirectiveKind Kind, bool EmitChecks, 3275 bool ForceSimpleCall) { 3276 if (!CGF.HaveInsertPoint()) 3277 return; 3278 // Build call __kmpc_cancel_barrier(loc, thread_id); 3279 // Build call __kmpc_barrier(loc, thread_id); 3280 unsigned Flags = getDefaultFlagsForBarriers(Kind); 3281 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc, 3282 // thread_id); 3283 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags), 3284 getThreadID(CGF, Loc)}; 3285 if (auto *OMPRegionInfo = 3286 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { 3287 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) { 3288 llvm::Value *Result = CGF.EmitRuntimeCall( 3289 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args); 3290 if (EmitChecks) { 3291 // if (__kmpc_cancel_barrier()) { 3292 // exit from construct; 3293 // } 3294 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit"); 3295 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue"); 3296 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result); 3297 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB); 3298 CGF.EmitBlock(ExitBB); 3299 // exit from construct; 3300 CodeGenFunction::JumpDest CancelDestination = 3301 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind()); 3302 CGF.EmitBranchThroughCleanup(CancelDestination); 3303 CGF.EmitBlock(ContBB, /*IsFinished=*/true); 3304 } 3305 return; 3306 } 3307 } 3308 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args); 3309 } 3310 3311 /// Map the OpenMP loop schedule to the runtime enumeration. 3312 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind, 3313 bool Chunked, bool Ordered) { 3314 switch (ScheduleKind) { 3315 case OMPC_SCHEDULE_static: 3316 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked) 3317 : (Ordered ? OMP_ord_static : OMP_sch_static); 3318 case OMPC_SCHEDULE_dynamic: 3319 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked; 3320 case OMPC_SCHEDULE_guided: 3321 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked; 3322 case OMPC_SCHEDULE_runtime: 3323 return Ordered ? OMP_ord_runtime : OMP_sch_runtime; 3324 case OMPC_SCHEDULE_auto: 3325 return Ordered ? OMP_ord_auto : OMP_sch_auto; 3326 case OMPC_SCHEDULE_unknown: 3327 assert(!Chunked && "chunk was specified but schedule kind not known"); 3328 return Ordered ? OMP_ord_static : OMP_sch_static; 3329 } 3330 llvm_unreachable("Unexpected runtime schedule"); 3331 } 3332 3333 /// Map the OpenMP distribute schedule to the runtime enumeration. 3334 static OpenMPSchedType 3335 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) { 3336 // only static is allowed for dist_schedule 3337 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static; 3338 } 3339 3340 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, 3341 bool Chunked) const { 3342 OpenMPSchedType Schedule = 3343 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false); 3344 return Schedule == OMP_sch_static; 3345 } 3346 3347 bool CGOpenMPRuntime::isStaticNonchunked( 3348 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const { 3349 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked); 3350 return Schedule == OMP_dist_sch_static; 3351 } 3352 3353 bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, 3354 bool Chunked) const { 3355 OpenMPSchedType Schedule = 3356 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false); 3357 return Schedule == OMP_sch_static_chunked; 3358 } 3359 3360 bool CGOpenMPRuntime::isStaticChunked( 3361 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const { 3362 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked); 3363 return Schedule == OMP_dist_sch_static_chunked; 3364 } 3365 3366 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const { 3367 OpenMPSchedType Schedule = 3368 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false); 3369 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here"); 3370 return Schedule != OMP_sch_static; 3371 } 3372 3373 static int addMonoNonMonoModifier(OpenMPSchedType Schedule, 3374 OpenMPScheduleClauseModifier M1, 3375 OpenMPScheduleClauseModifier M2) { 3376 int Modifier = 0; 3377 switch (M1) { 3378 case OMPC_SCHEDULE_MODIFIER_monotonic: 3379 Modifier = OMP_sch_modifier_monotonic; 3380 break; 3381 case OMPC_SCHEDULE_MODIFIER_nonmonotonic: 3382 Modifier = OMP_sch_modifier_nonmonotonic; 3383 break; 3384 case OMPC_SCHEDULE_MODIFIER_simd: 3385 if (Schedule == OMP_sch_static_chunked) 3386 Schedule = OMP_sch_static_balanced_chunked; 3387 break; 3388 case OMPC_SCHEDULE_MODIFIER_last: 3389 case OMPC_SCHEDULE_MODIFIER_unknown: 3390 break; 3391 } 3392 switch (M2) { 3393 case OMPC_SCHEDULE_MODIFIER_monotonic: 3394 Modifier = OMP_sch_modifier_monotonic; 3395 break; 3396 case OMPC_SCHEDULE_MODIFIER_nonmonotonic: 3397 Modifier = OMP_sch_modifier_nonmonotonic; 3398 break; 3399 case OMPC_SCHEDULE_MODIFIER_simd: 3400 if (Schedule == OMP_sch_static_chunked) 3401 Schedule = OMP_sch_static_balanced_chunked; 3402 break; 3403 case OMPC_SCHEDULE_MODIFIER_last: 3404 case OMPC_SCHEDULE_MODIFIER_unknown: 3405 break; 3406 } 3407 return Schedule | Modifier; 3408 } 3409 3410 void CGOpenMPRuntime::emitForDispatchInit( 3411 CodeGenFunction &CGF, SourceLocation Loc, 3412 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, 3413 bool Ordered, const DispatchRTInput &DispatchValues) { 3414 if (!CGF.HaveInsertPoint()) 3415 return; 3416 OpenMPSchedType Schedule = getRuntimeSchedule( 3417 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered); 3418 assert(Ordered || 3419 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && 3420 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && 3421 Schedule != OMP_sch_static_balanced_chunked)); 3422 // Call __kmpc_dispatch_init( 3423 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule, 3424 // kmp_int[32|64] lower, kmp_int[32|64] upper, 3425 // kmp_int[32|64] stride, kmp_int[32|64] chunk); 3426 3427 // If the Chunk was not specified in the clause - use default value 1. 3428 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk 3429 : CGF.Builder.getIntN(IVSize, 1); 3430 llvm::Value *Args[] = { 3431 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 3432 CGF.Builder.getInt32(addMonoNonMonoModifier( 3433 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type 3434 DispatchValues.LB, // Lower 3435 DispatchValues.UB, // Upper 3436 CGF.Builder.getIntN(IVSize, 1), // Stride 3437 Chunk // Chunk 3438 }; 3439 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args); 3440 } 3441 3442 static void emitForStaticInitCall( 3443 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId, 3444 llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule, 3445 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 3446 const CGOpenMPRuntime::StaticRTInput &Values) { 3447 if (!CGF.HaveInsertPoint()) 3448 return; 3449 3450 assert(!Values.Ordered); 3451 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || 3452 Schedule == OMP_sch_static_balanced_chunked || 3453 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || 3454 Schedule == OMP_dist_sch_static || 3455 Schedule == OMP_dist_sch_static_chunked); 3456 3457 // Call __kmpc_for_static_init( 3458 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype, 3459 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower, 3460 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride, 3461 // kmp_int[32|64] incr, kmp_int[32|64] chunk); 3462 llvm::Value *Chunk = Values.Chunk; 3463 if (Chunk == nullptr) { 3464 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static || 3465 Schedule == OMP_dist_sch_static) && 3466 "expected static non-chunked schedule"); 3467 // If the Chunk was not specified in the clause - use default value 1. 3468 Chunk = CGF.Builder.getIntN(Values.IVSize, 1); 3469 } else { 3470 assert((Schedule == OMP_sch_static_chunked || 3471 Schedule == OMP_sch_static_balanced_chunked || 3472 Schedule == OMP_ord_static_chunked || 3473 Schedule == OMP_dist_sch_static_chunked) && 3474 "expected static chunked schedule"); 3475 } 3476 llvm::Value *Args[] = { 3477 UpdateLocation, 3478 ThreadId, 3479 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1, 3480 M2)), // Schedule type 3481 Values.IL.getPointer(), // &isLastIter 3482 Values.LB.getPointer(), // &LB 3483 Values.UB.getPointer(), // &UB 3484 Values.ST.getPointer(), // &Stride 3485 CGF.Builder.getIntN(Values.IVSize, 1), // Incr 3486 Chunk // Chunk 3487 }; 3488 CGF.EmitRuntimeCall(ForStaticInitFunction, Args); 3489 } 3490 3491 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF, 3492 SourceLocation Loc, 3493 OpenMPDirectiveKind DKind, 3494 const OpenMPScheduleTy &ScheduleKind, 3495 const StaticRTInput &Values) { 3496 OpenMPSchedType ScheduleNum = getRuntimeSchedule( 3497 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered); 3498 assert(isOpenMPWorksharingDirective(DKind) && 3499 "Expected loop-based or sections-based directive."); 3500 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc, 3501 isOpenMPLoopDirective(DKind) 3502 ? OMP_IDENT_WORK_LOOP 3503 : OMP_IDENT_WORK_SECTIONS); 3504 llvm::Value *ThreadId = getThreadID(CGF, Loc); 3505 llvm::FunctionCallee StaticInitFunction = 3506 createForStaticInitFunction(Values.IVSize, Values.IVSigned); 3507 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction, 3508 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values); 3509 } 3510 3511 void CGOpenMPRuntime::emitDistributeStaticInit( 3512 CodeGenFunction &CGF, SourceLocation Loc, 3513 OpenMPDistScheduleClauseKind SchedKind, 3514 const CGOpenMPRuntime::StaticRTInput &Values) { 3515 OpenMPSchedType ScheduleNum = 3516 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr); 3517 llvm::Value *UpdatedLocation = 3518 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE); 3519 llvm::Value *ThreadId = getThreadID(CGF, Loc); 3520 llvm::FunctionCallee StaticInitFunction = 3521 createForStaticInitFunction(Values.IVSize, Values.IVSigned); 3522 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction, 3523 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown, 3524 OMPC_SCHEDULE_MODIFIER_unknown, Values); 3525 } 3526 3527 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF, 3528 SourceLocation Loc, 3529 OpenMPDirectiveKind DKind) { 3530 if (!CGF.HaveInsertPoint()) 3531 return; 3532 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid); 3533 llvm::Value *Args[] = { 3534 emitUpdateLocation(CGF, Loc, 3535 isOpenMPDistributeDirective(DKind) 3536 ? OMP_IDENT_WORK_DISTRIBUTE 3537 : isOpenMPLoopDirective(DKind) 3538 ? OMP_IDENT_WORK_LOOP 3539 : OMP_IDENT_WORK_SECTIONS), 3540 getThreadID(CGF, Loc)}; 3541 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini), 3542 Args); 3543 } 3544 3545 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF, 3546 SourceLocation Loc, 3547 unsigned IVSize, 3548 bool IVSigned) { 3549 if (!CGF.HaveInsertPoint()) 3550 return; 3551 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid); 3552 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 3553 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args); 3554 } 3555 3556 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF, 3557 SourceLocation Loc, unsigned IVSize, 3558 bool IVSigned, Address IL, 3559 Address LB, Address UB, 3560 Address ST) { 3561 // Call __kmpc_dispatch_next( 3562 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, 3563 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, 3564 // kmp_int[32|64] *p_stride); 3565 llvm::Value *Args[] = { 3566 emitUpdateLocation(CGF, Loc), 3567 getThreadID(CGF, Loc), 3568 IL.getPointer(), // &isLastIter 3569 LB.getPointer(), // &Lower 3570 UB.getPointer(), // &Upper 3571 ST.getPointer() // &Stride 3572 }; 3573 llvm::Value *Call = 3574 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args); 3575 return CGF.EmitScalarConversion( 3576 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1), 3577 CGF.getContext().BoolTy, Loc); 3578 } 3579 3580 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF, 3581 llvm::Value *NumThreads, 3582 SourceLocation Loc) { 3583 if (!CGF.HaveInsertPoint()) 3584 return; 3585 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads) 3586 llvm::Value *Args[] = { 3587 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 3588 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)}; 3589 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads), 3590 Args); 3591 } 3592 3593 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF, 3594 OpenMPProcBindClauseKind ProcBind, 3595 SourceLocation Loc) { 3596 if (!CGF.HaveInsertPoint()) 3597 return; 3598 // Constants for proc bind value accepted by the runtime. 3599 enum ProcBindTy { 3600 ProcBindFalse = 0, 3601 ProcBindTrue, 3602 ProcBindMaster, 3603 ProcBindClose, 3604 ProcBindSpread, 3605 ProcBindIntel, 3606 ProcBindDefault 3607 } RuntimeProcBind; 3608 switch (ProcBind) { 3609 case OMPC_PROC_BIND_master: 3610 RuntimeProcBind = ProcBindMaster; 3611 break; 3612 case OMPC_PROC_BIND_close: 3613 RuntimeProcBind = ProcBindClose; 3614 break; 3615 case OMPC_PROC_BIND_spread: 3616 RuntimeProcBind = ProcBindSpread; 3617 break; 3618 case OMPC_PROC_BIND_unknown: 3619 llvm_unreachable("Unsupported proc_bind value."); 3620 } 3621 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind) 3622 llvm::Value *Args[] = { 3623 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 3624 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)}; 3625 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args); 3626 } 3627 3628 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>, 3629 SourceLocation Loc) { 3630 if (!CGF.HaveInsertPoint()) 3631 return; 3632 // Build call void __kmpc_flush(ident_t *loc) 3633 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush), 3634 emitUpdateLocation(CGF, Loc)); 3635 } 3636 3637 namespace { 3638 /// Indexes of fields for type kmp_task_t. 3639 enum KmpTaskTFields { 3640 /// List of shared variables. 3641 KmpTaskTShareds, 3642 /// Task routine. 3643 KmpTaskTRoutine, 3644 /// Partition id for the untied tasks. 3645 KmpTaskTPartId, 3646 /// Function with call of destructors for private variables. 3647 Data1, 3648 /// Task priority. 3649 Data2, 3650 /// (Taskloops only) Lower bound. 3651 KmpTaskTLowerBound, 3652 /// (Taskloops only) Upper bound. 3653 KmpTaskTUpperBound, 3654 /// (Taskloops only) Stride. 3655 KmpTaskTStride, 3656 /// (Taskloops only) Is last iteration flag. 3657 KmpTaskTLastIter, 3658 /// (Taskloops only) Reduction data. 3659 KmpTaskTReductions, 3660 }; 3661 } // anonymous namespace 3662 3663 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const { 3664 return OffloadEntriesTargetRegion.empty() && 3665 OffloadEntriesDeviceGlobalVar.empty(); 3666 } 3667 3668 /// Initialize target region entry. 3669 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3670 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 3671 StringRef ParentName, unsigned LineNum, 3672 unsigned Order) { 3673 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is " 3674 "only required for the device " 3675 "code generation."); 3676 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = 3677 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr, 3678 OMPTargetRegionEntryTargetRegion); 3679 ++OffloadingEntriesNum; 3680 } 3681 3682 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3683 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 3684 StringRef ParentName, unsigned LineNum, 3685 llvm::Constant *Addr, llvm::Constant *ID, 3686 OMPTargetRegionEntryKind Flags) { 3687 // If we are emitting code for a target, the entry is already initialized, 3688 // only has to be registered. 3689 if (CGM.getLangOpts().OpenMPIsDevice) { 3690 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) { 3691 unsigned DiagID = CGM.getDiags().getCustomDiagID( 3692 DiagnosticsEngine::Error, 3693 "Unable to find target region on line '%0' in the device code."); 3694 CGM.getDiags().Report(DiagID) << LineNum; 3695 return; 3696 } 3697 auto &Entry = 3698 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum]; 3699 assert(Entry.isValid() && "Entry not initialized!"); 3700 Entry.setAddress(Addr); 3701 Entry.setID(ID); 3702 Entry.setFlags(Flags); 3703 } else { 3704 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags); 3705 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry; 3706 ++OffloadingEntriesNum; 3707 } 3708 } 3709 3710 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo( 3711 unsigned DeviceID, unsigned FileID, StringRef ParentName, 3712 unsigned LineNum) const { 3713 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID); 3714 if (PerDevice == OffloadEntriesTargetRegion.end()) 3715 return false; 3716 auto PerFile = PerDevice->second.find(FileID); 3717 if (PerFile == PerDevice->second.end()) 3718 return false; 3719 auto PerParentName = PerFile->second.find(ParentName); 3720 if (PerParentName == PerFile->second.end()) 3721 return false; 3722 auto PerLine = PerParentName->second.find(LineNum); 3723 if (PerLine == PerParentName->second.end()) 3724 return false; 3725 // Fail if this entry is already registered. 3726 if (PerLine->second.getAddress() || PerLine->second.getID()) 3727 return false; 3728 return true; 3729 } 3730 3731 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo( 3732 const OffloadTargetRegionEntryInfoActTy &Action) { 3733 // Scan all target region entries and perform the provided action. 3734 for (const auto &D : OffloadEntriesTargetRegion) 3735 for (const auto &F : D.second) 3736 for (const auto &P : F.second) 3737 for (const auto &L : P.second) 3738 Action(D.first, F.first, P.first(), L.first, L.second); 3739 } 3740 3741 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3742 initializeDeviceGlobalVarEntryInfo(StringRef Name, 3743 OMPTargetGlobalVarEntryKind Flags, 3744 unsigned Order) { 3745 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is " 3746 "only required for the device " 3747 "code generation."); 3748 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags); 3749 ++OffloadingEntriesNum; 3750 } 3751 3752 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3753 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr, 3754 CharUnits VarSize, 3755 OMPTargetGlobalVarEntryKind Flags, 3756 llvm::GlobalValue::LinkageTypes Linkage) { 3757 if (CGM.getLangOpts().OpenMPIsDevice) { 3758 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName]; 3759 assert(Entry.isValid() && Entry.getFlags() == Flags && 3760 "Entry not initialized!"); 3761 assert((!Entry.getAddress() || Entry.getAddress() == Addr) && 3762 "Resetting with the new address."); 3763 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) { 3764 if (Entry.getVarSize().isZero()) { 3765 Entry.setVarSize(VarSize); 3766 Entry.setLinkage(Linkage); 3767 } 3768 return; 3769 } 3770 Entry.setVarSize(VarSize); 3771 Entry.setLinkage(Linkage); 3772 Entry.setAddress(Addr); 3773 } else { 3774 if (hasDeviceGlobalVarEntryInfo(VarName)) { 3775 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName]; 3776 assert(Entry.isValid() && Entry.getFlags() == Flags && 3777 "Entry not initialized!"); 3778 assert((!Entry.getAddress() || Entry.getAddress() == Addr) && 3779 "Resetting with the new address."); 3780 if (Entry.getVarSize().isZero()) { 3781 Entry.setVarSize(VarSize); 3782 Entry.setLinkage(Linkage); 3783 } 3784 return; 3785 } 3786 OffloadEntriesDeviceGlobalVar.try_emplace( 3787 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage); 3788 ++OffloadingEntriesNum; 3789 } 3790 } 3791 3792 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3793 actOnDeviceGlobalVarEntriesInfo( 3794 const OffloadDeviceGlobalVarEntryInfoActTy &Action) { 3795 // Scan all target region entries and perform the provided action. 3796 for (const auto &E : OffloadEntriesDeviceGlobalVar) 3797 Action(E.getKey(), E.getValue()); 3798 } 3799 3800 llvm::Function * 3801 CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() { 3802 // If we don't have entries or if we are emitting code for the device, we 3803 // don't need to do anything. 3804 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty()) 3805 return nullptr; 3806 3807 llvm::Module &M = CGM.getModule(); 3808 ASTContext &C = CGM.getContext(); 3809 3810 // Get list of devices we care about 3811 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples; 3812 3813 // We should be creating an offloading descriptor only if there are devices 3814 // specified. 3815 assert(!Devices.empty() && "No OpenMP offloading devices??"); 3816 3817 // Create the external variables that will point to the begin and end of the 3818 // host entries section. These will be defined by the linker. 3819 llvm::Type *OffloadEntryTy = 3820 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()); 3821 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"}); 3822 auto *HostEntriesBegin = new llvm::GlobalVariable( 3823 M, OffloadEntryTy, /*isConstant=*/true, 3824 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr, 3825 EntriesBeginName); 3826 std::string EntriesEndName = getName({"omp_offloading", "entries_end"}); 3827 auto *HostEntriesEnd = 3828 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true, 3829 llvm::GlobalValue::ExternalLinkage, 3830 /*Initializer=*/nullptr, EntriesEndName); 3831 3832 // Create all device images 3833 auto *DeviceImageTy = cast<llvm::StructType>( 3834 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy())); 3835 ConstantInitBuilder DeviceImagesBuilder(CGM); 3836 ConstantArrayBuilder DeviceImagesEntries = 3837 DeviceImagesBuilder.beginArray(DeviceImageTy); 3838 3839 for (const llvm::Triple &Device : Devices) { 3840 StringRef T = Device.getTriple(); 3841 std::string BeginName = getName({"omp_offloading", "img_start", ""}); 3842 auto *ImgBegin = new llvm::GlobalVariable( 3843 M, CGM.Int8Ty, /*isConstant=*/true, 3844 llvm::GlobalValue::ExternalWeakLinkage, 3845 /*Initializer=*/nullptr, Twine(BeginName).concat(T)); 3846 std::string EndName = getName({"omp_offloading", "img_end", ""}); 3847 auto *ImgEnd = new llvm::GlobalVariable( 3848 M, CGM.Int8Ty, /*isConstant=*/true, 3849 llvm::GlobalValue::ExternalWeakLinkage, 3850 /*Initializer=*/nullptr, Twine(EndName).concat(T)); 3851 3852 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin, 3853 HostEntriesEnd}; 3854 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data, 3855 DeviceImagesEntries); 3856 } 3857 3858 // Create device images global array. 3859 std::string ImagesName = getName({"omp_offloading", "device_images"}); 3860 llvm::GlobalVariable *DeviceImages = 3861 DeviceImagesEntries.finishAndCreateGlobal(ImagesName, 3862 CGM.getPointerAlign(), 3863 /*isConstant=*/true); 3864 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3865 3866 // This is a Zero array to be used in the creation of the constant expressions 3867 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty), 3868 llvm::Constant::getNullValue(CGM.Int32Ty)}; 3869 3870 // Create the target region descriptor. 3871 llvm::Constant *Data[] = { 3872 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()), 3873 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(), 3874 DeviceImages, Index), 3875 HostEntriesBegin, HostEntriesEnd}; 3876 std::string Descriptor = getName({"omp_offloading", "descriptor"}); 3877 llvm::GlobalVariable *Desc = createGlobalStruct( 3878 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor); 3879 3880 // Emit code to register or unregister the descriptor at execution 3881 // startup or closing, respectively. 3882 3883 llvm::Function *UnRegFn; 3884 { 3885 FunctionArgList Args; 3886 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other); 3887 Args.push_back(&DummyPtr); 3888 3889 CodeGenFunction CGF(CGM); 3890 // Disable debug info for global (de-)initializer because they are not part 3891 // of some particular construct. 3892 CGF.disableDebugInfo(); 3893 const auto &FI = 3894 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 3895 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 3896 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"}); 3897 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI); 3898 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args); 3899 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib), 3900 Desc); 3901 CGF.FinishFunction(); 3902 } 3903 llvm::Function *RegFn; 3904 { 3905 CodeGenFunction CGF(CGM); 3906 // Disable debug info for global (de-)initializer because they are not part 3907 // of some particular construct. 3908 CGF.disableDebugInfo(); 3909 const auto &FI = CGM.getTypes().arrangeNullaryFunction(); 3910 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 3911 3912 // Encode offload target triples into the registration function name. It 3913 // will serve as a comdat key for the registration/unregistration code for 3914 // this particular combination of offloading targets. 3915 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U); 3916 RegFnNameParts[0] = "omp_offloading"; 3917 RegFnNameParts[1] = "descriptor_reg"; 3918 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2), 3919 [](const llvm::Triple &T) -> const std::string& { 3920 return T.getTriple(); 3921 }); 3922 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end()); 3923 std::string Descriptor = getName(RegFnNameParts); 3924 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI); 3925 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList()); 3926 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc); 3927 // Create a variable to drive the registration and unregistration of the 3928 // descriptor, so we can reuse the logic that emits Ctors and Dtors. 3929 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), 3930 SourceLocation(), nullptr, C.CharTy, 3931 ImplicitParamDecl::Other); 3932 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc); 3933 CGF.FinishFunction(); 3934 } 3935 if (CGM.supportsCOMDAT()) { 3936 // It is sufficient to call registration function only once, so create a 3937 // COMDAT group for registration/unregistration functions and associated 3938 // data. That would reduce startup time and code size. Registration 3939 // function serves as a COMDAT group key. 3940 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName()); 3941 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage); 3942 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility); 3943 RegFn->setComdat(ComdatKey); 3944 UnRegFn->setComdat(ComdatKey); 3945 DeviceImages->setComdat(ComdatKey); 3946 Desc->setComdat(ComdatKey); 3947 } 3948 return RegFn; 3949 } 3950 3951 void CGOpenMPRuntime::createOffloadEntry( 3952 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags, 3953 llvm::GlobalValue::LinkageTypes Linkage) { 3954 StringRef Name = Addr->getName(); 3955 llvm::Module &M = CGM.getModule(); 3956 llvm::LLVMContext &C = M.getContext(); 3957 3958 // Create constant string with the name. 3959 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name); 3960 3961 std::string StringName = getName({"omp_offloading", "entry_name"}); 3962 auto *Str = new llvm::GlobalVariable( 3963 M, StrPtrInit->getType(), /*isConstant=*/true, 3964 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName); 3965 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3966 3967 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy), 3968 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy), 3969 llvm::ConstantInt::get(CGM.SizeTy, Size), 3970 llvm::ConstantInt::get(CGM.Int32Ty, Flags), 3971 llvm::ConstantInt::get(CGM.Int32Ty, 0)}; 3972 std::string EntryName = getName({"omp_offloading", "entry", ""}); 3973 llvm::GlobalVariable *Entry = createGlobalStruct( 3974 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data, 3975 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage); 3976 3977 // The entry has to be created in the section the linker expects it to be. 3978 std::string Section = getName({"omp_offloading", "entries"}); 3979 Entry->setSection(Section); 3980 } 3981 3982 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() { 3983 // Emit the offloading entries and metadata so that the device codegen side 3984 // can easily figure out what to emit. The produced metadata looks like 3985 // this: 3986 // 3987 // !omp_offload.info = !{!1, ...} 3988 // 3989 // Right now we only generate metadata for function that contain target 3990 // regions. 3991 3992 // If we do not have entries, we don't need to do anything. 3993 if (OffloadEntriesInfoManager.empty()) 3994 return; 3995 3996 llvm::Module &M = CGM.getModule(); 3997 llvm::LLVMContext &C = M.getContext(); 3998 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16> 3999 OrderedEntries(OffloadEntriesInfoManager.size()); 4000 llvm::SmallVector<StringRef, 16> ParentFunctions( 4001 OffloadEntriesInfoManager.size()); 4002 4003 // Auxiliary methods to create metadata values and strings. 4004 auto &&GetMDInt = [this](unsigned V) { 4005 return llvm::ConstantAsMetadata::get( 4006 llvm::ConstantInt::get(CGM.Int32Ty, V)); 4007 }; 4008 4009 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); }; 4010 4011 // Create the offloading info metadata node. 4012 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info"); 4013 4014 // Create function that emits metadata for each target region entry; 4015 auto &&TargetRegionMetadataEmitter = 4016 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString]( 4017 unsigned DeviceID, unsigned FileID, StringRef ParentName, 4018 unsigned Line, 4019 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) { 4020 // Generate metadata for target regions. Each entry of this metadata 4021 // contains: 4022 // - Entry 0 -> Kind of this type of metadata (0). 4023 // - Entry 1 -> Device ID of the file where the entry was identified. 4024 // - Entry 2 -> File ID of the file where the entry was identified. 4025 // - Entry 3 -> Mangled name of the function where the entry was 4026 // identified. 4027 // - Entry 4 -> Line in the file where the entry was identified. 4028 // - Entry 5 -> Order the entry was created. 4029 // The first element of the metadata node is the kind. 4030 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID), 4031 GetMDInt(FileID), GetMDString(ParentName), 4032 GetMDInt(Line), GetMDInt(E.getOrder())}; 4033 4034 // Save this entry in the right position of the ordered entries array. 4035 OrderedEntries[E.getOrder()] = &E; 4036 ParentFunctions[E.getOrder()] = ParentName; 4037 4038 // Add metadata to the named metadata node. 4039 MD->addOperand(llvm::MDNode::get(C, Ops)); 4040 }; 4041 4042 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo( 4043 TargetRegionMetadataEmitter); 4044 4045 // Create function that emits metadata for each device global variable entry; 4046 auto &&DeviceGlobalVarMetadataEmitter = 4047 [&C, &OrderedEntries, &GetMDInt, &GetMDString, 4048 MD](StringRef MangledName, 4049 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar 4050 &E) { 4051 // Generate metadata for global variables. Each entry of this metadata 4052 // contains: 4053 // - Entry 0 -> Kind of this type of metadata (1). 4054 // - Entry 1 -> Mangled name of the variable. 4055 // - Entry 2 -> Declare target kind. 4056 // - Entry 3 -> Order the entry was created. 4057 // The first element of the metadata node is the kind. 4058 llvm::Metadata *Ops[] = { 4059 GetMDInt(E.getKind()), GetMDString(MangledName), 4060 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())}; 4061 4062 // Save this entry in the right position of the ordered entries array. 4063 OrderedEntries[E.getOrder()] = &E; 4064 4065 // Add metadata to the named metadata node. 4066 MD->addOperand(llvm::MDNode::get(C, Ops)); 4067 }; 4068 4069 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo( 4070 DeviceGlobalVarMetadataEmitter); 4071 4072 for (const auto *E : OrderedEntries) { 4073 assert(E && "All ordered entries must exist!"); 4074 if (const auto *CE = 4075 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>( 4076 E)) { 4077 if (!CE->getID() || !CE->getAddress()) { 4078 // Do not blame the entry if the parent funtion is not emitted. 4079 StringRef FnName = ParentFunctions[CE->getOrder()]; 4080 if (!CGM.GetGlobalValue(FnName)) 4081 continue; 4082 unsigned DiagID = CGM.getDiags().getCustomDiagID( 4083 DiagnosticsEngine::Error, 4084 "Offloading entry for target region is incorrect: either the " 4085 "address or the ID is invalid."); 4086 CGM.getDiags().Report(DiagID); 4087 continue; 4088 } 4089 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0, 4090 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage); 4091 } else if (const auto *CE = 4092 dyn_cast<OffloadEntriesInfoManagerTy:: 4093 OffloadEntryInfoDeviceGlobalVar>(E)) { 4094 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags = 4095 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>( 4096 CE->getFlags()); 4097 switch (Flags) { 4098 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: { 4099 if (!CE->getAddress()) { 4100 unsigned DiagID = CGM.getDiags().getCustomDiagID( 4101 DiagnosticsEngine::Error, 4102 "Offloading entry for declare target variable is incorrect: the " 4103 "address is invalid."); 4104 CGM.getDiags().Report(DiagID); 4105 continue; 4106 } 4107 // The vaiable has no definition - no need to add the entry. 4108 if (CE->getVarSize().isZero()) 4109 continue; 4110 break; 4111 } 4112 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink: 4113 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) || 4114 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) && 4115 "Declaret target link address is set."); 4116 if (CGM.getLangOpts().OpenMPIsDevice) 4117 continue; 4118 if (!CE->getAddress()) { 4119 unsigned DiagID = CGM.getDiags().getCustomDiagID( 4120 DiagnosticsEngine::Error, 4121 "Offloading entry for declare target variable is incorrect: the " 4122 "address is invalid."); 4123 CGM.getDiags().Report(DiagID); 4124 continue; 4125 } 4126 break; 4127 } 4128 createOffloadEntry(CE->getAddress(), CE->getAddress(), 4129 CE->getVarSize().getQuantity(), Flags, 4130 CE->getLinkage()); 4131 } else { 4132 llvm_unreachable("Unsupported entry kind."); 4133 } 4134 } 4135 } 4136 4137 /// Loads all the offload entries information from the host IR 4138 /// metadata. 4139 void CGOpenMPRuntime::loadOffloadInfoMetadata() { 4140 // If we are in target mode, load the metadata from the host IR. This code has 4141 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata(). 4142 4143 if (!CGM.getLangOpts().OpenMPIsDevice) 4144 return; 4145 4146 if (CGM.getLangOpts().OMPHostIRFile.empty()) 4147 return; 4148 4149 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile); 4150 if (auto EC = Buf.getError()) { 4151 CGM.getDiags().Report(diag::err_cannot_open_file) 4152 << CGM.getLangOpts().OMPHostIRFile << EC.message(); 4153 return; 4154 } 4155 4156 llvm::LLVMContext C; 4157 auto ME = expectedToErrorOrAndEmitErrors( 4158 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C)); 4159 4160 if (auto EC = ME.getError()) { 4161 unsigned DiagID = CGM.getDiags().getCustomDiagID( 4162 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'"); 4163 CGM.getDiags().Report(DiagID) 4164 << CGM.getLangOpts().OMPHostIRFile << EC.message(); 4165 return; 4166 } 4167 4168 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info"); 4169 if (!MD) 4170 return; 4171 4172 for (llvm::MDNode *MN : MD->operands()) { 4173 auto &&GetMDInt = [MN](unsigned Idx) { 4174 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx)); 4175 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue(); 4176 }; 4177 4178 auto &&GetMDString = [MN](unsigned Idx) { 4179 auto *V = cast<llvm::MDString>(MN->getOperand(Idx)); 4180 return V->getString(); 4181 }; 4182 4183 switch (GetMDInt(0)) { 4184 default: 4185 llvm_unreachable("Unexpected metadata!"); 4186 break; 4187 case OffloadEntriesInfoManagerTy::OffloadEntryInfo:: 4188 OffloadingEntryInfoTargetRegion: 4189 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo( 4190 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2), 4191 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4), 4192 /*Order=*/GetMDInt(5)); 4193 break; 4194 case OffloadEntriesInfoManagerTy::OffloadEntryInfo:: 4195 OffloadingEntryInfoDeviceGlobalVar: 4196 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo( 4197 /*MangledName=*/GetMDString(1), 4198 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>( 4199 /*Flags=*/GetMDInt(2)), 4200 /*Order=*/GetMDInt(3)); 4201 break; 4202 } 4203 } 4204 } 4205 4206 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) { 4207 if (!KmpRoutineEntryPtrTy) { 4208 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type. 4209 ASTContext &C = CGM.getContext(); 4210 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy}; 4211 FunctionProtoType::ExtProtoInfo EPI; 4212 KmpRoutineEntryPtrQTy = C.getPointerType( 4213 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI)); 4214 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy); 4215 } 4216 } 4217 4218 QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() { 4219 // Make sure the type of the entry is already created. This is the type we 4220 // have to create: 4221 // struct __tgt_offload_entry{ 4222 // void *addr; // Pointer to the offload entry info. 4223 // // (function or global) 4224 // char *name; // Name of the function or global. 4225 // size_t size; // Size of the entry info (0 if it a function). 4226 // int32_t flags; // Flags associated with the entry, e.g. 'link'. 4227 // int32_t reserved; // Reserved, to use by the runtime library. 4228 // }; 4229 if (TgtOffloadEntryQTy.isNull()) { 4230 ASTContext &C = CGM.getContext(); 4231 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry"); 4232 RD->startDefinition(); 4233 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4234 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy)); 4235 addFieldToRecordDecl(C, RD, C.getSizeType()); 4236 addFieldToRecordDecl( 4237 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true)); 4238 addFieldToRecordDecl( 4239 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true)); 4240 RD->completeDefinition(); 4241 RD->addAttr(PackedAttr::CreateImplicit(C)); 4242 TgtOffloadEntryQTy = C.getRecordType(RD); 4243 } 4244 return TgtOffloadEntryQTy; 4245 } 4246 4247 QualType CGOpenMPRuntime::getTgtDeviceImageQTy() { 4248 // These are the types we need to build: 4249 // struct __tgt_device_image{ 4250 // void *ImageStart; // Pointer to the target code start. 4251 // void *ImageEnd; // Pointer to the target code end. 4252 // // We also add the host entries to the device image, as it may be useful 4253 // // for the target runtime to have access to that information. 4254 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all 4255 // // the entries. 4256 // __tgt_offload_entry *EntriesEnd; // End of the table with all the 4257 // // entries (non inclusive). 4258 // }; 4259 if (TgtDeviceImageQTy.isNull()) { 4260 ASTContext &C = CGM.getContext(); 4261 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image"); 4262 RD->startDefinition(); 4263 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4264 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4265 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy())); 4266 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy())); 4267 RD->completeDefinition(); 4268 TgtDeviceImageQTy = C.getRecordType(RD); 4269 } 4270 return TgtDeviceImageQTy; 4271 } 4272 4273 QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() { 4274 // struct __tgt_bin_desc{ 4275 // int32_t NumDevices; // Number of devices supported. 4276 // __tgt_device_image *DeviceImages; // Arrays of device images 4277 // // (one per device). 4278 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the 4279 // // entries. 4280 // __tgt_offload_entry *EntriesEnd; // End of the table with all the 4281 // // entries (non inclusive). 4282 // }; 4283 if (TgtBinaryDescriptorQTy.isNull()) { 4284 ASTContext &C = CGM.getContext(); 4285 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc"); 4286 RD->startDefinition(); 4287 addFieldToRecordDecl( 4288 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true)); 4289 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy())); 4290 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy())); 4291 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy())); 4292 RD->completeDefinition(); 4293 TgtBinaryDescriptorQTy = C.getRecordType(RD); 4294 } 4295 return TgtBinaryDescriptorQTy; 4296 } 4297 4298 namespace { 4299 struct PrivateHelpersTy { 4300 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy, 4301 const VarDecl *PrivateElemInit) 4302 : Original(Original), PrivateCopy(PrivateCopy), 4303 PrivateElemInit(PrivateElemInit) {} 4304 const VarDecl *Original; 4305 const VarDecl *PrivateCopy; 4306 const VarDecl *PrivateElemInit; 4307 }; 4308 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy; 4309 } // anonymous namespace 4310 4311 static RecordDecl * 4312 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) { 4313 if (!Privates.empty()) { 4314 ASTContext &C = CGM.getContext(); 4315 // Build struct .kmp_privates_t. { 4316 // /* private vars */ 4317 // }; 4318 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t"); 4319 RD->startDefinition(); 4320 for (const auto &Pair : Privates) { 4321 const VarDecl *VD = Pair.second.Original; 4322 QualType Type = VD->getType().getNonReferenceType(); 4323 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type); 4324 if (VD->hasAttrs()) { 4325 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()), 4326 E(VD->getAttrs().end()); 4327 I != E; ++I) 4328 FD->addAttr(*I); 4329 } 4330 } 4331 RD->completeDefinition(); 4332 return RD; 4333 } 4334 return nullptr; 4335 } 4336 4337 static RecordDecl * 4338 createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind, 4339 QualType KmpInt32Ty, 4340 QualType KmpRoutineEntryPointerQTy) { 4341 ASTContext &C = CGM.getContext(); 4342 // Build struct kmp_task_t { 4343 // void * shareds; 4344 // kmp_routine_entry_t routine; 4345 // kmp_int32 part_id; 4346 // kmp_cmplrdata_t data1; 4347 // kmp_cmplrdata_t data2; 4348 // For taskloops additional fields: 4349 // kmp_uint64 lb; 4350 // kmp_uint64 ub; 4351 // kmp_int64 st; 4352 // kmp_int32 liter; 4353 // void * reductions; 4354 // }; 4355 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union); 4356 UD->startDefinition(); 4357 addFieldToRecordDecl(C, UD, KmpInt32Ty); 4358 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy); 4359 UD->completeDefinition(); 4360 QualType KmpCmplrdataTy = C.getRecordType(UD); 4361 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t"); 4362 RD->startDefinition(); 4363 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4364 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy); 4365 addFieldToRecordDecl(C, RD, KmpInt32Ty); 4366 addFieldToRecordDecl(C, RD, KmpCmplrdataTy); 4367 addFieldToRecordDecl(C, RD, KmpCmplrdataTy); 4368 if (isOpenMPTaskLoopDirective(Kind)) { 4369 QualType KmpUInt64Ty = 4370 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4371 QualType KmpInt64Ty = 4372 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4373 addFieldToRecordDecl(C, RD, KmpUInt64Ty); 4374 addFieldToRecordDecl(C, RD, KmpUInt64Ty); 4375 addFieldToRecordDecl(C, RD, KmpInt64Ty); 4376 addFieldToRecordDecl(C, RD, KmpInt32Ty); 4377 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4378 } 4379 RD->completeDefinition(); 4380 return RD; 4381 } 4382 4383 static RecordDecl * 4384 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy, 4385 ArrayRef<PrivateDataTy> Privates) { 4386 ASTContext &C = CGM.getContext(); 4387 // Build struct kmp_task_t_with_privates { 4388 // kmp_task_t task_data; 4389 // .kmp_privates_t. privates; 4390 // }; 4391 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates"); 4392 RD->startDefinition(); 4393 addFieldToRecordDecl(C, RD, KmpTaskTQTy); 4394 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) 4395 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD)); 4396 RD->completeDefinition(); 4397 return RD; 4398 } 4399 4400 /// Emit a proxy function which accepts kmp_task_t as the second 4401 /// argument. 4402 /// \code 4403 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 4404 /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt, 4405 /// For taskloops: 4406 /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter, 4407 /// tt->reductions, tt->shareds); 4408 /// return 0; 4409 /// } 4410 /// \endcode 4411 static llvm::Function * 4412 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc, 4413 OpenMPDirectiveKind Kind, QualType KmpInt32Ty, 4414 QualType KmpTaskTWithPrivatesPtrQTy, 4415 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy, 4416 QualType SharedsPtrTy, llvm::Function *TaskFunction, 4417 llvm::Value *TaskPrivatesMap) { 4418 ASTContext &C = CGM.getContext(); 4419 FunctionArgList Args; 4420 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty, 4421 ImplicitParamDecl::Other); 4422 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4423 KmpTaskTWithPrivatesPtrQTy.withRestrict(), 4424 ImplicitParamDecl::Other); 4425 Args.push_back(&GtidArg); 4426 Args.push_back(&TaskTypeArg); 4427 const auto &TaskEntryFnInfo = 4428 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args); 4429 llvm::FunctionType *TaskEntryTy = 4430 CGM.getTypes().GetFunctionType(TaskEntryFnInfo); 4431 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""}); 4432 auto *TaskEntry = llvm::Function::Create( 4433 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); 4434 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo); 4435 TaskEntry->setDoesNotRecurse(); 4436 CodeGenFunction CGF(CGM); 4437 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args, 4438 Loc, Loc); 4439 4440 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map, 4441 // tt, 4442 // For taskloops: 4443 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter, 4444 // tt->task_data.shareds); 4445 llvm::Value *GtidParam = CGF.EmitLoadOfScalar( 4446 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc); 4447 LValue TDBase = CGF.EmitLoadOfPointerLValue( 4448 CGF.GetAddrOfLocalVar(&TaskTypeArg), 4449 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); 4450 const auto *KmpTaskTWithPrivatesQTyRD = 4451 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl()); 4452 LValue Base = 4453 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); 4454 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl()); 4455 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId); 4456 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI); 4457 llvm::Value *PartidParam = PartIdLVal.getPointer(); 4458 4459 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds); 4460 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI); 4461 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4462 CGF.EmitLoadOfScalar(SharedsLVal, Loc), 4463 CGF.ConvertTypeForMem(SharedsPtrTy)); 4464 4465 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1); 4466 llvm::Value *PrivatesParam; 4467 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) { 4468 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI); 4469 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4470 PrivatesLVal.getPointer(), CGF.VoidPtrTy); 4471 } else { 4472 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 4473 } 4474 4475 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam, 4476 TaskPrivatesMap, 4477 CGF.Builder 4478 .CreatePointerBitCastOrAddrSpaceCast( 4479 TDBase.getAddress(), CGF.VoidPtrTy) 4480 .getPointer()}; 4481 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs), 4482 std::end(CommonArgs)); 4483 if (isOpenMPTaskLoopDirective(Kind)) { 4484 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound); 4485 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI); 4486 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc); 4487 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound); 4488 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI); 4489 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc); 4490 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride); 4491 LValue StLVal = CGF.EmitLValueForField(Base, *StFI); 4492 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc); 4493 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter); 4494 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI); 4495 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc); 4496 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions); 4497 LValue RLVal = CGF.EmitLValueForField(Base, *RFI); 4498 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc); 4499 CallArgs.push_back(LBParam); 4500 CallArgs.push_back(UBParam); 4501 CallArgs.push_back(StParam); 4502 CallArgs.push_back(LIParam); 4503 CallArgs.push_back(RParam); 4504 } 4505 CallArgs.push_back(SharedsParam); 4506 4507 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction, 4508 CallArgs); 4509 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)), 4510 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty)); 4511 CGF.FinishFunction(); 4512 return TaskEntry; 4513 } 4514 4515 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM, 4516 SourceLocation Loc, 4517 QualType KmpInt32Ty, 4518 QualType KmpTaskTWithPrivatesPtrQTy, 4519 QualType KmpTaskTWithPrivatesQTy) { 4520 ASTContext &C = CGM.getContext(); 4521 FunctionArgList Args; 4522 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty, 4523 ImplicitParamDecl::Other); 4524 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4525 KmpTaskTWithPrivatesPtrQTy.withRestrict(), 4526 ImplicitParamDecl::Other); 4527 Args.push_back(&GtidArg); 4528 Args.push_back(&TaskTypeArg); 4529 const auto &DestructorFnInfo = 4530 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args); 4531 llvm::FunctionType *DestructorFnTy = 4532 CGM.getTypes().GetFunctionType(DestructorFnInfo); 4533 std::string Name = 4534 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""}); 4535 auto *DestructorFn = 4536 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage, 4537 Name, &CGM.getModule()); 4538 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn, 4539 DestructorFnInfo); 4540 DestructorFn->setDoesNotRecurse(); 4541 CodeGenFunction CGF(CGM); 4542 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo, 4543 Args, Loc, Loc); 4544 4545 LValue Base = CGF.EmitLoadOfPointerLValue( 4546 CGF.GetAddrOfLocalVar(&TaskTypeArg), 4547 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); 4548 const auto *KmpTaskTWithPrivatesQTyRD = 4549 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl()); 4550 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); 4551 Base = CGF.EmitLValueForField(Base, *FI); 4552 for (const auto *Field : 4553 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) { 4554 if (QualType::DestructionKind DtorKind = 4555 Field->getType().isDestructedType()) { 4556 LValue FieldLValue = CGF.EmitLValueForField(Base, Field); 4557 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType()); 4558 } 4559 } 4560 CGF.FinishFunction(); 4561 return DestructorFn; 4562 } 4563 4564 /// Emit a privates mapping function for correct handling of private and 4565 /// firstprivate variables. 4566 /// \code 4567 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1> 4568 /// **noalias priv1,..., <tyn> **noalias privn) { 4569 /// *priv1 = &.privates.priv1; 4570 /// ...; 4571 /// *privn = &.privates.privn; 4572 /// } 4573 /// \endcode 4574 static llvm::Value * 4575 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc, 4576 ArrayRef<const Expr *> PrivateVars, 4577 ArrayRef<const Expr *> FirstprivateVars, 4578 ArrayRef<const Expr *> LastprivateVars, 4579 QualType PrivatesQTy, 4580 ArrayRef<PrivateDataTy> Privates) { 4581 ASTContext &C = CGM.getContext(); 4582 FunctionArgList Args; 4583 ImplicitParamDecl TaskPrivatesArg( 4584 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4585 C.getPointerType(PrivatesQTy).withConst().withRestrict(), 4586 ImplicitParamDecl::Other); 4587 Args.push_back(&TaskPrivatesArg); 4588 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos; 4589 unsigned Counter = 1; 4590 for (const Expr *E : PrivateVars) { 4591 Args.push_back(ImplicitParamDecl::Create( 4592 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4593 C.getPointerType(C.getPointerType(E->getType())) 4594 .withConst() 4595 .withRestrict(), 4596 ImplicitParamDecl::Other)); 4597 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4598 PrivateVarsPos[VD] = Counter; 4599 ++Counter; 4600 } 4601 for (const Expr *E : FirstprivateVars) { 4602 Args.push_back(ImplicitParamDecl::Create( 4603 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4604 C.getPointerType(C.getPointerType(E->getType())) 4605 .withConst() 4606 .withRestrict(), 4607 ImplicitParamDecl::Other)); 4608 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4609 PrivateVarsPos[VD] = Counter; 4610 ++Counter; 4611 } 4612 for (const Expr *E : LastprivateVars) { 4613 Args.push_back(ImplicitParamDecl::Create( 4614 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4615 C.getPointerType(C.getPointerType(E->getType())) 4616 .withConst() 4617 .withRestrict(), 4618 ImplicitParamDecl::Other)); 4619 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4620 PrivateVarsPos[VD] = Counter; 4621 ++Counter; 4622 } 4623 const auto &TaskPrivatesMapFnInfo = 4624 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 4625 llvm::FunctionType *TaskPrivatesMapTy = 4626 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo); 4627 std::string Name = 4628 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""}); 4629 auto *TaskPrivatesMap = llvm::Function::Create( 4630 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name, 4631 &CGM.getModule()); 4632 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap, 4633 TaskPrivatesMapFnInfo); 4634 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline); 4635 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone); 4636 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline); 4637 CodeGenFunction CGF(CGM); 4638 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap, 4639 TaskPrivatesMapFnInfo, Args, Loc, Loc); 4640 4641 // *privi = &.privates.privi; 4642 LValue Base = CGF.EmitLoadOfPointerLValue( 4643 CGF.GetAddrOfLocalVar(&TaskPrivatesArg), 4644 TaskPrivatesArg.getType()->castAs<PointerType>()); 4645 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl()); 4646 Counter = 0; 4647 for (const FieldDecl *Field : PrivatesQTyRD->fields()) { 4648 LValue FieldLVal = CGF.EmitLValueForField(Base, Field); 4649 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]]; 4650 LValue RefLVal = 4651 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType()); 4652 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue( 4653 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>()); 4654 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal); 4655 ++Counter; 4656 } 4657 CGF.FinishFunction(); 4658 return TaskPrivatesMap; 4659 } 4660 4661 static bool stable_sort_comparator(const PrivateDataTy P1, 4662 const PrivateDataTy P2) { 4663 return P1.first > P2.first; 4664 } 4665 4666 /// Emit initialization for private variables in task-based directives. 4667 static void emitPrivatesInit(CodeGenFunction &CGF, 4668 const OMPExecutableDirective &D, 4669 Address KmpTaskSharedsPtr, LValue TDBase, 4670 const RecordDecl *KmpTaskTWithPrivatesQTyRD, 4671 QualType SharedsTy, QualType SharedsPtrTy, 4672 const OMPTaskDataTy &Data, 4673 ArrayRef<PrivateDataTy> Privates, bool ForDup) { 4674 ASTContext &C = CGF.getContext(); 4675 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); 4676 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI); 4677 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind()) 4678 ? OMPD_taskloop 4679 : OMPD_task; 4680 const CapturedStmt &CS = *D.getCapturedStmt(Kind); 4681 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS); 4682 LValue SrcBase; 4683 bool IsTargetTask = 4684 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) || 4685 isOpenMPTargetExecutionDirective(D.getDirectiveKind()); 4686 // For target-based directives skip 3 firstprivate arrays BasePointersArray, 4687 // PointersArray and SizesArray. The original variables for these arrays are 4688 // not captured and we get their addresses explicitly. 4689 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) || 4690 (IsTargetTask && KmpTaskSharedsPtr.isValid())) { 4691 SrcBase = CGF.MakeAddrLValue( 4692 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4693 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)), 4694 SharedsTy); 4695 } 4696 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin(); 4697 for (const PrivateDataTy &Pair : Privates) { 4698 const VarDecl *VD = Pair.second.PrivateCopy; 4699 const Expr *Init = VD->getAnyInitializer(); 4700 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) && 4701 !CGF.isTrivialInitializer(Init)))) { 4702 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI); 4703 if (const VarDecl *Elem = Pair.second.PrivateElemInit) { 4704 const VarDecl *OriginalVD = Pair.second.Original; 4705 // Check if the variable is the target-based BasePointersArray, 4706 // PointersArray or SizesArray. 4707 LValue SharedRefLValue; 4708 QualType Type = OriginalVD->getType(); 4709 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD); 4710 if (IsTargetTask && !SharedField) { 4711 assert(isa<ImplicitParamDecl>(OriginalVD) && 4712 isa<CapturedDecl>(OriginalVD->getDeclContext()) && 4713 cast<CapturedDecl>(OriginalVD->getDeclContext()) 4714 ->getNumParams() == 0 && 4715 isa<TranslationUnitDecl>( 4716 cast<CapturedDecl>(OriginalVD->getDeclContext()) 4717 ->getDeclContext()) && 4718 "Expected artificial target data variable."); 4719 SharedRefLValue = 4720 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type); 4721 } else { 4722 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField); 4723 SharedRefLValue = CGF.MakeAddrLValue( 4724 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)), 4725 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl), 4726 SharedRefLValue.getTBAAInfo()); 4727 } 4728 if (Type->isArrayType()) { 4729 // Initialize firstprivate array. 4730 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) { 4731 // Perform simple memcpy. 4732 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type); 4733 } else { 4734 // Initialize firstprivate array using element-by-element 4735 // initialization. 4736 CGF.EmitOMPAggregateAssign( 4737 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type, 4738 [&CGF, Elem, Init, &CapturesInfo](Address DestElement, 4739 Address SrcElement) { 4740 // Clean up any temporaries needed by the initialization. 4741 CodeGenFunction::OMPPrivateScope InitScope(CGF); 4742 InitScope.addPrivate( 4743 Elem, [SrcElement]() -> Address { return SrcElement; }); 4744 (void)InitScope.Privatize(); 4745 // Emit initialization for single element. 4746 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII( 4747 CGF, &CapturesInfo); 4748 CGF.EmitAnyExprToMem(Init, DestElement, 4749 Init->getType().getQualifiers(), 4750 /*IsInitializer=*/false); 4751 }); 4752 } 4753 } else { 4754 CodeGenFunction::OMPPrivateScope InitScope(CGF); 4755 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address { 4756 return SharedRefLValue.getAddress(); 4757 }); 4758 (void)InitScope.Privatize(); 4759 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo); 4760 CGF.EmitExprAsInit(Init, VD, PrivateLValue, 4761 /*capturedByInit=*/false); 4762 } 4763 } else { 4764 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false); 4765 } 4766 } 4767 ++FI; 4768 } 4769 } 4770 4771 /// Check if duplication function is required for taskloops. 4772 static bool checkInitIsRequired(CodeGenFunction &CGF, 4773 ArrayRef<PrivateDataTy> Privates) { 4774 bool InitRequired = false; 4775 for (const PrivateDataTy &Pair : Privates) { 4776 const VarDecl *VD = Pair.second.PrivateCopy; 4777 const Expr *Init = VD->getAnyInitializer(); 4778 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) && 4779 !CGF.isTrivialInitializer(Init)); 4780 if (InitRequired) 4781 break; 4782 } 4783 return InitRequired; 4784 } 4785 4786 4787 /// Emit task_dup function (for initialization of 4788 /// private/firstprivate/lastprivate vars and last_iter flag) 4789 /// \code 4790 /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int 4791 /// lastpriv) { 4792 /// // setup lastprivate flag 4793 /// task_dst->last = lastpriv; 4794 /// // could be constructor calls here... 4795 /// } 4796 /// \endcode 4797 static llvm::Value * 4798 emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc, 4799 const OMPExecutableDirective &D, 4800 QualType KmpTaskTWithPrivatesPtrQTy, 4801 const RecordDecl *KmpTaskTWithPrivatesQTyRD, 4802 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy, 4803 QualType SharedsPtrTy, const OMPTaskDataTy &Data, 4804 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) { 4805 ASTContext &C = CGM.getContext(); 4806 FunctionArgList Args; 4807 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4808 KmpTaskTWithPrivatesPtrQTy, 4809 ImplicitParamDecl::Other); 4810 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4811 KmpTaskTWithPrivatesPtrQTy, 4812 ImplicitParamDecl::Other); 4813 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy, 4814 ImplicitParamDecl::Other); 4815 Args.push_back(&DstArg); 4816 Args.push_back(&SrcArg); 4817 Args.push_back(&LastprivArg); 4818 const auto &TaskDupFnInfo = 4819 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 4820 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo); 4821 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""}); 4822 auto *TaskDup = llvm::Function::Create( 4823 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); 4824 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo); 4825 TaskDup->setDoesNotRecurse(); 4826 CodeGenFunction CGF(CGM); 4827 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc, 4828 Loc); 4829 4830 LValue TDBase = CGF.EmitLoadOfPointerLValue( 4831 CGF.GetAddrOfLocalVar(&DstArg), 4832 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); 4833 // task_dst->liter = lastpriv; 4834 if (WithLastIter) { 4835 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter); 4836 LValue Base = CGF.EmitLValueForField( 4837 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); 4838 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI); 4839 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar( 4840 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc); 4841 CGF.EmitStoreOfScalar(Lastpriv, LILVal); 4842 } 4843 4844 // Emit initial values for private copies (if any). 4845 assert(!Privates.empty()); 4846 Address KmpTaskSharedsPtr = Address::invalid(); 4847 if (!Data.FirstprivateVars.empty()) { 4848 LValue TDBase = CGF.EmitLoadOfPointerLValue( 4849 CGF.GetAddrOfLocalVar(&SrcArg), 4850 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); 4851 LValue Base = CGF.EmitLValueForField( 4852 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); 4853 KmpTaskSharedsPtr = Address( 4854 CGF.EmitLoadOfScalar(CGF.EmitLValueForField( 4855 Base, *std::next(KmpTaskTQTyRD->field_begin(), 4856 KmpTaskTShareds)), 4857 Loc), 4858 CGF.getNaturalTypeAlignment(SharedsTy)); 4859 } 4860 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD, 4861 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true); 4862 CGF.FinishFunction(); 4863 return TaskDup; 4864 } 4865 4866 /// Checks if destructor function is required to be generated. 4867 /// \return true if cleanups are required, false otherwise. 4868 static bool 4869 checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) { 4870 bool NeedsCleanup = false; 4871 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1); 4872 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl()); 4873 for (const FieldDecl *FD : PrivateRD->fields()) { 4874 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType(); 4875 if (NeedsCleanup) 4876 break; 4877 } 4878 return NeedsCleanup; 4879 } 4880 4881 CGOpenMPRuntime::TaskResultTy 4882 CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, 4883 const OMPExecutableDirective &D, 4884 llvm::Function *TaskFunction, QualType SharedsTy, 4885 Address Shareds, const OMPTaskDataTy &Data) { 4886 ASTContext &C = CGM.getContext(); 4887 llvm::SmallVector<PrivateDataTy, 4> Privates; 4888 // Aggregate privates and sort them by the alignment. 4889 auto I = Data.PrivateCopies.begin(); 4890 for (const Expr *E : Data.PrivateVars) { 4891 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4892 Privates.emplace_back( 4893 C.getDeclAlign(VD), 4894 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), 4895 /*PrivateElemInit=*/nullptr)); 4896 ++I; 4897 } 4898 I = Data.FirstprivateCopies.begin(); 4899 auto IElemInitRef = Data.FirstprivateInits.begin(); 4900 for (const Expr *E : Data.FirstprivateVars) { 4901 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4902 Privates.emplace_back( 4903 C.getDeclAlign(VD), 4904 PrivateHelpersTy( 4905 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), 4906 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))); 4907 ++I; 4908 ++IElemInitRef; 4909 } 4910 I = Data.LastprivateCopies.begin(); 4911 for (const Expr *E : Data.LastprivateVars) { 4912 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4913 Privates.emplace_back( 4914 C.getDeclAlign(VD), 4915 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), 4916 /*PrivateElemInit=*/nullptr)); 4917 ++I; 4918 } 4919 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator); 4920 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 4921 // Build type kmp_routine_entry_t (if not built yet). 4922 emitKmpRoutineEntryT(KmpInt32Ty); 4923 // Build type kmp_task_t (if not built yet). 4924 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) { 4925 if (SavedKmpTaskloopTQTy.isNull()) { 4926 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl( 4927 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy)); 4928 } 4929 KmpTaskTQTy = SavedKmpTaskloopTQTy; 4930 } else { 4931 assert((D.getDirectiveKind() == OMPD_task || 4932 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || 4933 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && 4934 "Expected taskloop, task or target directive"); 4935 if (SavedKmpTaskTQTy.isNull()) { 4936 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl( 4937 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy)); 4938 } 4939 KmpTaskTQTy = SavedKmpTaskTQTy; 4940 } 4941 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl()); 4942 // Build particular struct kmp_task_t for the given task. 4943 const RecordDecl *KmpTaskTWithPrivatesQTyRD = 4944 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates); 4945 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD); 4946 QualType KmpTaskTWithPrivatesPtrQTy = 4947 C.getPointerType(KmpTaskTWithPrivatesQTy); 4948 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy); 4949 llvm::Type *KmpTaskTWithPrivatesPtrTy = 4950 KmpTaskTWithPrivatesTy->getPointerTo(); 4951 llvm::Value *KmpTaskTWithPrivatesTySize = 4952 CGF.getTypeSize(KmpTaskTWithPrivatesQTy); 4953 QualType SharedsPtrTy = C.getPointerType(SharedsTy); 4954 4955 // Emit initial values for private copies (if any). 4956 llvm::Value *TaskPrivatesMap = nullptr; 4957 llvm::Type *TaskPrivatesMapTy = 4958 std::next(TaskFunction->arg_begin(), 3)->getType(); 4959 if (!Privates.empty()) { 4960 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); 4961 TaskPrivatesMap = emitTaskPrivateMappingFunction( 4962 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars, 4963 FI->getType(), Privates); 4964 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4965 TaskPrivatesMap, TaskPrivatesMapTy); 4966 } else { 4967 TaskPrivatesMap = llvm::ConstantPointerNull::get( 4968 cast<llvm::PointerType>(TaskPrivatesMapTy)); 4969 } 4970 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid, 4971 // kmp_task_t *tt); 4972 llvm::Function *TaskEntry = emitProxyTaskFunction( 4973 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, 4974 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction, 4975 TaskPrivatesMap); 4976 4977 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid, 4978 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 4979 // kmp_routine_entry_t *task_entry); 4980 // Task flags. Format is taken from 4981 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h, 4982 // description of kmp_tasking_flags struct. 4983 enum { 4984 TiedFlag = 0x1, 4985 FinalFlag = 0x2, 4986 DestructorsFlag = 0x8, 4987 PriorityFlag = 0x20 4988 }; 4989 unsigned Flags = Data.Tied ? TiedFlag : 0; 4990 bool NeedsCleanup = false; 4991 if (!Privates.empty()) { 4992 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD); 4993 if (NeedsCleanup) 4994 Flags = Flags | DestructorsFlag; 4995 } 4996 if (Data.Priority.getInt()) 4997 Flags = Flags | PriorityFlag; 4998 llvm::Value *TaskFlags = 4999 Data.Final.getPointer() 5000 ? CGF.Builder.CreateSelect(Data.Final.getPointer(), 5001 CGF.Builder.getInt32(FinalFlag), 5002 CGF.Builder.getInt32(/*C=*/0)) 5003 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0); 5004 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags)); 5005 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy)); 5006 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc), 5007 getThreadID(CGF, Loc), TaskFlags, 5008 KmpTaskTWithPrivatesTySize, SharedsSize, 5009 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5010 TaskEntry, KmpRoutineEntryPtrTy)}; 5011 llvm::Value *NewTask = CGF.EmitRuntimeCall( 5012 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs); 5013 llvm::Value *NewTaskNewTaskTTy = 5014 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5015 NewTask, KmpTaskTWithPrivatesPtrTy); 5016 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy, 5017 KmpTaskTWithPrivatesQTy); 5018 LValue TDBase = 5019 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin()); 5020 // Fill the data in the resulting kmp_task_t record. 5021 // Copy shareds if there are any. 5022 Address KmpTaskSharedsPtr = Address::invalid(); 5023 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) { 5024 KmpTaskSharedsPtr = 5025 Address(CGF.EmitLoadOfScalar( 5026 CGF.EmitLValueForField( 5027 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), 5028 KmpTaskTShareds)), 5029 Loc), 5030 CGF.getNaturalTypeAlignment(SharedsTy)); 5031 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy); 5032 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy); 5033 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap); 5034 } 5035 // Emit initial values for private copies (if any). 5036 TaskResultTy Result; 5037 if (!Privates.empty()) { 5038 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD, 5039 SharedsTy, SharedsPtrTy, Data, Privates, 5040 /*ForDup=*/false); 5041 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) && 5042 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) { 5043 Result.TaskDupFn = emitTaskDupFunction( 5044 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD, 5045 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates, 5046 /*WithLastIter=*/!Data.LastprivateVars.empty()); 5047 } 5048 } 5049 // Fields of union "kmp_cmplrdata_t" for destructors and priority. 5050 enum { Priority = 0, Destructors = 1 }; 5051 // Provide pointer to function with destructors for privates. 5052 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1); 5053 const RecordDecl *KmpCmplrdataUD = 5054 (*FI)->getType()->getAsUnionType()->getDecl(); 5055 if (NeedsCleanup) { 5056 llvm::Value *DestructorFn = emitDestructorsFunction( 5057 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, 5058 KmpTaskTWithPrivatesQTy); 5059 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI); 5060 LValue DestructorsLV = CGF.EmitLValueForField( 5061 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors)); 5062 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5063 DestructorFn, KmpRoutineEntryPtrTy), 5064 DestructorsLV); 5065 } 5066 // Set priority. 5067 if (Data.Priority.getInt()) { 5068 LValue Data2LV = CGF.EmitLValueForField( 5069 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2)); 5070 LValue PriorityLV = CGF.EmitLValueForField( 5071 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority)); 5072 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV); 5073 } 5074 Result.NewTask = NewTask; 5075 Result.TaskEntry = TaskEntry; 5076 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy; 5077 Result.TDBase = TDBase; 5078 Result.KmpTaskTQTyRD = KmpTaskTQTyRD; 5079 return Result; 5080 } 5081 5082 void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 5083 const OMPExecutableDirective &D, 5084 llvm::Function *TaskFunction, 5085 QualType SharedsTy, Address Shareds, 5086 const Expr *IfCond, 5087 const OMPTaskDataTy &Data) { 5088 if (!CGF.HaveInsertPoint()) 5089 return; 5090 5091 TaskResultTy Result = 5092 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data); 5093 llvm::Value *NewTask = Result.NewTask; 5094 llvm::Function *TaskEntry = Result.TaskEntry; 5095 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy; 5096 LValue TDBase = Result.TDBase; 5097 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD; 5098 ASTContext &C = CGM.getContext(); 5099 // Process list of dependences. 5100 Address DependenciesArray = Address::invalid(); 5101 unsigned NumDependencies = Data.Dependences.size(); 5102 if (NumDependencies) { 5103 // Dependence kind for RTL. 5104 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3, DepMutexInOutSet = 0x4 }; 5105 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags }; 5106 RecordDecl *KmpDependInfoRD; 5107 QualType FlagsTy = 5108 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false); 5109 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy); 5110 if (KmpDependInfoTy.isNull()) { 5111 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info"); 5112 KmpDependInfoRD->startDefinition(); 5113 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType()); 5114 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType()); 5115 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy); 5116 KmpDependInfoRD->completeDefinition(); 5117 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD); 5118 } else { 5119 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); 5120 } 5121 // Define type kmp_depend_info[<Dependences.size()>]; 5122 QualType KmpDependInfoArrayTy = C.getConstantArrayType( 5123 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies), 5124 ArrayType::Normal, /*IndexTypeQuals=*/0); 5125 // kmp_depend_info[<Dependences.size()>] deps; 5126 DependenciesArray = 5127 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr"); 5128 for (unsigned I = 0; I < NumDependencies; ++I) { 5129 const Expr *E = Data.Dependences[I].second; 5130 LValue Addr = CGF.EmitLValue(E); 5131 llvm::Value *Size; 5132 QualType Ty = E->getType(); 5133 if (const auto *ASE = 5134 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) { 5135 LValue UpAddrLVal = 5136 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false); 5137 llvm::Value *UpAddr = 5138 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1); 5139 llvm::Value *LowIntPtr = 5140 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy); 5141 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy); 5142 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr); 5143 } else { 5144 Size = CGF.getTypeSize(Ty); 5145 } 5146 LValue Base = CGF.MakeAddrLValue( 5147 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I), 5148 KmpDependInfoTy); 5149 // deps[i].base_addr = &<Dependences[i].second>; 5150 LValue BaseAddrLVal = CGF.EmitLValueForField( 5151 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr)); 5152 CGF.EmitStoreOfScalar( 5153 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy), 5154 BaseAddrLVal); 5155 // deps[i].len = sizeof(<Dependences[i].second>); 5156 LValue LenLVal = CGF.EmitLValueForField( 5157 Base, *std::next(KmpDependInfoRD->field_begin(), Len)); 5158 CGF.EmitStoreOfScalar(Size, LenLVal); 5159 // deps[i].flags = <Dependences[i].first>; 5160 RTLDependenceKindTy DepKind; 5161 switch (Data.Dependences[I].first) { 5162 case OMPC_DEPEND_in: 5163 DepKind = DepIn; 5164 break; 5165 // Out and InOut dependencies must use the same code. 5166 case OMPC_DEPEND_out: 5167 case OMPC_DEPEND_inout: 5168 DepKind = DepInOut; 5169 break; 5170 case OMPC_DEPEND_mutexinoutset: 5171 DepKind = DepMutexInOutSet; 5172 break; 5173 case OMPC_DEPEND_source: 5174 case OMPC_DEPEND_sink: 5175 case OMPC_DEPEND_unknown: 5176 llvm_unreachable("Unknown task dependence type"); 5177 } 5178 LValue FlagsLVal = CGF.EmitLValueForField( 5179 Base, *std::next(KmpDependInfoRD->field_begin(), Flags)); 5180 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind), 5181 FlagsLVal); 5182 } 5183 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5184 CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0), CGF.VoidPtrTy); 5185 } 5186 5187 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc() 5188 // libcall. 5189 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid, 5190 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list, 5191 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence 5192 // list is not empty 5193 llvm::Value *ThreadID = getThreadID(CGF, Loc); 5194 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc); 5195 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask }; 5196 llvm::Value *DepTaskArgs[7]; 5197 if (NumDependencies) { 5198 DepTaskArgs[0] = UpLoc; 5199 DepTaskArgs[1] = ThreadID; 5200 DepTaskArgs[2] = NewTask; 5201 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies); 5202 DepTaskArgs[4] = DependenciesArray.getPointer(); 5203 DepTaskArgs[5] = CGF.Builder.getInt32(0); 5204 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 5205 } 5206 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies, 5207 &TaskArgs, 5208 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) { 5209 if (!Data.Tied) { 5210 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId); 5211 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI); 5212 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal); 5213 } 5214 if (NumDependencies) { 5215 CGF.EmitRuntimeCall( 5216 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs); 5217 } else { 5218 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), 5219 TaskArgs); 5220 } 5221 // Check if parent region is untied and build return for untied task; 5222 if (auto *Region = 5223 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) 5224 Region->emitUntiedSwitch(CGF); 5225 }; 5226 5227 llvm::Value *DepWaitTaskArgs[6]; 5228 if (NumDependencies) { 5229 DepWaitTaskArgs[0] = UpLoc; 5230 DepWaitTaskArgs[1] = ThreadID; 5231 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies); 5232 DepWaitTaskArgs[3] = DependenciesArray.getPointer(); 5233 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0); 5234 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 5235 } 5236 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry, 5237 NumDependencies, &DepWaitTaskArgs, 5238 Loc](CodeGenFunction &CGF, PrePostActionTy &) { 5239 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 5240 CodeGenFunction::RunCleanupsScope LocalScope(CGF); 5241 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid, 5242 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 5243 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info 5244 // is specified. 5245 if (NumDependencies) 5246 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps), 5247 DepWaitTaskArgs); 5248 // Call proxy_task_entry(gtid, new_task); 5249 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy, 5250 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) { 5251 Action.Enter(CGF); 5252 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy}; 5253 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry, 5254 OutlinedFnArgs); 5255 }; 5256 5257 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid, 5258 // kmp_task_t *new_task); 5259 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid, 5260 // kmp_task_t *new_task); 5261 RegionCodeGenTy RCG(CodeGen); 5262 CommonActionTy Action( 5263 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs, 5264 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs); 5265 RCG.setAction(Action); 5266 RCG(CGF); 5267 }; 5268 5269 if (IfCond) { 5270 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen); 5271 } else { 5272 RegionCodeGenTy ThenRCG(ThenCodeGen); 5273 ThenRCG(CGF); 5274 } 5275 } 5276 5277 void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, 5278 const OMPLoopDirective &D, 5279 llvm::Function *TaskFunction, 5280 QualType SharedsTy, Address Shareds, 5281 const Expr *IfCond, 5282 const OMPTaskDataTy &Data) { 5283 if (!CGF.HaveInsertPoint()) 5284 return; 5285 TaskResultTy Result = 5286 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data); 5287 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc() 5288 // libcall. 5289 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int 5290 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int 5291 // sched, kmp_uint64 grainsize, void *task_dup); 5292 llvm::Value *ThreadID = getThreadID(CGF, Loc); 5293 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc); 5294 llvm::Value *IfVal; 5295 if (IfCond) { 5296 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy, 5297 /*isSigned=*/true); 5298 } else { 5299 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1); 5300 } 5301 5302 LValue LBLVal = CGF.EmitLValueForField( 5303 Result.TDBase, 5304 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound)); 5305 const auto *LBVar = 5306 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl()); 5307 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(), 5308 /*IsInitializer=*/true); 5309 LValue UBLVal = CGF.EmitLValueForField( 5310 Result.TDBase, 5311 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound)); 5312 const auto *UBVar = 5313 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl()); 5314 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(), 5315 /*IsInitializer=*/true); 5316 LValue StLVal = CGF.EmitLValueForField( 5317 Result.TDBase, 5318 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride)); 5319 const auto *StVar = 5320 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl()); 5321 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(), 5322 /*IsInitializer=*/true); 5323 // Store reductions address. 5324 LValue RedLVal = CGF.EmitLValueForField( 5325 Result.TDBase, 5326 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions)); 5327 if (Data.Reductions) { 5328 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal); 5329 } else { 5330 CGF.EmitNullInitialization(RedLVal.getAddress(), 5331 CGF.getContext().VoidPtrTy); 5332 } 5333 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 }; 5334 llvm::Value *TaskArgs[] = { 5335 UpLoc, 5336 ThreadID, 5337 Result.NewTask, 5338 IfVal, 5339 LBLVal.getPointer(), 5340 UBLVal.getPointer(), 5341 CGF.EmitLoadOfScalar(StLVal, Loc), 5342 llvm::ConstantInt::getSigned( 5343 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler 5344 llvm::ConstantInt::getSigned( 5345 CGF.IntTy, Data.Schedule.getPointer() 5346 ? Data.Schedule.getInt() ? NumTasks : Grainsize 5347 : NoSchedule), 5348 Data.Schedule.getPointer() 5349 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty, 5350 /*isSigned=*/false) 5351 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0), 5352 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5353 Result.TaskDupFn, CGF.VoidPtrTy) 5354 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)}; 5355 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs); 5356 } 5357 5358 /// Emit reduction operation for each element of array (required for 5359 /// array sections) LHS op = RHS. 5360 /// \param Type Type of array. 5361 /// \param LHSVar Variable on the left side of the reduction operation 5362 /// (references element of array in original variable). 5363 /// \param RHSVar Variable on the right side of the reduction operation 5364 /// (references element of array in original variable). 5365 /// \param RedOpGen Generator of reduction operation with use of LHSVar and 5366 /// RHSVar. 5367 static void EmitOMPAggregateReduction( 5368 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar, 5369 const VarDecl *RHSVar, 5370 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *, 5371 const Expr *, const Expr *)> &RedOpGen, 5372 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr, 5373 const Expr *UpExpr = nullptr) { 5374 // Perform element-by-element initialization. 5375 QualType ElementTy; 5376 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar); 5377 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar); 5378 5379 // Drill down to the base element type on both arrays. 5380 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe(); 5381 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr); 5382 5383 llvm::Value *RHSBegin = RHSAddr.getPointer(); 5384 llvm::Value *LHSBegin = LHSAddr.getPointer(); 5385 // Cast from pointer to array type to pointer to single element. 5386 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements); 5387 // The basic structure here is a while-do loop. 5388 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body"); 5389 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done"); 5390 llvm::Value *IsEmpty = 5391 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty"); 5392 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 5393 5394 // Enter the loop body, making that address the current address. 5395 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); 5396 CGF.EmitBlock(BodyBB); 5397 5398 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); 5399 5400 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI( 5401 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 5402 RHSElementPHI->addIncoming(RHSBegin, EntryBB); 5403 Address RHSElementCurrent = 5404 Address(RHSElementPHI, 5405 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 5406 5407 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI( 5408 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast"); 5409 LHSElementPHI->addIncoming(LHSBegin, EntryBB); 5410 Address LHSElementCurrent = 5411 Address(LHSElementPHI, 5412 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 5413 5414 // Emit copy. 5415 CodeGenFunction::OMPPrivateScope Scope(CGF); 5416 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; }); 5417 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; }); 5418 Scope.Privatize(); 5419 RedOpGen(CGF, XExpr, EExpr, UpExpr); 5420 Scope.ForceCleanup(); 5421 5422 // Shift the address forward by one element. 5423 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32( 5424 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 5425 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32( 5426 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element"); 5427 // Check whether we've reached the end. 5428 llvm::Value *Done = 5429 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done"); 5430 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); 5431 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock()); 5432 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock()); 5433 5434 // Done. 5435 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 5436 } 5437 5438 /// Emit reduction combiner. If the combiner is a simple expression emit it as 5439 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of 5440 /// UDR combiner function. 5441 static void emitReductionCombiner(CodeGenFunction &CGF, 5442 const Expr *ReductionOp) { 5443 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) 5444 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) 5445 if (const auto *DRE = 5446 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) 5447 if (const auto *DRD = 5448 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) { 5449 std::pair<llvm::Function *, llvm::Function *> Reduction = 5450 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); 5451 RValue Func = RValue::get(Reduction.first); 5452 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); 5453 CGF.EmitIgnoredExpr(ReductionOp); 5454 return; 5455 } 5456 CGF.EmitIgnoredExpr(ReductionOp); 5457 } 5458 5459 llvm::Function *CGOpenMPRuntime::emitReductionFunction( 5460 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType, 5461 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, 5462 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) { 5463 ASTContext &C = CGM.getContext(); 5464 5465 // void reduction_func(void *LHSArg, void *RHSArg); 5466 FunctionArgList Args; 5467 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5468 ImplicitParamDecl::Other); 5469 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5470 ImplicitParamDecl::Other); 5471 Args.push_back(&LHSArg); 5472 Args.push_back(&RHSArg); 5473 const auto &CGFI = 5474 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 5475 std::string Name = getName({"omp", "reduction", "reduction_func"}); 5476 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI), 5477 llvm::GlobalValue::InternalLinkage, Name, 5478 &CGM.getModule()); 5479 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); 5480 Fn->setDoesNotRecurse(); 5481 CodeGenFunction CGF(CGM); 5482 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); 5483 5484 // Dst = (void*[n])(LHSArg); 5485 // Src = (void*[n])(RHSArg); 5486 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5487 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)), 5488 ArgsType), CGF.getPointerAlign()); 5489 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5490 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)), 5491 ArgsType), CGF.getPointerAlign()); 5492 5493 // ... 5494 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); 5495 // ... 5496 CodeGenFunction::OMPPrivateScope Scope(CGF); 5497 auto IPriv = Privates.begin(); 5498 unsigned Idx = 0; 5499 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) { 5500 const auto *RHSVar = 5501 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()); 5502 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() { 5503 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar); 5504 }); 5505 const auto *LHSVar = 5506 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()); 5507 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() { 5508 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar); 5509 }); 5510 QualType PrivTy = (*IPriv)->getType(); 5511 if (PrivTy->isVariablyModifiedType()) { 5512 // Get array size and emit VLA type. 5513 ++Idx; 5514 Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx); 5515 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem); 5516 const VariableArrayType *VLA = 5517 CGF.getContext().getAsVariableArrayType(PrivTy); 5518 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr()); 5519 CodeGenFunction::OpaqueValueMapping OpaqueMap( 5520 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy))); 5521 CGF.EmitVariablyModifiedType(PrivTy); 5522 } 5523 } 5524 Scope.Privatize(); 5525 IPriv = Privates.begin(); 5526 auto ILHS = LHSExprs.begin(); 5527 auto IRHS = RHSExprs.begin(); 5528 for (const Expr *E : ReductionOps) { 5529 if ((*IPriv)->getType()->isArrayType()) { 5530 // Emit reduction for array section. 5531 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 5532 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 5533 EmitOMPAggregateReduction( 5534 CGF, (*IPriv)->getType(), LHSVar, RHSVar, 5535 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) { 5536 emitReductionCombiner(CGF, E); 5537 }); 5538 } else { 5539 // Emit reduction for array subscript or single variable. 5540 emitReductionCombiner(CGF, E); 5541 } 5542 ++IPriv; 5543 ++ILHS; 5544 ++IRHS; 5545 } 5546 Scope.ForceCleanup(); 5547 CGF.FinishFunction(); 5548 return Fn; 5549 } 5550 5551 void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF, 5552 const Expr *ReductionOp, 5553 const Expr *PrivateRef, 5554 const DeclRefExpr *LHS, 5555 const DeclRefExpr *RHS) { 5556 if (PrivateRef->getType()->isArrayType()) { 5557 // Emit reduction for array section. 5558 const auto *LHSVar = cast<VarDecl>(LHS->getDecl()); 5559 const auto *RHSVar = cast<VarDecl>(RHS->getDecl()); 5560 EmitOMPAggregateReduction( 5561 CGF, PrivateRef->getType(), LHSVar, RHSVar, 5562 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) { 5563 emitReductionCombiner(CGF, ReductionOp); 5564 }); 5565 } else { 5566 // Emit reduction for array subscript or single variable. 5567 emitReductionCombiner(CGF, ReductionOp); 5568 } 5569 } 5570 5571 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc, 5572 ArrayRef<const Expr *> Privates, 5573 ArrayRef<const Expr *> LHSExprs, 5574 ArrayRef<const Expr *> RHSExprs, 5575 ArrayRef<const Expr *> ReductionOps, 5576 ReductionOptionsTy Options) { 5577 if (!CGF.HaveInsertPoint()) 5578 return; 5579 5580 bool WithNowait = Options.WithNowait; 5581 bool SimpleReduction = Options.SimpleReduction; 5582 5583 // Next code should be emitted for reduction: 5584 // 5585 // static kmp_critical_name lock = { 0 }; 5586 // 5587 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) { 5588 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]); 5589 // ... 5590 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1], 5591 // *(Type<n>-1*)rhs[<n>-1]); 5592 // } 5593 // 5594 // ... 5595 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; 5596 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 5597 // RedList, reduce_func, &<lock>)) { 5598 // case 1: 5599 // ... 5600 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 5601 // ... 5602 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 5603 // break; 5604 // case 2: 5605 // ... 5606 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 5607 // ... 5608 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);] 5609 // break; 5610 // default:; 5611 // } 5612 // 5613 // if SimpleReduction is true, only the next code is generated: 5614 // ... 5615 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 5616 // ... 5617 5618 ASTContext &C = CGM.getContext(); 5619 5620 if (SimpleReduction) { 5621 CodeGenFunction::RunCleanupsScope Scope(CGF); 5622 auto IPriv = Privates.begin(); 5623 auto ILHS = LHSExprs.begin(); 5624 auto IRHS = RHSExprs.begin(); 5625 for (const Expr *E : ReductionOps) { 5626 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), 5627 cast<DeclRefExpr>(*IRHS)); 5628 ++IPriv; 5629 ++ILHS; 5630 ++IRHS; 5631 } 5632 return; 5633 } 5634 5635 // 1. Build a list of reduction variables. 5636 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]}; 5637 auto Size = RHSExprs.size(); 5638 for (const Expr *E : Privates) { 5639 if (E->getType()->isVariablyModifiedType()) 5640 // Reserve place for array size. 5641 ++Size; 5642 } 5643 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size); 5644 QualType ReductionArrayTy = 5645 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal, 5646 /*IndexTypeQuals=*/0); 5647 Address ReductionList = 5648 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list"); 5649 auto IPriv = Privates.begin(); 5650 unsigned Idx = 0; 5651 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) { 5652 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx); 5653 CGF.Builder.CreateStore( 5654 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5655 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy), 5656 Elem); 5657 if ((*IPriv)->getType()->isVariablyModifiedType()) { 5658 // Store array size. 5659 ++Idx; 5660 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx); 5661 llvm::Value *Size = CGF.Builder.CreateIntCast( 5662 CGF.getVLASize( 5663 CGF.getContext().getAsVariableArrayType((*IPriv)->getType())) 5664 .NumElts, 5665 CGF.SizeTy, /*isSigned=*/false); 5666 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy), 5667 Elem); 5668 } 5669 } 5670 5671 // 2. Emit reduce_func(). 5672 llvm::Function *ReductionFn = emitReductionFunction( 5673 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), 5674 Privates, LHSExprs, RHSExprs, ReductionOps); 5675 5676 // 3. Create static kmp_critical_name lock = { 0 }; 5677 std::string Name = getName({"reduction"}); 5678 llvm::Value *Lock = getCriticalRegionLock(Name); 5679 5680 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 5681 // RedList, reduce_func, &<lock>); 5682 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE); 5683 llvm::Value *ThreadId = getThreadID(CGF, Loc); 5684 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy); 5685 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5686 ReductionList.getPointer(), CGF.VoidPtrTy); 5687 llvm::Value *Args[] = { 5688 IdentTLoc, // ident_t *<loc> 5689 ThreadId, // i32 <gtid> 5690 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n> 5691 ReductionArrayTySize, // size_type sizeof(RedList) 5692 RL, // void *RedList 5693 ReductionFn, // void (*) (void *, void *) <reduce_func> 5694 Lock // kmp_critical_name *&<lock> 5695 }; 5696 llvm::Value *Res = CGF.EmitRuntimeCall( 5697 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait 5698 : OMPRTL__kmpc_reduce), 5699 Args); 5700 5701 // 5. Build switch(res) 5702 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default"); 5703 llvm::SwitchInst *SwInst = 5704 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2); 5705 5706 // 6. Build case 1: 5707 // ... 5708 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 5709 // ... 5710 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 5711 // break; 5712 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1"); 5713 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB); 5714 CGF.EmitBlock(Case1BB); 5715 5716 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 5717 llvm::Value *EndArgs[] = { 5718 IdentTLoc, // ident_t *<loc> 5719 ThreadId, // i32 <gtid> 5720 Lock // kmp_critical_name *&<lock> 5721 }; 5722 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps]( 5723 CodeGenFunction &CGF, PrePostActionTy &Action) { 5724 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 5725 auto IPriv = Privates.begin(); 5726 auto ILHS = LHSExprs.begin(); 5727 auto IRHS = RHSExprs.begin(); 5728 for (const Expr *E : ReductionOps) { 5729 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), 5730 cast<DeclRefExpr>(*IRHS)); 5731 ++IPriv; 5732 ++ILHS; 5733 ++IRHS; 5734 } 5735 }; 5736 RegionCodeGenTy RCG(CodeGen); 5737 CommonActionTy Action( 5738 nullptr, llvm::None, 5739 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait 5740 : OMPRTL__kmpc_end_reduce), 5741 EndArgs); 5742 RCG.setAction(Action); 5743 RCG(CGF); 5744 5745 CGF.EmitBranch(DefaultBB); 5746 5747 // 7. Build case 2: 5748 // ... 5749 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 5750 // ... 5751 // break; 5752 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2"); 5753 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB); 5754 CGF.EmitBlock(Case2BB); 5755 5756 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps]( 5757 CodeGenFunction &CGF, PrePostActionTy &Action) { 5758 auto ILHS = LHSExprs.begin(); 5759 auto IRHS = RHSExprs.begin(); 5760 auto IPriv = Privates.begin(); 5761 for (const Expr *E : ReductionOps) { 5762 const Expr *XExpr = nullptr; 5763 const Expr *EExpr = nullptr; 5764 const Expr *UpExpr = nullptr; 5765 BinaryOperatorKind BO = BO_Comma; 5766 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 5767 if (BO->getOpcode() == BO_Assign) { 5768 XExpr = BO->getLHS(); 5769 UpExpr = BO->getRHS(); 5770 } 5771 } 5772 // Try to emit update expression as a simple atomic. 5773 const Expr *RHSExpr = UpExpr; 5774 if (RHSExpr) { 5775 // Analyze RHS part of the whole expression. 5776 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>( 5777 RHSExpr->IgnoreParenImpCasts())) { 5778 // If this is a conditional operator, analyze its condition for 5779 // min/max reduction operator. 5780 RHSExpr = ACO->getCond(); 5781 } 5782 if (const auto *BORHS = 5783 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) { 5784 EExpr = BORHS->getRHS(); 5785 BO = BORHS->getOpcode(); 5786 } 5787 } 5788 if (XExpr) { 5789 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 5790 auto &&AtomicRedGen = [BO, VD, 5791 Loc](CodeGenFunction &CGF, const Expr *XExpr, 5792 const Expr *EExpr, const Expr *UpExpr) { 5793 LValue X = CGF.EmitLValue(XExpr); 5794 RValue E; 5795 if (EExpr) 5796 E = CGF.EmitAnyExpr(EExpr); 5797 CGF.EmitOMPAtomicSimpleUpdateExpr( 5798 X, E, BO, /*IsXLHSInRHSPart=*/true, 5799 llvm::AtomicOrdering::Monotonic, Loc, 5800 [&CGF, UpExpr, VD, Loc](RValue XRValue) { 5801 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5802 PrivateScope.addPrivate( 5803 VD, [&CGF, VD, XRValue, Loc]() { 5804 Address LHSTemp = CGF.CreateMemTemp(VD->getType()); 5805 CGF.emitOMPSimpleStore( 5806 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue, 5807 VD->getType().getNonReferenceType(), Loc); 5808 return LHSTemp; 5809 }); 5810 (void)PrivateScope.Privatize(); 5811 return CGF.EmitAnyExpr(UpExpr); 5812 }); 5813 }; 5814 if ((*IPriv)->getType()->isArrayType()) { 5815 // Emit atomic reduction for array section. 5816 const auto *RHSVar = 5817 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 5818 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar, 5819 AtomicRedGen, XExpr, EExpr, UpExpr); 5820 } else { 5821 // Emit atomic reduction for array subscript or single variable. 5822 AtomicRedGen(CGF, XExpr, EExpr, UpExpr); 5823 } 5824 } else { 5825 // Emit as a critical region. 5826 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *, 5827 const Expr *, const Expr *) { 5828 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 5829 std::string Name = RT.getName({"atomic_reduction"}); 5830 RT.emitCriticalRegion( 5831 CGF, Name, 5832 [=](CodeGenFunction &CGF, PrePostActionTy &Action) { 5833 Action.Enter(CGF); 5834 emitReductionCombiner(CGF, E); 5835 }, 5836 Loc); 5837 }; 5838 if ((*IPriv)->getType()->isArrayType()) { 5839 const auto *LHSVar = 5840 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 5841 const auto *RHSVar = 5842 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 5843 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar, 5844 CritRedGen); 5845 } else { 5846 CritRedGen(CGF, nullptr, nullptr, nullptr); 5847 } 5848 } 5849 ++ILHS; 5850 ++IRHS; 5851 ++IPriv; 5852 } 5853 }; 5854 RegionCodeGenTy AtomicRCG(AtomicCodeGen); 5855 if (!WithNowait) { 5856 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>); 5857 llvm::Value *EndArgs[] = { 5858 IdentTLoc, // ident_t *<loc> 5859 ThreadId, // i32 <gtid> 5860 Lock // kmp_critical_name *&<lock> 5861 }; 5862 CommonActionTy Action(nullptr, llvm::None, 5863 createRuntimeFunction(OMPRTL__kmpc_end_reduce), 5864 EndArgs); 5865 AtomicRCG.setAction(Action); 5866 AtomicRCG(CGF); 5867 } else { 5868 AtomicRCG(CGF); 5869 } 5870 5871 CGF.EmitBranch(DefaultBB); 5872 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true); 5873 } 5874 5875 /// Generates unique name for artificial threadprivate variables. 5876 /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>" 5877 static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix, 5878 const Expr *Ref) { 5879 SmallString<256> Buffer; 5880 llvm::raw_svector_ostream Out(Buffer); 5881 const clang::DeclRefExpr *DE; 5882 const VarDecl *D = ::getBaseDecl(Ref, DE); 5883 if (!D) 5884 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl()); 5885 D = D->getCanonicalDecl(); 5886 std::string Name = CGM.getOpenMPRuntime().getName( 5887 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)}); 5888 Out << Prefix << Name << "_" 5889 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding(); 5890 return Out.str(); 5891 } 5892 5893 /// Emits reduction initializer function: 5894 /// \code 5895 /// void @.red_init(void* %arg) { 5896 /// %0 = bitcast void* %arg to <type>* 5897 /// store <type> <init>, <type>* %0 5898 /// ret void 5899 /// } 5900 /// \endcode 5901 static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM, 5902 SourceLocation Loc, 5903 ReductionCodeGen &RCG, unsigned N) { 5904 ASTContext &C = CGM.getContext(); 5905 FunctionArgList Args; 5906 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5907 ImplicitParamDecl::Other); 5908 Args.emplace_back(&Param); 5909 const auto &FnInfo = 5910 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 5911 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 5912 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""}); 5913 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, 5914 Name, &CGM.getModule()); 5915 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); 5916 Fn->setDoesNotRecurse(); 5917 CodeGenFunction CGF(CGM); 5918 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); 5919 Address PrivateAddr = CGF.EmitLoadOfPointer( 5920 CGF.GetAddrOfLocalVar(&Param), 5921 C.getPointerType(C.VoidPtrTy).castAs<PointerType>()); 5922 llvm::Value *Size = nullptr; 5923 // If the size of the reduction item is non-constant, load it from global 5924 // threadprivate variable. 5925 if (RCG.getSizes(N).second) { 5926 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( 5927 CGF, CGM.getContext().getSizeType(), 5928 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); 5929 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, 5930 CGM.getContext().getSizeType(), Loc); 5931 } 5932 RCG.emitAggregateType(CGF, N, Size); 5933 LValue SharedLVal; 5934 // If initializer uses initializer from declare reduction construct, emit a 5935 // pointer to the address of the original reduction item (reuired by reduction 5936 // initializer) 5937 if (RCG.usesReductionInitializer(N)) { 5938 Address SharedAddr = 5939 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( 5940 CGF, CGM.getContext().VoidPtrTy, 5941 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N))); 5942 SharedAddr = CGF.EmitLoadOfPointer( 5943 SharedAddr, 5944 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr()); 5945 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy); 5946 } else { 5947 SharedLVal = CGF.MakeNaturalAlignAddrLValue( 5948 llvm::ConstantPointerNull::get(CGM.VoidPtrTy), 5949 CGM.getContext().VoidPtrTy); 5950 } 5951 // Emit the initializer: 5952 // %0 = bitcast void* %arg to <type>* 5953 // store <type> <init>, <type>* %0 5954 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal, 5955 [](CodeGenFunction &) { return false; }); 5956 CGF.FinishFunction(); 5957 return Fn; 5958 } 5959 5960 /// Emits reduction combiner function: 5961 /// \code 5962 /// void @.red_comb(void* %arg0, void* %arg1) { 5963 /// %lhs = bitcast void* %arg0 to <type>* 5964 /// %rhs = bitcast void* %arg1 to <type>* 5965 /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs) 5966 /// store <type> %2, <type>* %lhs 5967 /// ret void 5968 /// } 5969 /// \endcode 5970 static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM, 5971 SourceLocation Loc, 5972 ReductionCodeGen &RCG, unsigned N, 5973 const Expr *ReductionOp, 5974 const Expr *LHS, const Expr *RHS, 5975 const Expr *PrivateRef) { 5976 ASTContext &C = CGM.getContext(); 5977 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl()); 5978 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl()); 5979 FunctionArgList Args; 5980 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 5981 C.VoidPtrTy, ImplicitParamDecl::Other); 5982 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5983 ImplicitParamDecl::Other); 5984 Args.emplace_back(&ParamInOut); 5985 Args.emplace_back(&ParamIn); 5986 const auto &FnInfo = 5987 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 5988 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 5989 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""}); 5990 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, 5991 Name, &CGM.getModule()); 5992 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); 5993 Fn->setDoesNotRecurse(); 5994 CodeGenFunction CGF(CGM); 5995 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); 5996 llvm::Value *Size = nullptr; 5997 // If the size of the reduction item is non-constant, load it from global 5998 // threadprivate variable. 5999 if (RCG.getSizes(N).second) { 6000 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( 6001 CGF, CGM.getContext().getSizeType(), 6002 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); 6003 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, 6004 CGM.getContext().getSizeType(), Loc); 6005 } 6006 RCG.emitAggregateType(CGF, N, Size); 6007 // Remap lhs and rhs variables to the addresses of the function arguments. 6008 // %lhs = bitcast void* %arg0 to <type>* 6009 // %rhs = bitcast void* %arg1 to <type>* 6010 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6011 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() { 6012 // Pull out the pointer to the variable. 6013 Address PtrAddr = CGF.EmitLoadOfPointer( 6014 CGF.GetAddrOfLocalVar(&ParamInOut), 6015 C.getPointerType(C.VoidPtrTy).castAs<PointerType>()); 6016 return CGF.Builder.CreateElementBitCast( 6017 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType())); 6018 }); 6019 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() { 6020 // Pull out the pointer to the variable. 6021 Address PtrAddr = CGF.EmitLoadOfPointer( 6022 CGF.GetAddrOfLocalVar(&ParamIn), 6023 C.getPointerType(C.VoidPtrTy).castAs<PointerType>()); 6024 return CGF.Builder.CreateElementBitCast( 6025 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType())); 6026 }); 6027 PrivateScope.Privatize(); 6028 // Emit the combiner body: 6029 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs) 6030 // store <type> %2, <type>* %lhs 6031 CGM.getOpenMPRuntime().emitSingleReductionCombiner( 6032 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS), 6033 cast<DeclRefExpr>(RHS)); 6034 CGF.FinishFunction(); 6035 return Fn; 6036 } 6037 6038 /// Emits reduction finalizer function: 6039 /// \code 6040 /// void @.red_fini(void* %arg) { 6041 /// %0 = bitcast void* %arg to <type>* 6042 /// <destroy>(<type>* %0) 6043 /// ret void 6044 /// } 6045 /// \endcode 6046 static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM, 6047 SourceLocation Loc, 6048 ReductionCodeGen &RCG, unsigned N) { 6049 if (!RCG.needCleanups(N)) 6050 return nullptr; 6051 ASTContext &C = CGM.getContext(); 6052 FunctionArgList Args; 6053 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 6054 ImplicitParamDecl::Other); 6055 Args.emplace_back(&Param); 6056 const auto &FnInfo = 6057 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 6058 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 6059 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""}); 6060 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, 6061 Name, &CGM.getModule()); 6062 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); 6063 Fn->setDoesNotRecurse(); 6064 CodeGenFunction CGF(CGM); 6065 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); 6066 Address PrivateAddr = CGF.EmitLoadOfPointer( 6067 CGF.GetAddrOfLocalVar(&Param), 6068 C.getPointerType(C.VoidPtrTy).castAs<PointerType>()); 6069 llvm::Value *Size = nullptr; 6070 // If the size of the reduction item is non-constant, load it from global 6071 // threadprivate variable. 6072 if (RCG.getSizes(N).second) { 6073 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( 6074 CGF, CGM.getContext().getSizeType(), 6075 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); 6076 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, 6077 CGM.getContext().getSizeType(), Loc); 6078 } 6079 RCG.emitAggregateType(CGF, N, Size); 6080 // Emit the finalizer body: 6081 // <destroy>(<type>* %0) 6082 RCG.emitCleanups(CGF, N, PrivateAddr); 6083 CGF.FinishFunction(); 6084 return Fn; 6085 } 6086 6087 llvm::Value *CGOpenMPRuntime::emitTaskReductionInit( 6088 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, 6089 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) { 6090 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty()) 6091 return nullptr; 6092 6093 // Build typedef struct: 6094 // kmp_task_red_input { 6095 // void *reduce_shar; // shared reduction item 6096 // size_t reduce_size; // size of data item 6097 // void *reduce_init; // data initialization routine 6098 // void *reduce_fini; // data finalization routine 6099 // void *reduce_comb; // data combiner routine 6100 // kmp_task_red_flags_t flags; // flags for additional info from compiler 6101 // } kmp_task_red_input_t; 6102 ASTContext &C = CGM.getContext(); 6103 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t"); 6104 RD->startDefinition(); 6105 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); 6106 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType()); 6107 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); 6108 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); 6109 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); 6110 const FieldDecl *FlagsFD = addFieldToRecordDecl( 6111 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false)); 6112 RD->completeDefinition(); 6113 QualType RDType = C.getRecordType(RD); 6114 unsigned Size = Data.ReductionVars.size(); 6115 llvm::APInt ArraySize(/*numBits=*/64, Size); 6116 QualType ArrayRDType = C.getConstantArrayType( 6117 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0); 6118 // kmp_task_red_input_t .rd_input.[Size]; 6119 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input."); 6120 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies, 6121 Data.ReductionOps); 6122 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) { 6123 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt]; 6124 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0), 6125 llvm::ConstantInt::get(CGM.SizeTy, Cnt)}; 6126 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP( 6127 TaskRedInput.getPointer(), Idxs, 6128 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc, 6129 ".rd_input.gep."); 6130 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType); 6131 // ElemLVal.reduce_shar = &Shareds[Cnt]; 6132 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD); 6133 RCG.emitSharedLValue(CGF, Cnt); 6134 llvm::Value *CastedShared = 6135 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer()); 6136 CGF.EmitStoreOfScalar(CastedShared, SharedLVal); 6137 RCG.emitAggregateType(CGF, Cnt); 6138 llvm::Value *SizeValInChars; 6139 llvm::Value *SizeVal; 6140 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt); 6141 // We use delayed creation/initialization for VLAs, array sections and 6142 // custom reduction initializations. It is required because runtime does not 6143 // provide the way to pass the sizes of VLAs/array sections to 6144 // initializer/combiner/finalizer functions and does not pass the pointer to 6145 // original reduction item to the initializer. Instead threadprivate global 6146 // variables are used to store these values and use them in the functions. 6147 bool DelayedCreation = !!SizeVal; 6148 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy, 6149 /*isSigned=*/false); 6150 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD); 6151 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal); 6152 // ElemLVal.reduce_init = init; 6153 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD); 6154 llvm::Value *InitAddr = 6155 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt)); 6156 CGF.EmitStoreOfScalar(InitAddr, InitLVal); 6157 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt); 6158 // ElemLVal.reduce_fini = fini; 6159 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD); 6160 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt); 6161 llvm::Value *FiniAddr = Fini 6162 ? CGF.EmitCastToVoidPtr(Fini) 6163 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy); 6164 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal); 6165 // ElemLVal.reduce_comb = comb; 6166 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD); 6167 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction( 6168 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt], 6169 RHSExprs[Cnt], Data.ReductionCopies[Cnt])); 6170 CGF.EmitStoreOfScalar(CombAddr, CombLVal); 6171 // ElemLVal.flags = 0; 6172 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD); 6173 if (DelayedCreation) { 6174 CGF.EmitStoreOfScalar( 6175 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true), 6176 FlagsLVal); 6177 } else 6178 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType()); 6179 } 6180 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void 6181 // *data); 6182 llvm::Value *Args[] = { 6183 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy, 6184 /*isSigned=*/true), 6185 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true), 6186 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(), 6187 CGM.VoidPtrTy)}; 6188 return CGF.EmitRuntimeCall( 6189 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args); 6190 } 6191 6192 void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF, 6193 SourceLocation Loc, 6194 ReductionCodeGen &RCG, 6195 unsigned N) { 6196 auto Sizes = RCG.getSizes(N); 6197 // Emit threadprivate global variable if the type is non-constant 6198 // (Sizes.second = nullptr). 6199 if (Sizes.second) { 6200 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy, 6201 /*isSigned=*/false); 6202 Address SizeAddr = getAddrOfArtificialThreadPrivate( 6203 CGF, CGM.getContext().getSizeType(), 6204 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); 6205 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false); 6206 } 6207 // Store address of the original reduction item if custom initializer is used. 6208 if (RCG.usesReductionInitializer(N)) { 6209 Address SharedAddr = getAddrOfArtificialThreadPrivate( 6210 CGF, CGM.getContext().VoidPtrTy, 6211 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N))); 6212 CGF.Builder.CreateStore( 6213 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 6214 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy), 6215 SharedAddr, /*IsVolatile=*/false); 6216 } 6217 } 6218 6219 Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF, 6220 SourceLocation Loc, 6221 llvm::Value *ReductionsPtr, 6222 LValue SharedLVal) { 6223 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void 6224 // *d); 6225 llvm::Value *Args[] = { 6226 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy, 6227 /*isSigned=*/true), 6228 ReductionsPtr, 6229 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(), 6230 CGM.VoidPtrTy)}; 6231 return Address( 6232 CGF.EmitRuntimeCall( 6233 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args), 6234 SharedLVal.getAlignment()); 6235 } 6236 6237 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF, 6238 SourceLocation Loc) { 6239 if (!CGF.HaveInsertPoint()) 6240 return; 6241 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 6242 // global_tid); 6243 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 6244 // Ignore return result until untied tasks are supported. 6245 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args); 6246 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) 6247 Region->emitUntiedSwitch(CGF); 6248 } 6249 6250 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF, 6251 OpenMPDirectiveKind InnerKind, 6252 const RegionCodeGenTy &CodeGen, 6253 bool HasCancel) { 6254 if (!CGF.HaveInsertPoint()) 6255 return; 6256 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel); 6257 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr); 6258 } 6259 6260 namespace { 6261 enum RTCancelKind { 6262 CancelNoreq = 0, 6263 CancelParallel = 1, 6264 CancelLoop = 2, 6265 CancelSections = 3, 6266 CancelTaskgroup = 4 6267 }; 6268 } // anonymous namespace 6269 6270 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) { 6271 RTCancelKind CancelKind = CancelNoreq; 6272 if (CancelRegion == OMPD_parallel) 6273 CancelKind = CancelParallel; 6274 else if (CancelRegion == OMPD_for) 6275 CancelKind = CancelLoop; 6276 else if (CancelRegion == OMPD_sections) 6277 CancelKind = CancelSections; 6278 else { 6279 assert(CancelRegion == OMPD_taskgroup); 6280 CancelKind = CancelTaskgroup; 6281 } 6282 return CancelKind; 6283 } 6284 6285 void CGOpenMPRuntime::emitCancellationPointCall( 6286 CodeGenFunction &CGF, SourceLocation Loc, 6287 OpenMPDirectiveKind CancelRegion) { 6288 if (!CGF.HaveInsertPoint()) 6289 return; 6290 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32 6291 // global_tid, kmp_int32 cncl_kind); 6292 if (auto *OMPRegionInfo = 6293 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { 6294 // For 'cancellation point taskgroup', the task region info may not have a 6295 // cancel. This may instead happen in another adjacent task. 6296 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) { 6297 llvm::Value *Args[] = { 6298 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 6299 CGF.Builder.getInt32(getCancellationKind(CancelRegion))}; 6300 // Ignore return result until untied tasks are supported. 6301 llvm::Value *Result = CGF.EmitRuntimeCall( 6302 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args); 6303 // if (__kmpc_cancellationpoint()) { 6304 // exit from construct; 6305 // } 6306 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit"); 6307 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue"); 6308 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result); 6309 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB); 6310 CGF.EmitBlock(ExitBB); 6311 // exit from construct; 6312 CodeGenFunction::JumpDest CancelDest = 6313 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind()); 6314 CGF.EmitBranchThroughCleanup(CancelDest); 6315 CGF.EmitBlock(ContBB, /*IsFinished=*/true); 6316 } 6317 } 6318 } 6319 6320 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, 6321 const Expr *IfCond, 6322 OpenMPDirectiveKind CancelRegion) { 6323 if (!CGF.HaveInsertPoint()) 6324 return; 6325 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid, 6326 // kmp_int32 cncl_kind); 6327 if (auto *OMPRegionInfo = 6328 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { 6329 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF, 6330 PrePostActionTy &) { 6331 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 6332 llvm::Value *Args[] = { 6333 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc), 6334 CGF.Builder.getInt32(getCancellationKind(CancelRegion))}; 6335 // Ignore return result until untied tasks are supported. 6336 llvm::Value *Result = CGF.EmitRuntimeCall( 6337 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args); 6338 // if (__kmpc_cancel()) { 6339 // exit from construct; 6340 // } 6341 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit"); 6342 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue"); 6343 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result); 6344 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB); 6345 CGF.EmitBlock(ExitBB); 6346 // exit from construct; 6347 CodeGenFunction::JumpDest CancelDest = 6348 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind()); 6349 CGF.EmitBranchThroughCleanup(CancelDest); 6350 CGF.EmitBlock(ContBB, /*IsFinished=*/true); 6351 }; 6352 if (IfCond) { 6353 emitOMPIfClause(CGF, IfCond, ThenGen, 6354 [](CodeGenFunction &, PrePostActionTy &) {}); 6355 } else { 6356 RegionCodeGenTy ThenRCG(ThenGen); 6357 ThenRCG(CGF); 6358 } 6359 } 6360 } 6361 6362 void CGOpenMPRuntime::emitTargetOutlinedFunction( 6363 const OMPExecutableDirective &D, StringRef ParentName, 6364 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, 6365 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { 6366 assert(!ParentName.empty() && "Invalid target region parent name!"); 6367 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID, 6368 IsOffloadEntry, CodeGen); 6369 } 6370 6371 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper( 6372 const OMPExecutableDirective &D, StringRef ParentName, 6373 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, 6374 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { 6375 // Create a unique name for the entry function using the source location 6376 // information of the current target region. The name will be something like: 6377 // 6378 // __omp_offloading_DD_FFFF_PP_lBB 6379 // 6380 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the 6381 // mangled name of the function that encloses the target region and BB is the 6382 // line number of the target region. 6383 6384 unsigned DeviceID; 6385 unsigned FileID; 6386 unsigned Line; 6387 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID, 6388 Line); 6389 SmallString<64> EntryFnName; 6390 { 6391 llvm::raw_svector_ostream OS(EntryFnName); 6392 OS << "__omp_offloading" << llvm::format("_%x", DeviceID) 6393 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line; 6394 } 6395 6396 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target); 6397 6398 CodeGenFunction CGF(CGM, true); 6399 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName); 6400 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 6401 6402 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS); 6403 6404 // If this target outline function is not an offload entry, we don't need to 6405 // register it. 6406 if (!IsOffloadEntry) 6407 return; 6408 6409 // The target region ID is used by the runtime library to identify the current 6410 // target region, so it only has to be unique and not necessarily point to 6411 // anything. It could be the pointer to the outlined function that implements 6412 // the target region, but we aren't using that so that the compiler doesn't 6413 // need to keep that, and could therefore inline the host function if proven 6414 // worthwhile during optimization. In the other hand, if emitting code for the 6415 // device, the ID has to be the function address so that it can retrieved from 6416 // the offloading entry and launched by the runtime library. We also mark the 6417 // outlined function to have external linkage in case we are emitting code for 6418 // the device, because these functions will be entry points to the device. 6419 6420 if (CGM.getLangOpts().OpenMPIsDevice) { 6421 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy); 6422 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage); 6423 OutlinedFn->setDSOLocal(false); 6424 } else { 6425 std::string Name = getName({EntryFnName, "region_id"}); 6426 OutlinedFnID = new llvm::GlobalVariable( 6427 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, 6428 llvm::GlobalValue::WeakAnyLinkage, 6429 llvm::Constant::getNullValue(CGM.Int8Ty), Name); 6430 } 6431 6432 // Register the information for the entry associated with this target region. 6433 OffloadEntriesInfoManager.registerTargetRegionEntryInfo( 6434 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID, 6435 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion); 6436 } 6437 6438 /// discard all CompoundStmts intervening between two constructs 6439 static const Stmt *ignoreCompoundStmts(const Stmt *Body) { 6440 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) 6441 Body = CS->body_front(); 6442 6443 return Body; 6444 } 6445 6446 /// Emit the number of teams for a target directive. Inspect the num_teams 6447 /// clause associated with a teams construct combined or closely nested 6448 /// with the target directive. 6449 /// 6450 /// Emit a team of size one for directives such as 'target parallel' that 6451 /// have no associated teams construct. 6452 /// 6453 /// Otherwise, return nullptr. 6454 static llvm::Value * 6455 emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime, 6456 CodeGenFunction &CGF, 6457 const OMPExecutableDirective &D) { 6458 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the " 6459 "teams directive expected to be " 6460 "emitted only for the host!"); 6461 6462 CGBuilderTy &Bld = CGF.Builder; 6463 6464 // If the target directive is combined with a teams directive: 6465 // Return the value in the num_teams clause, if any. 6466 // Otherwise, return 0 to denote the runtime default. 6467 if (isOpenMPTeamsDirective(D.getDirectiveKind())) { 6468 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) { 6469 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF); 6470 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(), 6471 /*IgnoreResultAssign*/ true); 6472 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty, 6473 /*IsSigned=*/true); 6474 } 6475 6476 // The default value is 0. 6477 return Bld.getInt32(0); 6478 } 6479 6480 // If the target directive is combined with a parallel directive but not a 6481 // teams directive, start one team. 6482 if (isOpenMPParallelDirective(D.getDirectiveKind())) 6483 return Bld.getInt32(1); 6484 6485 // If the current target region has a teams region enclosed, we need to get 6486 // the number of teams to pass to the runtime function call. This is done 6487 // by generating the expression in a inlined region. This is required because 6488 // the expression is captured in the enclosing target environment when the 6489 // teams directive is not combined with target. 6490 6491 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target); 6492 6493 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>( 6494 ignoreCompoundStmts(CS.getCapturedStmt()))) { 6495 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) { 6496 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) { 6497 CGOpenMPInnerExprInfo CGInfo(CGF, CS); 6498 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 6499 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams()); 6500 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty, 6501 /*IsSigned=*/true); 6502 } 6503 6504 // If we have an enclosed teams directive but no num_teams clause we use 6505 // the default value 0. 6506 return Bld.getInt32(0); 6507 } 6508 } 6509 6510 // No teams associated with the directive. 6511 return nullptr; 6512 } 6513 6514 /// Emit the number of threads for a target directive. Inspect the 6515 /// thread_limit clause associated with a teams construct combined or closely 6516 /// nested with the target directive. 6517 /// 6518 /// Emit the num_threads clause for directives such as 'target parallel' that 6519 /// have no associated teams construct. 6520 /// 6521 /// Otherwise, return nullptr. 6522 static llvm::Value * 6523 emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime, 6524 CodeGenFunction &CGF, 6525 const OMPExecutableDirective &D) { 6526 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the " 6527 "teams directive expected to be " 6528 "emitted only for the host!"); 6529 6530 CGBuilderTy &Bld = CGF.Builder; 6531 6532 // 6533 // If the target directive is combined with a teams directive: 6534 // Return the value in the thread_limit clause, if any. 6535 // 6536 // If the target directive is combined with a parallel directive: 6537 // Return the value in the num_threads clause, if any. 6538 // 6539 // If both clauses are set, select the minimum of the two. 6540 // 6541 // If neither teams or parallel combined directives set the number of threads 6542 // in a team, return 0 to denote the runtime default. 6543 // 6544 // If this is not a teams directive return nullptr. 6545 6546 if (isOpenMPTeamsDirective(D.getDirectiveKind()) || 6547 isOpenMPParallelDirective(D.getDirectiveKind())) { 6548 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0); 6549 llvm::Value *NumThreadsVal = nullptr; 6550 llvm::Value *ThreadLimitVal = nullptr; 6551 6552 if (const auto *ThreadLimitClause = 6553 D.getSingleClause<OMPThreadLimitClause>()) { 6554 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF); 6555 llvm::Value *ThreadLimit = 6556 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(), 6557 /*IgnoreResultAssign*/ true); 6558 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, 6559 /*IsSigned=*/true); 6560 } 6561 6562 if (const auto *NumThreadsClause = 6563 D.getSingleClause<OMPNumThreadsClause>()) { 6564 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 6565 llvm::Value *NumThreads = 6566 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 6567 /*IgnoreResultAssign*/ true); 6568 NumThreadsVal = 6569 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true); 6570 } 6571 6572 // Select the lesser of thread_limit and num_threads. 6573 if (NumThreadsVal) 6574 ThreadLimitVal = ThreadLimitVal 6575 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal, 6576 ThreadLimitVal), 6577 NumThreadsVal, ThreadLimitVal) 6578 : NumThreadsVal; 6579 6580 // Set default value passed to the runtime if either teams or a target 6581 // parallel type directive is found but no clause is specified. 6582 if (!ThreadLimitVal) 6583 ThreadLimitVal = DefaultThreadLimitVal; 6584 6585 return ThreadLimitVal; 6586 } 6587 6588 // If the current target region has a teams region enclosed, we need to get 6589 // the thread limit to pass to the runtime function call. This is done 6590 // by generating the expression in a inlined region. This is required because 6591 // the expression is captured in the enclosing target environment when the 6592 // teams directive is not combined with target. 6593 6594 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target); 6595 6596 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>( 6597 ignoreCompoundStmts(CS.getCapturedStmt()))) { 6598 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) { 6599 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) { 6600 CGOpenMPInnerExprInfo CGInfo(CGF, CS); 6601 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 6602 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit()); 6603 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty, 6604 /*IsSigned=*/true); 6605 } 6606 6607 // If we have an enclosed teams directive but no thread_limit clause we 6608 // use the default value 0. 6609 return CGF.Builder.getInt32(0); 6610 } 6611 } 6612 6613 // No teams associated with the directive. 6614 return nullptr; 6615 } 6616 6617 namespace { 6618 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE(); 6619 6620 // Utility to handle information from clauses associated with a given 6621 // construct that use mappable expressions (e.g. 'map' clause, 'to' clause). 6622 // It provides a convenient interface to obtain the information and generate 6623 // code for that information. 6624 class MappableExprsHandler { 6625 public: 6626 /// Values for bit flags used to specify the mapping type for 6627 /// offloading. 6628 enum OpenMPOffloadMappingFlags : uint64_t { 6629 /// No flags 6630 OMP_MAP_NONE = 0x0, 6631 /// Allocate memory on the device and move data from host to device. 6632 OMP_MAP_TO = 0x01, 6633 /// Allocate memory on the device and move data from device to host. 6634 OMP_MAP_FROM = 0x02, 6635 /// Always perform the requested mapping action on the element, even 6636 /// if it was already mapped before. 6637 OMP_MAP_ALWAYS = 0x04, 6638 /// Delete the element from the device environment, ignoring the 6639 /// current reference count associated with the element. 6640 OMP_MAP_DELETE = 0x08, 6641 /// The element being mapped is a pointer-pointee pair; both the 6642 /// pointer and the pointee should be mapped. 6643 OMP_MAP_PTR_AND_OBJ = 0x10, 6644 /// This flags signals that the base address of an entry should be 6645 /// passed to the target kernel as an argument. 6646 OMP_MAP_TARGET_PARAM = 0x20, 6647 /// Signal that the runtime library has to return the device pointer 6648 /// in the current position for the data being mapped. Used when we have the 6649 /// use_device_ptr clause. 6650 OMP_MAP_RETURN_PARAM = 0x40, 6651 /// This flag signals that the reference being passed is a pointer to 6652 /// private data. 6653 OMP_MAP_PRIVATE = 0x80, 6654 /// Pass the element to the device by value. 6655 OMP_MAP_LITERAL = 0x100, 6656 /// Implicit map 6657 OMP_MAP_IMPLICIT = 0x200, 6658 /// The 16 MSBs of the flags indicate whether the entry is member of some 6659 /// struct/class. 6660 OMP_MAP_MEMBER_OF = 0xffff000000000000, 6661 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF), 6662 }; 6663 6664 /// Class that associates information with a base pointer to be passed to the 6665 /// runtime library. 6666 class BasePointerInfo { 6667 /// The base pointer. 6668 llvm::Value *Ptr = nullptr; 6669 /// The base declaration that refers to this device pointer, or null if 6670 /// there is none. 6671 const ValueDecl *DevPtrDecl = nullptr; 6672 6673 public: 6674 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr) 6675 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {} 6676 llvm::Value *operator*() const { return Ptr; } 6677 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; } 6678 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; } 6679 }; 6680 6681 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>; 6682 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>; 6683 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>; 6684 6685 /// Map between a struct and the its lowest & highest elements which have been 6686 /// mapped. 6687 /// [ValueDecl *] --> {LE(FieldIndex, Pointer), 6688 /// HE(FieldIndex, Pointer)} 6689 struct StructRangeInfoTy { 6690 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = { 6691 0, Address::invalid()}; 6692 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = { 6693 0, Address::invalid()}; 6694 Address Base = Address::invalid(); 6695 }; 6696 6697 private: 6698 /// Kind that defines how a device pointer has to be returned. 6699 struct MapInfo { 6700 OMPClauseMappableExprCommon::MappableExprComponentListRef Components; 6701 OpenMPMapClauseKind MapType = OMPC_MAP_unknown; 6702 ArrayRef<OpenMPMapModifierKind> MapModifiers; 6703 bool ReturnDevicePointer = false; 6704 bool IsImplicit = false; 6705 6706 MapInfo() = default; 6707 MapInfo( 6708 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 6709 OpenMPMapClauseKind MapType, 6710 ArrayRef<OpenMPMapModifierKind> MapModifiers, 6711 bool ReturnDevicePointer, bool IsImplicit) 6712 : Components(Components), MapType(MapType), MapModifiers(MapModifiers), 6713 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {} 6714 }; 6715 6716 /// If use_device_ptr is used on a pointer which is a struct member and there 6717 /// is no map information about it, then emission of that entry is deferred 6718 /// until the whole struct has been processed. 6719 struct DeferredDevicePtrEntryTy { 6720 const Expr *IE = nullptr; 6721 const ValueDecl *VD = nullptr; 6722 6723 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD) 6724 : IE(IE), VD(VD) {} 6725 }; 6726 6727 /// Directive from where the map clauses were extracted. 6728 const OMPExecutableDirective &CurDir; 6729 6730 /// Function the directive is being generated for. 6731 CodeGenFunction &CGF; 6732 6733 /// Set of all first private variables in the current directive. 6734 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls; 6735 6736 /// Map between device pointer declarations and their expression components. 6737 /// The key value for declarations in 'this' is null. 6738 llvm::DenseMap< 6739 const ValueDecl *, 6740 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>> 6741 DevPointersMap; 6742 6743 llvm::Value *getExprTypeSize(const Expr *E) const { 6744 QualType ExprTy = E->getType().getCanonicalType(); 6745 6746 // Reference types are ignored for mapping purposes. 6747 if (const auto *RefTy = ExprTy->getAs<ReferenceType>()) 6748 ExprTy = RefTy->getPointeeType().getCanonicalType(); 6749 6750 // Given that an array section is considered a built-in type, we need to 6751 // do the calculation based on the length of the section instead of relying 6752 // on CGF.getTypeSize(E->getType()). 6753 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) { 6754 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType( 6755 OAE->getBase()->IgnoreParenImpCasts()) 6756 .getCanonicalType(); 6757 6758 // If there is no length associated with the expression, that means we 6759 // are using the whole length of the base. 6760 if (!OAE->getLength() && OAE->getColonLoc().isValid()) 6761 return CGF.getTypeSize(BaseTy); 6762 6763 llvm::Value *ElemSize; 6764 if (const auto *PTy = BaseTy->getAs<PointerType>()) { 6765 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType()); 6766 } else { 6767 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr()); 6768 assert(ATy && "Expecting array type if not a pointer type."); 6769 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType()); 6770 } 6771 6772 // If we don't have a length at this point, that is because we have an 6773 // array section with a single element. 6774 if (!OAE->getLength()) 6775 return ElemSize; 6776 6777 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength()); 6778 LengthVal = 6779 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false); 6780 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize); 6781 } 6782 return CGF.getTypeSize(ExprTy); 6783 } 6784 6785 /// Return the corresponding bits for a given map clause modifier. Add 6786 /// a flag marking the map as a pointer if requested. Add a flag marking the 6787 /// map as the first one of a series of maps that relate to the same map 6788 /// expression. 6789 OpenMPOffloadMappingFlags getMapTypeBits( 6790 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers, 6791 bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const { 6792 OpenMPOffloadMappingFlags Bits = 6793 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE; 6794 switch (MapType) { 6795 case OMPC_MAP_alloc: 6796 case OMPC_MAP_release: 6797 // alloc and release is the default behavior in the runtime library, i.e. 6798 // if we don't pass any bits alloc/release that is what the runtime is 6799 // going to do. Therefore, we don't need to signal anything for these two 6800 // type modifiers. 6801 break; 6802 case OMPC_MAP_to: 6803 Bits |= OMP_MAP_TO; 6804 break; 6805 case OMPC_MAP_from: 6806 Bits |= OMP_MAP_FROM; 6807 break; 6808 case OMPC_MAP_tofrom: 6809 Bits |= OMP_MAP_TO | OMP_MAP_FROM; 6810 break; 6811 case OMPC_MAP_delete: 6812 Bits |= OMP_MAP_DELETE; 6813 break; 6814 case OMPC_MAP_unknown: 6815 llvm_unreachable("Unexpected map type!"); 6816 } 6817 if (AddPtrFlag) 6818 Bits |= OMP_MAP_PTR_AND_OBJ; 6819 if (AddIsTargetParamFlag) 6820 Bits |= OMP_MAP_TARGET_PARAM; 6821 if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always) 6822 != MapModifiers.end()) 6823 Bits |= OMP_MAP_ALWAYS; 6824 return Bits; 6825 } 6826 6827 /// Return true if the provided expression is a final array section. A 6828 /// final array section, is one whose length can't be proved to be one. 6829 bool isFinalArraySectionExpression(const Expr *E) const { 6830 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 6831 6832 // It is not an array section and therefore not a unity-size one. 6833 if (!OASE) 6834 return false; 6835 6836 // An array section with no colon always refer to a single element. 6837 if (OASE->getColonLoc().isInvalid()) 6838 return false; 6839 6840 const Expr *Length = OASE->getLength(); 6841 6842 // If we don't have a length we have to check if the array has size 1 6843 // for this dimension. Also, we should always expect a length if the 6844 // base type is pointer. 6845 if (!Length) { 6846 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType( 6847 OASE->getBase()->IgnoreParenImpCasts()) 6848 .getCanonicalType(); 6849 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 6850 return ATy->getSize().getSExtValue() != 1; 6851 // If we don't have a constant dimension length, we have to consider 6852 // the current section as having any size, so it is not necessarily 6853 // unitary. If it happen to be unity size, that's user fault. 6854 return true; 6855 } 6856 6857 // Check if the length evaluates to 1. 6858 Expr::EvalResult Result; 6859 if (!Length->EvaluateAsInt(Result, CGF.getContext())) 6860 return true; // Can have more that size 1. 6861 6862 llvm::APSInt ConstLength = Result.Val.getInt(); 6863 return ConstLength.getSExtValue() != 1; 6864 } 6865 6866 /// Generate the base pointers, section pointers, sizes and map type 6867 /// bits for the provided map type, map modifier, and expression components. 6868 /// \a IsFirstComponent should be set to true if the provided set of 6869 /// components is the first associated with a capture. 6870 void generateInfoForComponentList( 6871 OpenMPMapClauseKind MapType, 6872 ArrayRef<OpenMPMapModifierKind> MapModifiers, 6873 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 6874 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers, 6875 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types, 6876 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList, 6877 bool IsImplicit, 6878 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef> 6879 OverlappedElements = llvm::None) const { 6880 // The following summarizes what has to be generated for each map and the 6881 // types below. The generated information is expressed in this order: 6882 // base pointer, section pointer, size, flags 6883 // (to add to the ones that come from the map type and modifier). 6884 // 6885 // double d; 6886 // int i[100]; 6887 // float *p; 6888 // 6889 // struct S1 { 6890 // int i; 6891 // float f[50]; 6892 // } 6893 // struct S2 { 6894 // int i; 6895 // float f[50]; 6896 // S1 s; 6897 // double *p; 6898 // struct S2 *ps; 6899 // } 6900 // S2 s; 6901 // S2 *ps; 6902 // 6903 // map(d) 6904 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM 6905 // 6906 // map(i) 6907 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM 6908 // 6909 // map(i[1:23]) 6910 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM 6911 // 6912 // map(p) 6913 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM 6914 // 6915 // map(p[1:24]) 6916 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM 6917 // 6918 // map(s) 6919 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM 6920 // 6921 // map(s.i) 6922 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM 6923 // 6924 // map(s.s.f) 6925 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM 6926 // 6927 // map(s.p) 6928 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM 6929 // 6930 // map(to: s.p[:22]) 6931 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*) 6932 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**) 6933 // &(s.p), &(s.p[0]), 22*sizeof(double), 6934 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***) 6935 // (*) alloc space for struct members, only this is a target parameter 6936 // (**) map the pointer (nothing to be mapped in this example) (the compiler 6937 // optimizes this entry out, same in the examples below) 6938 // (***) map the pointee (map: to) 6939 // 6940 // map(s.ps) 6941 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM 6942 // 6943 // map(from: s.ps->s.i) 6944 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM 6945 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1) 6946 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM 6947 // 6948 // map(to: s.ps->ps) 6949 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM 6950 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1) 6951 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO 6952 // 6953 // map(s.ps->ps->ps) 6954 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM 6955 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1) 6956 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ 6957 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM 6958 // 6959 // map(to: s.ps->ps->s.f[:22]) 6960 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM 6961 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1) 6962 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ 6963 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO 6964 // 6965 // map(ps) 6966 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM 6967 // 6968 // map(ps->i) 6969 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM 6970 // 6971 // map(ps->s.f) 6972 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM 6973 // 6974 // map(from: ps->p) 6975 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM 6976 // 6977 // map(to: ps->p[:22]) 6978 // ps, &(ps->p), sizeof(double*), TARGET_PARAM 6979 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1) 6980 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO 6981 // 6982 // map(ps->ps) 6983 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM 6984 // 6985 // map(from: ps->ps->s.i) 6986 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM 6987 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1) 6988 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM 6989 // 6990 // map(from: ps->ps->ps) 6991 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM 6992 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1) 6993 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM 6994 // 6995 // map(ps->ps->ps->ps) 6996 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM 6997 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1) 6998 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ 6999 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM 7000 // 7001 // map(to: ps->ps->ps->s.f[:22]) 7002 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM 7003 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1) 7004 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ 7005 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO 7006 // 7007 // map(to: s.f[:22]) map(from: s.p[:33]) 7008 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) + 7009 // sizeof(double*) (**), TARGET_PARAM 7010 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO 7011 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) 7012 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM 7013 // (*) allocate contiguous space needed to fit all mapped members even if 7014 // we allocate space for members not mapped (in this example, 7015 // s.f[22..49] and s.s are not mapped, yet we must allocate space for 7016 // them as well because they fall between &s.f[0] and &s.p) 7017 // 7018 // map(from: s.f[:22]) map(to: ps->p[:33]) 7019 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM 7020 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM 7021 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*) 7022 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO 7023 // (*) the struct this entry pertains to is the 2nd element in the list of 7024 // arguments, hence MEMBER_OF(2) 7025 // 7026 // map(from: s.f[:22], s.s) map(to: ps->p[:33]) 7027 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM 7028 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM 7029 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM 7030 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM 7031 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*) 7032 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO 7033 // (*) the struct this entry pertains to is the 4th element in the list 7034 // of arguments, hence MEMBER_OF(4) 7035 7036 // Track if the map information being generated is the first for a capture. 7037 bool IsCaptureFirstInfo = IsFirstComponentList; 7038 bool IsLink = false; // Is this variable a "declare target link"? 7039 7040 // Scan the components from the base to the complete expression. 7041 auto CI = Components.rbegin(); 7042 auto CE = Components.rend(); 7043 auto I = CI; 7044 7045 // Track if the map information being generated is the first for a list of 7046 // components. 7047 bool IsExpressionFirstInfo = true; 7048 Address BP = Address::invalid(); 7049 const Expr *AssocExpr = I->getAssociatedExpression(); 7050 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr); 7051 const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr); 7052 7053 if (isa<MemberExpr>(AssocExpr)) { 7054 // The base is the 'this' pointer. The content of the pointer is going 7055 // to be the base of the field being mapped. 7056 BP = CGF.LoadCXXThisAddress(); 7057 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) || 7058 (OASE && 7059 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) { 7060 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress(); 7061 } else { 7062 // The base is the reference to the variable. 7063 // BP = &Var. 7064 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress(); 7065 if (const auto *VD = 7066 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) { 7067 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 7068 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 7069 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) { 7070 IsLink = true; 7071 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD); 7072 } 7073 } 7074 7075 // If the variable is a pointer and is being dereferenced (i.e. is not 7076 // the last component), the base has to be the pointer itself, not its 7077 // reference. References are ignored for mapping purposes. 7078 QualType Ty = 7079 I->getAssociatedDeclaration()->getType().getNonReferenceType(); 7080 if (Ty->isAnyPointerType() && std::next(I) != CE) { 7081 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>()); 7082 7083 // We do not need to generate individual map information for the 7084 // pointer, it can be associated with the combined storage. 7085 ++I; 7086 } 7087 } 7088 7089 // Track whether a component of the list should be marked as MEMBER_OF some 7090 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry 7091 // in a component list should be marked as MEMBER_OF, all subsequent entries 7092 // do not belong to the base struct. E.g. 7093 // struct S2 s; 7094 // s.ps->ps->ps->f[:] 7095 // (1) (2) (3) (4) 7096 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a 7097 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3) 7098 // is the pointee of ps(2) which is not member of struct s, so it should not 7099 // be marked as such (it is still PTR_AND_OBJ). 7100 // The variable is initialized to false so that PTR_AND_OBJ entries which 7101 // are not struct members are not considered (e.g. array of pointers to 7102 // data). 7103 bool ShouldBeMemberOf = false; 7104 7105 // Variable keeping track of whether or not we have encountered a component 7106 // in the component list which is a member expression. Useful when we have a 7107 // pointer or a final array section, in which case it is the previous 7108 // component in the list which tells us whether we have a member expression. 7109 // E.g. X.f[:] 7110 // While processing the final array section "[:]" it is "f" which tells us 7111 // whether we are dealing with a member of a declared struct. 7112 const MemberExpr *EncounteredME = nullptr; 7113 7114 for (; I != CE; ++I) { 7115 // If the current component is member of a struct (parent struct) mark it. 7116 if (!EncounteredME) { 7117 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression()); 7118 // If we encounter a PTR_AND_OBJ entry from now on it should be marked 7119 // as MEMBER_OF the parent struct. 7120 if (EncounteredME) 7121 ShouldBeMemberOf = true; 7122 } 7123 7124 auto Next = std::next(I); 7125 7126 // We need to generate the addresses and sizes if this is the last 7127 // component, if the component is a pointer or if it is an array section 7128 // whose length can't be proved to be one. If this is a pointer, it 7129 // becomes the base address for the following components. 7130 7131 // A final array section, is one whose length can't be proved to be one. 7132 bool IsFinalArraySection = 7133 isFinalArraySectionExpression(I->getAssociatedExpression()); 7134 7135 // Get information on whether the element is a pointer. Have to do a 7136 // special treatment for array sections given that they are built-in 7137 // types. 7138 const auto *OASE = 7139 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression()); 7140 bool IsPointer = 7141 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE) 7142 .getCanonicalType() 7143 ->isAnyPointerType()) || 7144 I->getAssociatedExpression()->getType()->isAnyPointerType(); 7145 7146 if (Next == CE || IsPointer || IsFinalArraySection) { 7147 // If this is not the last component, we expect the pointer to be 7148 // associated with an array expression or member expression. 7149 assert((Next == CE || 7150 isa<MemberExpr>(Next->getAssociatedExpression()) || 7151 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) || 7152 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) && 7153 "Unexpected expression"); 7154 7155 Address LB = 7156 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress(); 7157 7158 // If this component is a pointer inside the base struct then we don't 7159 // need to create any entry for it - it will be combined with the object 7160 // it is pointing to into a single PTR_AND_OBJ entry. 7161 bool IsMemberPointer = 7162 IsPointer && EncounteredME && 7163 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) == 7164 EncounteredME); 7165 if (!OverlappedElements.empty()) { 7166 // Handle base element with the info for overlapped elements. 7167 assert(!PartialStruct.Base.isValid() && "The base element is set."); 7168 assert(Next == CE && 7169 "Expected last element for the overlapped elements."); 7170 assert(!IsPointer && 7171 "Unexpected base element with the pointer type."); 7172 // Mark the whole struct as the struct that requires allocation on the 7173 // device. 7174 PartialStruct.LowestElem = {0, LB}; 7175 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars( 7176 I->getAssociatedExpression()->getType()); 7177 Address HB = CGF.Builder.CreateConstGEP( 7178 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB, 7179 CGF.VoidPtrTy), 7180 TypeSize.getQuantity() - 1); 7181 PartialStruct.HighestElem = { 7182 std::numeric_limits<decltype( 7183 PartialStruct.HighestElem.first)>::max(), 7184 HB}; 7185 PartialStruct.Base = BP; 7186 // Emit data for non-overlapped data. 7187 OpenMPOffloadMappingFlags Flags = 7188 OMP_MAP_MEMBER_OF | 7189 getMapTypeBits(MapType, MapModifiers, IsImplicit, 7190 /*AddPtrFlag=*/false, 7191 /*AddIsTargetParamFlag=*/false); 7192 LB = BP; 7193 llvm::Value *Size = nullptr; 7194 // Do bitcopy of all non-overlapped structure elements. 7195 for (OMPClauseMappableExprCommon::MappableExprComponentListRef 7196 Component : OverlappedElements) { 7197 Address ComponentLB = Address::invalid(); 7198 for (const OMPClauseMappableExprCommon::MappableComponent &MC : 7199 Component) { 7200 if (MC.getAssociatedDeclaration()) { 7201 ComponentLB = 7202 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression()) 7203 .getAddress(); 7204 Size = CGF.Builder.CreatePtrDiff( 7205 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()), 7206 CGF.EmitCastToVoidPtr(LB.getPointer())); 7207 break; 7208 } 7209 } 7210 BasePointers.push_back(BP.getPointer()); 7211 Pointers.push_back(LB.getPointer()); 7212 Sizes.push_back(Size); 7213 Types.push_back(Flags); 7214 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1); 7215 } 7216 BasePointers.push_back(BP.getPointer()); 7217 Pointers.push_back(LB.getPointer()); 7218 Size = CGF.Builder.CreatePtrDiff( 7219 CGF.EmitCastToVoidPtr( 7220 CGF.Builder.CreateConstGEP(HB, 1).getPointer()), 7221 CGF.EmitCastToVoidPtr(LB.getPointer())); 7222 Sizes.push_back(Size); 7223 Types.push_back(Flags); 7224 break; 7225 } 7226 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression()); 7227 if (!IsMemberPointer) { 7228 BasePointers.push_back(BP.getPointer()); 7229 Pointers.push_back(LB.getPointer()); 7230 Sizes.push_back(Size); 7231 7232 // We need to add a pointer flag for each map that comes from the 7233 // same expression except for the first one. We also need to signal 7234 // this map is the first one that relates with the current capture 7235 // (there is a set of entries for each capture). 7236 OpenMPOffloadMappingFlags Flags = getMapTypeBits( 7237 MapType, MapModifiers, IsImplicit, 7238 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink); 7239 7240 if (!IsExpressionFirstInfo) { 7241 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well, 7242 // then we reset the TO/FROM/ALWAYS/DELETE flags. 7243 if (IsPointer) 7244 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS | 7245 OMP_MAP_DELETE); 7246 7247 if (ShouldBeMemberOf) { 7248 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag 7249 // should be later updated with the correct value of MEMBER_OF. 7250 Flags |= OMP_MAP_MEMBER_OF; 7251 // From now on, all subsequent PTR_AND_OBJ entries should not be 7252 // marked as MEMBER_OF. 7253 ShouldBeMemberOf = false; 7254 } 7255 } 7256 7257 Types.push_back(Flags); 7258 } 7259 7260 // If we have encountered a member expression so far, keep track of the 7261 // mapped member. If the parent is "*this", then the value declaration 7262 // is nullptr. 7263 if (EncounteredME) { 7264 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl()); 7265 unsigned FieldIndex = FD->getFieldIndex(); 7266 7267 // Update info about the lowest and highest elements for this struct 7268 if (!PartialStruct.Base.isValid()) { 7269 PartialStruct.LowestElem = {FieldIndex, LB}; 7270 PartialStruct.HighestElem = {FieldIndex, LB}; 7271 PartialStruct.Base = BP; 7272 } else if (FieldIndex < PartialStruct.LowestElem.first) { 7273 PartialStruct.LowestElem = {FieldIndex, LB}; 7274 } else if (FieldIndex > PartialStruct.HighestElem.first) { 7275 PartialStruct.HighestElem = {FieldIndex, LB}; 7276 } 7277 } 7278 7279 // If we have a final array section, we are done with this expression. 7280 if (IsFinalArraySection) 7281 break; 7282 7283 // The pointer becomes the base for the next element. 7284 if (Next != CE) 7285 BP = LB; 7286 7287 IsExpressionFirstInfo = false; 7288 IsCaptureFirstInfo = false; 7289 } 7290 } 7291 } 7292 7293 /// Return the adjusted map modifiers if the declaration a capture refers to 7294 /// appears in a first-private clause. This is expected to be used only with 7295 /// directives that start with 'target'. 7296 MappableExprsHandler::OpenMPOffloadMappingFlags 7297 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const { 7298 assert(Cap.capturesVariable() && "Expected capture by reference only!"); 7299 7300 // A first private variable captured by reference will use only the 7301 // 'private ptr' and 'map to' flag. Return the right flags if the captured 7302 // declaration is known as first-private in this handler. 7303 if (FirstPrivateDecls.count(Cap.getCapturedVar())) { 7304 if (Cap.getCapturedVar()->getType().isConstant(CGF.getContext()) && 7305 Cap.getCaptureKind() == CapturedStmt::VCK_ByRef) 7306 return MappableExprsHandler::OMP_MAP_ALWAYS | 7307 MappableExprsHandler::OMP_MAP_TO; 7308 return MappableExprsHandler::OMP_MAP_PRIVATE | 7309 MappableExprsHandler::OMP_MAP_TO; 7310 } 7311 return MappableExprsHandler::OMP_MAP_TO | 7312 MappableExprsHandler::OMP_MAP_FROM; 7313 } 7314 7315 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) { 7316 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits. 7317 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1) 7318 << 48); 7319 } 7320 7321 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags, 7322 OpenMPOffloadMappingFlags MemberOfFlag) { 7323 // If the entry is PTR_AND_OBJ but has not been marked with the special 7324 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be 7325 // marked as MEMBER_OF. 7326 if ((Flags & OMP_MAP_PTR_AND_OBJ) && 7327 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF)) 7328 return; 7329 7330 // Reset the placeholder value to prepare the flag for the assignment of the 7331 // proper MEMBER_OF value. 7332 Flags &= ~OMP_MAP_MEMBER_OF; 7333 Flags |= MemberOfFlag; 7334 } 7335 7336 void getPlainLayout(const CXXRecordDecl *RD, 7337 llvm::SmallVectorImpl<const FieldDecl *> &Layout, 7338 bool AsBase) const { 7339 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD); 7340 7341 llvm::StructType *St = 7342 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType(); 7343 7344 unsigned NumElements = St->getNumElements(); 7345 llvm::SmallVector< 7346 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4> 7347 RecordLayout(NumElements); 7348 7349 // Fill bases. 7350 for (const auto &I : RD->bases()) { 7351 if (I.isVirtual()) 7352 continue; 7353 const auto *Base = I.getType()->getAsCXXRecordDecl(); 7354 // Ignore empty bases. 7355 if (Base->isEmpty() || CGF.getContext() 7356 .getASTRecordLayout(Base) 7357 .getNonVirtualSize() 7358 .isZero()) 7359 continue; 7360 7361 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base); 7362 RecordLayout[FieldIndex] = Base; 7363 } 7364 // Fill in virtual bases. 7365 for (const auto &I : RD->vbases()) { 7366 const auto *Base = I.getType()->getAsCXXRecordDecl(); 7367 // Ignore empty bases. 7368 if (Base->isEmpty()) 7369 continue; 7370 unsigned FieldIndex = RL.getVirtualBaseIndex(Base); 7371 if (RecordLayout[FieldIndex]) 7372 continue; 7373 RecordLayout[FieldIndex] = Base; 7374 } 7375 // Fill in all the fields. 7376 assert(!RD->isUnion() && "Unexpected union."); 7377 for (const auto *Field : RD->fields()) { 7378 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we 7379 // will fill in later.) 7380 if (!Field->isBitField()) { 7381 unsigned FieldIndex = RL.getLLVMFieldNo(Field); 7382 RecordLayout[FieldIndex] = Field; 7383 } 7384 } 7385 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *> 7386 &Data : RecordLayout) { 7387 if (Data.isNull()) 7388 continue; 7389 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>()) 7390 getPlainLayout(Base, Layout, /*AsBase=*/true); 7391 else 7392 Layout.push_back(Data.get<const FieldDecl *>()); 7393 } 7394 } 7395 7396 public: 7397 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF) 7398 : CurDir(Dir), CGF(CGF) { 7399 // Extract firstprivate clause information. 7400 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>()) 7401 for (const auto *D : C->varlists()) 7402 FirstPrivateDecls.insert( 7403 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl()); 7404 // Extract device pointer clause information. 7405 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>()) 7406 for (auto L : C->component_lists()) 7407 DevPointersMap[L.first].push_back(L.second); 7408 } 7409 7410 /// Generate code for the combined entry if we have a partially mapped struct 7411 /// and take care of the mapping flags of the arguments corresponding to 7412 /// individual struct members. 7413 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers, 7414 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes, 7415 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes, 7416 const StructRangeInfoTy &PartialStruct) const { 7417 // Base is the base of the struct 7418 BasePointers.push_back(PartialStruct.Base.getPointer()); 7419 // Pointer is the address of the lowest element 7420 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer(); 7421 Pointers.push_back(LB); 7422 // Size is (addr of {highest+1} element) - (addr of lowest element) 7423 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer(); 7424 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1); 7425 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy); 7426 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy); 7427 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr); 7428 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy, 7429 /*isSinged=*/false); 7430 Sizes.push_back(Size); 7431 // Map type is always TARGET_PARAM 7432 Types.push_back(OMP_MAP_TARGET_PARAM); 7433 // Remove TARGET_PARAM flag from the first element 7434 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM; 7435 7436 // All other current entries will be MEMBER_OF the combined entry 7437 // (except for PTR_AND_OBJ entries which do not have a placeholder value 7438 // 0xFFFF in the MEMBER_OF field). 7439 OpenMPOffloadMappingFlags MemberOfFlag = 7440 getMemberOfFlag(BasePointers.size() - 1); 7441 for (auto &M : CurTypes) 7442 setCorrectMemberOfFlag(M, MemberOfFlag); 7443 } 7444 7445 /// Generate all the base pointers, section pointers, sizes and map 7446 /// types for the extracted mappable expressions. Also, for each item that 7447 /// relates with a device pointer, a pair of the relevant declaration and 7448 /// index where it occurs is appended to the device pointers info array. 7449 void generateAllInfo(MapBaseValuesArrayTy &BasePointers, 7450 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes, 7451 MapFlagsArrayTy &Types) const { 7452 // We have to process the component lists that relate with the same 7453 // declaration in a single chunk so that we can generate the map flags 7454 // correctly. Therefore, we organize all lists in a map. 7455 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info; 7456 7457 // Helper function to fill the information map for the different supported 7458 // clauses. 7459 auto &&InfoGen = [&Info]( 7460 const ValueDecl *D, 7461 OMPClauseMappableExprCommon::MappableExprComponentListRef L, 7462 OpenMPMapClauseKind MapType, 7463 ArrayRef<OpenMPMapModifierKind> MapModifiers, 7464 bool ReturnDevicePointer, bool IsImplicit) { 7465 const ValueDecl *VD = 7466 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr; 7467 Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer, 7468 IsImplicit); 7469 }; 7470 7471 // FIXME: MSVC 2013 seems to require this-> to find member CurDir. 7472 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) 7473 for (const auto &L : C->component_lists()) { 7474 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(), 7475 /*ReturnDevicePointer=*/false, C->isImplicit()); 7476 } 7477 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>()) 7478 for (const auto &L : C->component_lists()) { 7479 InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None, 7480 /*ReturnDevicePointer=*/false, C->isImplicit()); 7481 } 7482 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>()) 7483 for (const auto &L : C->component_lists()) { 7484 InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None, 7485 /*ReturnDevicePointer=*/false, C->isImplicit()); 7486 } 7487 7488 // Look at the use_device_ptr clause information and mark the existing map 7489 // entries as such. If there is no map information for an entry in the 7490 // use_device_ptr list, we create one with map type 'alloc' and zero size 7491 // section. It is the user fault if that was not mapped before. If there is 7492 // no map information and the pointer is a struct member, then we defer the 7493 // emission of that entry until the whole struct has been processed. 7494 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>> 7495 DeferredInfo; 7496 7497 // FIXME: MSVC 2013 seems to require this-> to find member CurDir. 7498 for (const auto *C : 7499 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) { 7500 for (const auto &L : C->component_lists()) { 7501 assert(!L.second.empty() && "Not expecting empty list of components!"); 7502 const ValueDecl *VD = L.second.back().getAssociatedDeclaration(); 7503 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 7504 const Expr *IE = L.second.back().getAssociatedExpression(); 7505 // If the first component is a member expression, we have to look into 7506 // 'this', which maps to null in the map of map information. Otherwise 7507 // look directly for the information. 7508 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD); 7509 7510 // We potentially have map information for this declaration already. 7511 // Look for the first set of components that refer to it. 7512 if (It != Info.end()) { 7513 auto CI = std::find_if( 7514 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) { 7515 return MI.Components.back().getAssociatedDeclaration() == VD; 7516 }); 7517 // If we found a map entry, signal that the pointer has to be returned 7518 // and move on to the next declaration. 7519 if (CI != It->second.end()) { 7520 CI->ReturnDevicePointer = true; 7521 continue; 7522 } 7523 } 7524 7525 // We didn't find any match in our map information - generate a zero 7526 // size array section - if the pointer is a struct member we defer this 7527 // action until the whole struct has been processed. 7528 // FIXME: MSVC 2013 seems to require this-> to find member CGF. 7529 if (isa<MemberExpr>(IE)) { 7530 // Insert the pointer into Info to be processed by 7531 // generateInfoForComponentList. Because it is a member pointer 7532 // without a pointee, no entry will be generated for it, therefore 7533 // we need to generate one after the whole struct has been processed. 7534 // Nonetheless, generateInfoForComponentList must be called to take 7535 // the pointer into account for the calculation of the range of the 7536 // partial struct. 7537 InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None, 7538 /*ReturnDevicePointer=*/false, C->isImplicit()); 7539 DeferredInfo[nullptr].emplace_back(IE, VD); 7540 } else { 7541 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar( 7542 this->CGF.EmitLValue(IE), IE->getExprLoc()); 7543 BasePointers.emplace_back(Ptr, VD); 7544 Pointers.push_back(Ptr); 7545 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy)); 7546 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM); 7547 } 7548 } 7549 } 7550 7551 for (const auto &M : Info) { 7552 // We need to know when we generate information for the first component 7553 // associated with a capture, because the mapping flags depend on it. 7554 bool IsFirstComponentList = true; 7555 7556 // Temporary versions of arrays 7557 MapBaseValuesArrayTy CurBasePointers; 7558 MapValuesArrayTy CurPointers; 7559 MapValuesArrayTy CurSizes; 7560 MapFlagsArrayTy CurTypes; 7561 StructRangeInfoTy PartialStruct; 7562 7563 for (const MapInfo &L : M.second) { 7564 assert(!L.Components.empty() && 7565 "Not expecting declaration with no component lists."); 7566 7567 // Remember the current base pointer index. 7568 unsigned CurrentBasePointersIdx = CurBasePointers.size(); 7569 // FIXME: MSVC 2013 seems to require this-> to find the member method. 7570 this->generateInfoForComponentList( 7571 L.MapType, L.MapModifiers, L.Components, CurBasePointers, 7572 CurPointers, CurSizes, CurTypes, PartialStruct, 7573 IsFirstComponentList, L.IsImplicit); 7574 7575 // If this entry relates with a device pointer, set the relevant 7576 // declaration and add the 'return pointer' flag. 7577 if (L.ReturnDevicePointer) { 7578 assert(CurBasePointers.size() > CurrentBasePointersIdx && 7579 "Unexpected number of mapped base pointers."); 7580 7581 const ValueDecl *RelevantVD = 7582 L.Components.back().getAssociatedDeclaration(); 7583 assert(RelevantVD && 7584 "No relevant declaration related with device pointer??"); 7585 7586 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD); 7587 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM; 7588 } 7589 IsFirstComponentList = false; 7590 } 7591 7592 // Append any pending zero-length pointers which are struct members and 7593 // used with use_device_ptr. 7594 auto CI = DeferredInfo.find(M.first); 7595 if (CI != DeferredInfo.end()) { 7596 for (const DeferredDevicePtrEntryTy &L : CI->second) { 7597 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer(); 7598 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar( 7599 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc()); 7600 CurBasePointers.emplace_back(BasePtr, L.VD); 7601 CurPointers.push_back(Ptr); 7602 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy)); 7603 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder 7604 // value MEMBER_OF=FFFF so that the entry is later updated with the 7605 // correct value of MEMBER_OF. 7606 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM | 7607 OMP_MAP_MEMBER_OF); 7608 } 7609 } 7610 7611 // If there is an entry in PartialStruct it means we have a struct with 7612 // individual members mapped. Emit an extra combined entry. 7613 if (PartialStruct.Base.isValid()) 7614 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes, 7615 PartialStruct); 7616 7617 // We need to append the results of this capture to what we already have. 7618 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end()); 7619 Pointers.append(CurPointers.begin(), CurPointers.end()); 7620 Sizes.append(CurSizes.begin(), CurSizes.end()); 7621 Types.append(CurTypes.begin(), CurTypes.end()); 7622 } 7623 } 7624 7625 /// Emit capture info for lambdas for variables captured by reference. 7626 void generateInfoForLambdaCaptures( 7627 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers, 7628 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes, 7629 MapFlagsArrayTy &Types, 7630 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const { 7631 const auto *RD = VD->getType() 7632 .getCanonicalType() 7633 .getNonReferenceType() 7634 ->getAsCXXRecordDecl(); 7635 if (!RD || !RD->isLambda()) 7636 return; 7637 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD)); 7638 LValue VDLVal = CGF.MakeAddrLValue( 7639 VDAddr, VD->getType().getCanonicalType().getNonReferenceType()); 7640 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 7641 FieldDecl *ThisCapture = nullptr; 7642 RD->getCaptureFields(Captures, ThisCapture); 7643 if (ThisCapture) { 7644 LValue ThisLVal = 7645 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture); 7646 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture); 7647 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer()); 7648 BasePointers.push_back(ThisLVal.getPointer()); 7649 Pointers.push_back(ThisLValVal.getPointer()); 7650 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy)); 7651 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL | 7652 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT); 7653 } 7654 for (const LambdaCapture &LC : RD->captures()) { 7655 if (LC.getCaptureKind() != LCK_ByRef) 7656 continue; 7657 const VarDecl *VD = LC.getCapturedVar(); 7658 auto It = Captures.find(VD); 7659 assert(It != Captures.end() && "Found lambda capture without field."); 7660 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second); 7661 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second); 7662 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer()); 7663 BasePointers.push_back(VarLVal.getPointer()); 7664 Pointers.push_back(VarLValVal.getPointer()); 7665 Sizes.push_back(CGF.getTypeSize( 7666 VD->getType().getCanonicalType().getNonReferenceType())); 7667 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL | 7668 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT); 7669 } 7670 } 7671 7672 /// Set correct indices for lambdas captures. 7673 void adjustMemberOfForLambdaCaptures( 7674 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers, 7675 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers, 7676 MapFlagsArrayTy &Types) const { 7677 for (unsigned I = 0, E = Types.size(); I < E; ++I) { 7678 // Set correct member_of idx for all implicit lambda captures. 7679 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL | 7680 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT)) 7681 continue; 7682 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]); 7683 assert(BasePtr && "Unable to find base lambda address."); 7684 int TgtIdx = -1; 7685 for (unsigned J = I; J > 0; --J) { 7686 unsigned Idx = J - 1; 7687 if (Pointers[Idx] != BasePtr) 7688 continue; 7689 TgtIdx = Idx; 7690 break; 7691 } 7692 assert(TgtIdx != -1 && "Unable to find parent lambda."); 7693 // All other current entries will be MEMBER_OF the combined entry 7694 // (except for PTR_AND_OBJ entries which do not have a placeholder value 7695 // 0xFFFF in the MEMBER_OF field). 7696 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx); 7697 setCorrectMemberOfFlag(Types[I], MemberOfFlag); 7698 } 7699 } 7700 7701 /// Generate the base pointers, section pointers, sizes and map types 7702 /// associated to a given capture. 7703 void generateInfoForCapture(const CapturedStmt::Capture *Cap, 7704 llvm::Value *Arg, 7705 MapBaseValuesArrayTy &BasePointers, 7706 MapValuesArrayTy &Pointers, 7707 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types, 7708 StructRangeInfoTy &PartialStruct) const { 7709 assert(!Cap->capturesVariableArrayType() && 7710 "Not expecting to generate map info for a variable array type!"); 7711 7712 // We need to know when we generating information for the first component 7713 const ValueDecl *VD = Cap->capturesThis() 7714 ? nullptr 7715 : Cap->getCapturedVar()->getCanonicalDecl(); 7716 7717 // If this declaration appears in a is_device_ptr clause we just have to 7718 // pass the pointer by value. If it is a reference to a declaration, we just 7719 // pass its value. 7720 if (DevPointersMap.count(VD)) { 7721 BasePointers.emplace_back(Arg, VD); 7722 Pointers.push_back(Arg); 7723 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy)); 7724 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM); 7725 return; 7726 } 7727 7728 using MapData = 7729 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef, 7730 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>; 7731 SmallVector<MapData, 4> DeclComponentLists; 7732 // FIXME: MSVC 2013 seems to require this-> to find member CurDir. 7733 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) { 7734 for (const auto &L : C->decl_component_lists(VD)) { 7735 assert(L.first == VD && 7736 "We got information for the wrong declaration??"); 7737 assert(!L.second.empty() && 7738 "Not expecting declaration with no component lists."); 7739 DeclComponentLists.emplace_back(L.second, C->getMapType(), 7740 C->getMapTypeModifiers(), 7741 C->isImplicit()); 7742 } 7743 } 7744 7745 // Find overlapping elements (including the offset from the base element). 7746 llvm::SmallDenseMap< 7747 const MapData *, 7748 llvm::SmallVector< 7749 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>, 7750 4> 7751 OverlappedData; 7752 size_t Count = 0; 7753 for (const MapData &L : DeclComponentLists) { 7754 OMPClauseMappableExprCommon::MappableExprComponentListRef Components; 7755 OpenMPMapClauseKind MapType; 7756 ArrayRef<OpenMPMapModifierKind> MapModifiers; 7757 bool IsImplicit; 7758 std::tie(Components, MapType, MapModifiers, IsImplicit) = L; 7759 ++Count; 7760 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) { 7761 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1; 7762 std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1; 7763 auto CI = Components.rbegin(); 7764 auto CE = Components.rend(); 7765 auto SI = Components1.rbegin(); 7766 auto SE = Components1.rend(); 7767 for (; CI != CE && SI != SE; ++CI, ++SI) { 7768 if (CI->getAssociatedExpression()->getStmtClass() != 7769 SI->getAssociatedExpression()->getStmtClass()) 7770 break; 7771 // Are we dealing with different variables/fields? 7772 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 7773 break; 7774 } 7775 // Found overlapping if, at least for one component, reached the head of 7776 // the components list. 7777 if (CI == CE || SI == SE) { 7778 assert((CI != CE || SI != SE) && 7779 "Unexpected full match of the mapping components."); 7780 const MapData &BaseData = CI == CE ? L : L1; 7781 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData = 7782 SI == SE ? Components : Components1; 7783 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData); 7784 OverlappedElements.getSecond().push_back(SubData); 7785 } 7786 } 7787 } 7788 // Sort the overlapped elements for each item. 7789 llvm::SmallVector<const FieldDecl *, 4> Layout; 7790 if (!OverlappedData.empty()) { 7791 if (const auto *CRD = 7792 VD->getType().getCanonicalType()->getAsCXXRecordDecl()) 7793 getPlainLayout(CRD, Layout, /*AsBase=*/false); 7794 else { 7795 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl(); 7796 Layout.append(RD->field_begin(), RD->field_end()); 7797 } 7798 } 7799 for (auto &Pair : OverlappedData) { 7800 llvm::sort( 7801 Pair.getSecond(), 7802 [&Layout]( 7803 OMPClauseMappableExprCommon::MappableExprComponentListRef First, 7804 OMPClauseMappableExprCommon::MappableExprComponentListRef 7805 Second) { 7806 auto CI = First.rbegin(); 7807 auto CE = First.rend(); 7808 auto SI = Second.rbegin(); 7809 auto SE = Second.rend(); 7810 for (; CI != CE && SI != SE; ++CI, ++SI) { 7811 if (CI->getAssociatedExpression()->getStmtClass() != 7812 SI->getAssociatedExpression()->getStmtClass()) 7813 break; 7814 // Are we dealing with different variables/fields? 7815 if (CI->getAssociatedDeclaration() != 7816 SI->getAssociatedDeclaration()) 7817 break; 7818 } 7819 7820 // Lists contain the same elements. 7821 if (CI == CE && SI == SE) 7822 return false; 7823 7824 // List with less elements is less than list with more elements. 7825 if (CI == CE || SI == SE) 7826 return CI == CE; 7827 7828 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration()); 7829 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration()); 7830 if (FD1->getParent() == FD2->getParent()) 7831 return FD1->getFieldIndex() < FD2->getFieldIndex(); 7832 const auto It = 7833 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) { 7834 return FD == FD1 || FD == FD2; 7835 }); 7836 return *It == FD1; 7837 }); 7838 } 7839 7840 // Associated with a capture, because the mapping flags depend on it. 7841 // Go through all of the elements with the overlapped elements. 7842 for (const auto &Pair : OverlappedData) { 7843 const MapData &L = *Pair.getFirst(); 7844 OMPClauseMappableExprCommon::MappableExprComponentListRef Components; 7845 OpenMPMapClauseKind MapType; 7846 ArrayRef<OpenMPMapModifierKind> MapModifiers; 7847 bool IsImplicit; 7848 std::tie(Components, MapType, MapModifiers, IsImplicit) = L; 7849 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef> 7850 OverlappedComponents = Pair.getSecond(); 7851 bool IsFirstComponentList = true; 7852 generateInfoForComponentList(MapType, MapModifiers, Components, 7853 BasePointers, Pointers, Sizes, Types, 7854 PartialStruct, IsFirstComponentList, 7855 IsImplicit, OverlappedComponents); 7856 } 7857 // Go through other elements without overlapped elements. 7858 bool IsFirstComponentList = OverlappedData.empty(); 7859 for (const MapData &L : DeclComponentLists) { 7860 OMPClauseMappableExprCommon::MappableExprComponentListRef Components; 7861 OpenMPMapClauseKind MapType; 7862 ArrayRef<OpenMPMapModifierKind> MapModifiers; 7863 bool IsImplicit; 7864 std::tie(Components, MapType, MapModifiers, IsImplicit) = L; 7865 auto It = OverlappedData.find(&L); 7866 if (It == OverlappedData.end()) 7867 generateInfoForComponentList(MapType, MapModifiers, Components, 7868 BasePointers, Pointers, Sizes, Types, 7869 PartialStruct, IsFirstComponentList, 7870 IsImplicit); 7871 IsFirstComponentList = false; 7872 } 7873 } 7874 7875 /// Generate the base pointers, section pointers, sizes and map types 7876 /// associated with the declare target link variables. 7877 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers, 7878 MapValuesArrayTy &Pointers, 7879 MapValuesArrayTy &Sizes, 7880 MapFlagsArrayTy &Types) const { 7881 // Map other list items in the map clause which are not captured variables 7882 // but "declare target link" global variables., 7883 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) { 7884 for (const auto &L : C->component_lists()) { 7885 if (!L.first) 7886 continue; 7887 const auto *VD = dyn_cast<VarDecl>(L.first); 7888 if (!VD) 7889 continue; 7890 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 7891 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 7892 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) 7893 continue; 7894 StructRangeInfoTy PartialStruct; 7895 generateInfoForComponentList( 7896 C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers, 7897 Pointers, Sizes, Types, PartialStruct, 7898 /*IsFirstComponentList=*/true, C->isImplicit()); 7899 assert(!PartialStruct.Base.isValid() && 7900 "No partial structs for declare target link expected."); 7901 } 7902 } 7903 } 7904 7905 /// Generate the default map information for a given capture \a CI, 7906 /// record field declaration \a RI and captured value \a CV. 7907 void generateDefaultMapInfo(const CapturedStmt::Capture &CI, 7908 const FieldDecl &RI, llvm::Value *CV, 7909 MapBaseValuesArrayTy &CurBasePointers, 7910 MapValuesArrayTy &CurPointers, 7911 MapValuesArrayTy &CurSizes, 7912 MapFlagsArrayTy &CurMapTypes) const { 7913 // Do the default mapping. 7914 if (CI.capturesThis()) { 7915 CurBasePointers.push_back(CV); 7916 CurPointers.push_back(CV); 7917 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr()); 7918 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType())); 7919 // Default map type. 7920 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM); 7921 } else if (CI.capturesVariableByCopy()) { 7922 CurBasePointers.push_back(CV); 7923 CurPointers.push_back(CV); 7924 if (!RI.getType()->isAnyPointerType()) { 7925 // We have to signal to the runtime captures passed by value that are 7926 // not pointers. 7927 CurMapTypes.push_back(OMP_MAP_LITERAL); 7928 CurSizes.push_back(CGF.getTypeSize(RI.getType())); 7929 } else { 7930 // Pointers are implicitly mapped with a zero size and no flags 7931 // (other than first map that is added for all implicit maps). 7932 CurMapTypes.push_back(OMP_MAP_NONE); 7933 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy)); 7934 } 7935 } else { 7936 assert(CI.capturesVariable() && "Expected captured reference."); 7937 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr()); 7938 QualType ElementType = PtrTy->getPointeeType(); 7939 CurSizes.push_back(CGF.getTypeSize(ElementType)); 7940 // The default map type for a scalar/complex type is 'to' because by 7941 // default the value doesn't have to be retrieved. For an aggregate 7942 // type, the default is 'tofrom'. 7943 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI)); 7944 const VarDecl *VD = CI.getCapturedVar(); 7945 if (FirstPrivateDecls.count(VD) && 7946 VD->getType().isConstant(CGF.getContext())) { 7947 llvm::Constant *Addr = 7948 CGF.CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(CGF, VD); 7949 // Copy the value of the original variable to the new global copy. 7950 CGF.Builder.CreateMemCpy( 7951 CGF.MakeNaturalAlignAddrLValue(Addr, ElementType).getAddress(), 7952 Address(CV, CGF.getContext().getTypeAlignInChars(ElementType)), 7953 CurSizes.back(), 7954 /*isVolatile=*/false); 7955 // Use new global variable as the base pointers. 7956 CurBasePointers.push_back(Addr); 7957 CurPointers.push_back(Addr); 7958 } else { 7959 CurBasePointers.push_back(CV); 7960 CurPointers.push_back(CV); 7961 } 7962 } 7963 // Every default map produces a single argument which is a target parameter. 7964 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM; 7965 7966 // Add flag stating this is an implicit map. 7967 CurMapTypes.back() |= OMP_MAP_IMPLICIT; 7968 } 7969 }; 7970 7971 enum OpenMPOffloadingReservedDeviceIDs { 7972 /// Device ID if the device was not defined, runtime should get it 7973 /// from environment variables in the spec. 7974 OMP_DEVICEID_UNDEF = -1, 7975 }; 7976 } // anonymous namespace 7977 7978 /// Emit the arrays used to pass the captures and map information to the 7979 /// offloading runtime library. If there is no map or capture information, 7980 /// return nullptr by reference. 7981 static void 7982 emitOffloadingArrays(CodeGenFunction &CGF, 7983 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers, 7984 MappableExprsHandler::MapValuesArrayTy &Pointers, 7985 MappableExprsHandler::MapValuesArrayTy &Sizes, 7986 MappableExprsHandler::MapFlagsArrayTy &MapTypes, 7987 CGOpenMPRuntime::TargetDataInfo &Info) { 7988 CodeGenModule &CGM = CGF.CGM; 7989 ASTContext &Ctx = CGF.getContext(); 7990 7991 // Reset the array information. 7992 Info.clearArrayInfo(); 7993 Info.NumberOfPtrs = BasePointers.size(); 7994 7995 if (Info.NumberOfPtrs) { 7996 // Detect if we have any capture size requiring runtime evaluation of the 7997 // size so that a constant array could be eventually used. 7998 bool hasRuntimeEvaluationCaptureSize = false; 7999 for (llvm::Value *S : Sizes) 8000 if (!isa<llvm::Constant>(S)) { 8001 hasRuntimeEvaluationCaptureSize = true; 8002 break; 8003 } 8004 8005 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true); 8006 QualType PointerArrayType = 8007 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal, 8008 /*IndexTypeQuals=*/0); 8009 8010 Info.BasePointersArray = 8011 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer(); 8012 Info.PointersArray = 8013 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer(); 8014 8015 // If we don't have any VLA types or other types that require runtime 8016 // evaluation, we can use a constant array for the map sizes, otherwise we 8017 // need to fill up the arrays as we do for the pointers. 8018 if (hasRuntimeEvaluationCaptureSize) { 8019 QualType SizeArrayType = Ctx.getConstantArrayType( 8020 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal, 8021 /*IndexTypeQuals=*/0); 8022 Info.SizesArray = 8023 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer(); 8024 } else { 8025 // We expect all the sizes to be constant, so we collect them to create 8026 // a constant array. 8027 SmallVector<llvm::Constant *, 16> ConstSizes; 8028 for (llvm::Value *S : Sizes) 8029 ConstSizes.push_back(cast<llvm::Constant>(S)); 8030 8031 auto *SizesArrayInit = llvm::ConstantArray::get( 8032 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes); 8033 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"}); 8034 auto *SizesArrayGbl = new llvm::GlobalVariable( 8035 CGM.getModule(), SizesArrayInit->getType(), 8036 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, 8037 SizesArrayInit, Name); 8038 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 8039 Info.SizesArray = SizesArrayGbl; 8040 } 8041 8042 // The map types are always constant so we don't need to generate code to 8043 // fill arrays. Instead, we create an array constant. 8044 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0); 8045 llvm::copy(MapTypes, Mapping.begin()); 8046 llvm::Constant *MapTypesArrayInit = 8047 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping); 8048 std::string MaptypesName = 8049 CGM.getOpenMPRuntime().getName({"offload_maptypes"}); 8050 auto *MapTypesArrayGbl = new llvm::GlobalVariable( 8051 CGM.getModule(), MapTypesArrayInit->getType(), 8052 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, 8053 MapTypesArrayInit, MaptypesName); 8054 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 8055 Info.MapTypesArray = MapTypesArrayGbl; 8056 8057 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) { 8058 llvm::Value *BPVal = *BasePointers[I]; 8059 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32( 8060 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), 8061 Info.BasePointersArray, 0, I); 8062 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 8063 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0)); 8064 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy)); 8065 CGF.Builder.CreateStore(BPVal, BPAddr); 8066 8067 if (Info.requiresDevicePointerInfo()) 8068 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl()) 8069 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr); 8070 8071 llvm::Value *PVal = Pointers[I]; 8072 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32( 8073 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), 8074 Info.PointersArray, 0, I); 8075 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 8076 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0)); 8077 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy)); 8078 CGF.Builder.CreateStore(PVal, PAddr); 8079 8080 if (hasRuntimeEvaluationCaptureSize) { 8081 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32( 8082 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), 8083 Info.SizesArray, 8084 /*Idx0=*/0, 8085 /*Idx1=*/I); 8086 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType())); 8087 CGF.Builder.CreateStore( 8088 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true), 8089 SAddr); 8090 } 8091 } 8092 } 8093 } 8094 /// Emit the arguments to be passed to the runtime library based on the 8095 /// arrays of pointers, sizes and map types. 8096 static void emitOffloadingArraysArgument( 8097 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg, 8098 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg, 8099 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) { 8100 CodeGenModule &CGM = CGF.CGM; 8101 if (Info.NumberOfPtrs) { 8102 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32( 8103 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), 8104 Info.BasePointersArray, 8105 /*Idx0=*/0, /*Idx1=*/0); 8106 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32( 8107 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), 8108 Info.PointersArray, 8109 /*Idx0=*/0, 8110 /*Idx1=*/0); 8111 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32( 8112 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray, 8113 /*Idx0=*/0, /*Idx1=*/0); 8114 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32( 8115 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs), 8116 Info.MapTypesArray, 8117 /*Idx0=*/0, 8118 /*Idx1=*/0); 8119 } else { 8120 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy); 8121 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy); 8122 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo()); 8123 MapTypesArrayArg = 8124 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo()); 8125 } 8126 } 8127 8128 /// Checks if the expression is constant or does not have non-trivial function 8129 /// calls. 8130 static bool isTrivial(ASTContext &Ctx, const Expr * E) { 8131 // We can skip constant expressions. 8132 // We can skip expressions with trivial calls or simple expressions. 8133 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) || 8134 !E->hasNonTrivialCall(Ctx)) && 8135 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true); 8136 } 8137 8138 /// Checks if the \p Body is the \a CompoundStmt and returns its child statement 8139 /// iff there is only one that is not evaluatable at the compile time. 8140 static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) { 8141 if (const auto *C = dyn_cast<CompoundStmt>(Body)) { 8142 const Stmt *Child = nullptr; 8143 for (const Stmt *S : C->body()) { 8144 if (const auto *E = dyn_cast<Expr>(S)) { 8145 if (isTrivial(Ctx, E)) 8146 continue; 8147 } 8148 // Some of the statements can be ignored. 8149 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) || 8150 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S)) 8151 continue; 8152 // Analyze declarations. 8153 if (const auto *DS = dyn_cast<DeclStmt>(S)) { 8154 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) { 8155 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) || 8156 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) || 8157 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) || 8158 isa<UsingDirectiveDecl>(D) || 8159 isa<OMPDeclareReductionDecl>(D) || 8160 isa<OMPThreadPrivateDecl>(D)) 8161 return true; 8162 const auto *VD = dyn_cast<VarDecl>(D); 8163 if (!VD) 8164 return false; 8165 return VD->isConstexpr() || 8166 ((VD->getType().isTrivialType(Ctx) || 8167 VD->getType()->isReferenceType()) && 8168 (!VD->hasInit() || isTrivial(Ctx, VD->getInit()))); 8169 })) 8170 continue; 8171 } 8172 // Found multiple children - cannot get the one child only. 8173 if (Child) 8174 return Body; 8175 Child = S; 8176 } 8177 if (Child) 8178 return Child; 8179 } 8180 return Body; 8181 } 8182 8183 /// Check for inner distribute directive. 8184 static const OMPExecutableDirective * 8185 getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) { 8186 const auto *CS = D.getInnermostCapturedStmt(); 8187 const auto *Body = 8188 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true); 8189 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body); 8190 8191 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) { 8192 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind(); 8193 switch (D.getDirectiveKind()) { 8194 case OMPD_target: 8195 if (isOpenMPDistributeDirective(DKind)) 8196 return NestedDir; 8197 if (DKind == OMPD_teams) { 8198 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers( 8199 /*IgnoreCaptured=*/true); 8200 if (!Body) 8201 return nullptr; 8202 ChildStmt = getSingleCompoundChild(Ctx, Body); 8203 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) { 8204 DKind = NND->getDirectiveKind(); 8205 if (isOpenMPDistributeDirective(DKind)) 8206 return NND; 8207 } 8208 } 8209 return nullptr; 8210 case OMPD_target_teams: 8211 if (isOpenMPDistributeDirective(DKind)) 8212 return NestedDir; 8213 return nullptr; 8214 case OMPD_target_parallel: 8215 case OMPD_target_simd: 8216 case OMPD_target_parallel_for: 8217 case OMPD_target_parallel_for_simd: 8218 return nullptr; 8219 case OMPD_target_teams_distribute: 8220 case OMPD_target_teams_distribute_simd: 8221 case OMPD_target_teams_distribute_parallel_for: 8222 case OMPD_target_teams_distribute_parallel_for_simd: 8223 case OMPD_parallel: 8224 case OMPD_for: 8225 case OMPD_parallel_for: 8226 case OMPD_parallel_sections: 8227 case OMPD_for_simd: 8228 case OMPD_parallel_for_simd: 8229 case OMPD_cancel: 8230 case OMPD_cancellation_point: 8231 case OMPD_ordered: 8232 case OMPD_threadprivate: 8233 case OMPD_allocate: 8234 case OMPD_task: 8235 case OMPD_simd: 8236 case OMPD_sections: 8237 case OMPD_section: 8238 case OMPD_single: 8239 case OMPD_master: 8240 case OMPD_critical: 8241 case OMPD_taskyield: 8242 case OMPD_barrier: 8243 case OMPD_taskwait: 8244 case OMPD_taskgroup: 8245 case OMPD_atomic: 8246 case OMPD_flush: 8247 case OMPD_teams: 8248 case OMPD_target_data: 8249 case OMPD_target_exit_data: 8250 case OMPD_target_enter_data: 8251 case OMPD_distribute: 8252 case OMPD_distribute_simd: 8253 case OMPD_distribute_parallel_for: 8254 case OMPD_distribute_parallel_for_simd: 8255 case OMPD_teams_distribute: 8256 case OMPD_teams_distribute_simd: 8257 case OMPD_teams_distribute_parallel_for: 8258 case OMPD_teams_distribute_parallel_for_simd: 8259 case OMPD_target_update: 8260 case OMPD_declare_simd: 8261 case OMPD_declare_target: 8262 case OMPD_end_declare_target: 8263 case OMPD_declare_reduction: 8264 case OMPD_declare_mapper: 8265 case OMPD_taskloop: 8266 case OMPD_taskloop_simd: 8267 case OMPD_requires: 8268 case OMPD_unknown: 8269 llvm_unreachable("Unexpected directive."); 8270 } 8271 } 8272 8273 return nullptr; 8274 } 8275 8276 void CGOpenMPRuntime::emitTargetNumIterationsCall( 8277 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *Device, 8278 const llvm::function_ref<llvm::Value *( 8279 CodeGenFunction &CGF, const OMPLoopDirective &D)> &SizeEmitter) { 8280 OpenMPDirectiveKind Kind = D.getDirectiveKind(); 8281 const OMPExecutableDirective *TD = &D; 8282 // Get nested teams distribute kind directive, if any. 8283 if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind)) 8284 TD = getNestedDistributeDirective(CGM.getContext(), D); 8285 if (!TD) 8286 return; 8287 const auto *LD = cast<OMPLoopDirective>(TD); 8288 auto &&CodeGen = [LD, &Device, &SizeEmitter, this](CodeGenFunction &CGF, 8289 PrePostActionTy &) { 8290 llvm::Value *NumIterations = SizeEmitter(CGF, *LD); 8291 8292 // Emit device ID if any. 8293 llvm::Value *DeviceID; 8294 if (Device) 8295 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 8296 CGF.Int64Ty, /*isSigned=*/true); 8297 else 8298 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 8299 8300 llvm::Value *Args[] = {DeviceID, NumIterations}; 8301 CGF.EmitRuntimeCall( 8302 createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args); 8303 }; 8304 emitInlinedDirective(CGF, OMPD_unknown, CodeGen); 8305 } 8306 8307 void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF, 8308 const OMPExecutableDirective &D, 8309 llvm::Function *OutlinedFn, 8310 llvm::Value *OutlinedFnID, 8311 const Expr *IfCond, const Expr *Device) { 8312 if (!CGF.HaveInsertPoint()) 8313 return; 8314 8315 assert(OutlinedFn && "Invalid outlined function!"); 8316 8317 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>(); 8318 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 8319 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target); 8320 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF, 8321 PrePostActionTy &) { 8322 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars); 8323 }; 8324 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen); 8325 8326 CodeGenFunction::OMPTargetDataInfo InputInfo; 8327 llvm::Value *MapTypesArray = nullptr; 8328 // Fill up the pointer arrays and transfer execution to the device. 8329 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo, 8330 &MapTypesArray, &CS, RequiresOuterTask, 8331 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) { 8332 // On top of the arrays that were filled up, the target offloading call 8333 // takes as arguments the device id as well as the host pointer. The host 8334 // pointer is used by the runtime library to identify the current target 8335 // region, so it only has to be unique and not necessarily point to 8336 // anything. It could be the pointer to the outlined function that 8337 // implements the target region, but we aren't using that so that the 8338 // compiler doesn't need to keep that, and could therefore inline the host 8339 // function if proven worthwhile during optimization. 8340 8341 // From this point on, we need to have an ID of the target region defined. 8342 assert(OutlinedFnID && "Invalid outlined function ID!"); 8343 8344 // Emit device ID if any. 8345 llvm::Value *DeviceID; 8346 if (Device) { 8347 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 8348 CGF.Int64Ty, /*isSigned=*/true); 8349 } else { 8350 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 8351 } 8352 8353 // Emit the number of elements in the offloading arrays. 8354 llvm::Value *PointerNum = 8355 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems); 8356 8357 // Return value of the runtime offloading call. 8358 llvm::Value *Return; 8359 8360 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D); 8361 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D); 8362 8363 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>(); 8364 // The target region is an outlined function launched by the runtime 8365 // via calls __tgt_target() or __tgt_target_teams(). 8366 // 8367 // __tgt_target() launches a target region with one team and one thread, 8368 // executing a serial region. This master thread may in turn launch 8369 // more threads within its team upon encountering a parallel region, 8370 // however, no additional teams can be launched on the device. 8371 // 8372 // __tgt_target_teams() launches a target region with one or more teams, 8373 // each with one or more threads. This call is required for target 8374 // constructs such as: 8375 // 'target teams' 8376 // 'target' / 'teams' 8377 // 'target teams distribute parallel for' 8378 // 'target parallel' 8379 // and so on. 8380 // 8381 // Note that on the host and CPU targets, the runtime implementation of 8382 // these calls simply call the outlined function without forking threads. 8383 // The outlined functions themselves have runtime calls to 8384 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by 8385 // the compiler in emitTeamsCall() and emitParallelCall(). 8386 // 8387 // In contrast, on the NVPTX target, the implementation of 8388 // __tgt_target_teams() launches a GPU kernel with the requested number 8389 // of teams and threads so no additional calls to the runtime are required. 8390 if (NumTeams) { 8391 // If we have NumTeams defined this means that we have an enclosed teams 8392 // region. Therefore we also expect to have NumThreads defined. These two 8393 // values should be defined in the presence of a teams directive, 8394 // regardless of having any clauses associated. If the user is using teams 8395 // but no clauses, these two values will be the default that should be 8396 // passed to the runtime library - a 32-bit integer with the value zero. 8397 assert(NumThreads && "Thread limit expression should be available along " 8398 "with number of teams."); 8399 llvm::Value *OffloadingArgs[] = {DeviceID, 8400 OutlinedFnID, 8401 PointerNum, 8402 InputInfo.BasePointersArray.getPointer(), 8403 InputInfo.PointersArray.getPointer(), 8404 InputInfo.SizesArray.getPointer(), 8405 MapTypesArray, 8406 NumTeams, 8407 NumThreads}; 8408 Return = CGF.EmitRuntimeCall( 8409 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait 8410 : OMPRTL__tgt_target_teams), 8411 OffloadingArgs); 8412 } else { 8413 llvm::Value *OffloadingArgs[] = {DeviceID, 8414 OutlinedFnID, 8415 PointerNum, 8416 InputInfo.BasePointersArray.getPointer(), 8417 InputInfo.PointersArray.getPointer(), 8418 InputInfo.SizesArray.getPointer(), 8419 MapTypesArray}; 8420 Return = CGF.EmitRuntimeCall( 8421 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait 8422 : OMPRTL__tgt_target), 8423 OffloadingArgs); 8424 } 8425 8426 // Check the error code and execute the host version if required. 8427 llvm::BasicBlock *OffloadFailedBlock = 8428 CGF.createBasicBlock("omp_offload.failed"); 8429 llvm::BasicBlock *OffloadContBlock = 8430 CGF.createBasicBlock("omp_offload.cont"); 8431 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return); 8432 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock); 8433 8434 CGF.EmitBlock(OffloadFailedBlock); 8435 if (RequiresOuterTask) { 8436 CapturedVars.clear(); 8437 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars); 8438 } 8439 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars); 8440 CGF.EmitBranch(OffloadContBlock); 8441 8442 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true); 8443 }; 8444 8445 // Notify that the host version must be executed. 8446 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars, 8447 RequiresOuterTask](CodeGenFunction &CGF, 8448 PrePostActionTy &) { 8449 if (RequiresOuterTask) { 8450 CapturedVars.clear(); 8451 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars); 8452 } 8453 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars); 8454 }; 8455 8456 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray, 8457 &CapturedVars, RequiresOuterTask, 8458 &CS](CodeGenFunction &CGF, PrePostActionTy &) { 8459 // Fill up the arrays with all the captured variables. 8460 MappableExprsHandler::MapBaseValuesArrayTy BasePointers; 8461 MappableExprsHandler::MapValuesArrayTy Pointers; 8462 MappableExprsHandler::MapValuesArrayTy Sizes; 8463 MappableExprsHandler::MapFlagsArrayTy MapTypes; 8464 8465 // Get mappable expression information. 8466 MappableExprsHandler MEHandler(D, CGF); 8467 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers; 8468 8469 auto RI = CS.getCapturedRecordDecl()->field_begin(); 8470 auto CV = CapturedVars.begin(); 8471 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(), 8472 CE = CS.capture_end(); 8473 CI != CE; ++CI, ++RI, ++CV) { 8474 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers; 8475 MappableExprsHandler::MapValuesArrayTy CurPointers; 8476 MappableExprsHandler::MapValuesArrayTy CurSizes; 8477 MappableExprsHandler::MapFlagsArrayTy CurMapTypes; 8478 MappableExprsHandler::StructRangeInfoTy PartialStruct; 8479 8480 // VLA sizes are passed to the outlined region by copy and do not have map 8481 // information associated. 8482 if (CI->capturesVariableArrayType()) { 8483 CurBasePointers.push_back(*CV); 8484 CurPointers.push_back(*CV); 8485 CurSizes.push_back(CGF.getTypeSize(RI->getType())); 8486 // Copy to the device as an argument. No need to retrieve it. 8487 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL | 8488 MappableExprsHandler::OMP_MAP_TARGET_PARAM); 8489 } else { 8490 // If we have any information in the map clause, we use it, otherwise we 8491 // just do a default mapping. 8492 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers, 8493 CurSizes, CurMapTypes, PartialStruct); 8494 if (CurBasePointers.empty()) 8495 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers, 8496 CurPointers, CurSizes, CurMapTypes); 8497 // Generate correct mapping for variables captured by reference in 8498 // lambdas. 8499 if (CI->capturesVariable()) 8500 MEHandler.generateInfoForLambdaCaptures( 8501 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes, 8502 CurMapTypes, LambdaPointers); 8503 } 8504 // We expect to have at least an element of information for this capture. 8505 assert(!CurBasePointers.empty() && 8506 "Non-existing map pointer for capture!"); 8507 assert(CurBasePointers.size() == CurPointers.size() && 8508 CurBasePointers.size() == CurSizes.size() && 8509 CurBasePointers.size() == CurMapTypes.size() && 8510 "Inconsistent map information sizes!"); 8511 8512 // If there is an entry in PartialStruct it means we have a struct with 8513 // individual members mapped. Emit an extra combined entry. 8514 if (PartialStruct.Base.isValid()) 8515 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes, 8516 CurMapTypes, PartialStruct); 8517 8518 // We need to append the results of this capture to what we already have. 8519 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end()); 8520 Pointers.append(CurPointers.begin(), CurPointers.end()); 8521 Sizes.append(CurSizes.begin(), CurSizes.end()); 8522 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end()); 8523 } 8524 // Adjust MEMBER_OF flags for the lambdas captures. 8525 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers, 8526 Pointers, MapTypes); 8527 // Map other list items in the map clause which are not captured variables 8528 // but "declare target link" global variables. 8529 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes, 8530 MapTypes); 8531 8532 TargetDataInfo Info; 8533 // Fill up the arrays and create the arguments. 8534 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info); 8535 emitOffloadingArraysArgument(CGF, Info.BasePointersArray, 8536 Info.PointersArray, Info.SizesArray, 8537 Info.MapTypesArray, Info); 8538 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs; 8539 InputInfo.BasePointersArray = 8540 Address(Info.BasePointersArray, CGM.getPointerAlign()); 8541 InputInfo.PointersArray = 8542 Address(Info.PointersArray, CGM.getPointerAlign()); 8543 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign()); 8544 MapTypesArray = Info.MapTypesArray; 8545 if (RequiresOuterTask) 8546 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo); 8547 else 8548 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen); 8549 }; 8550 8551 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask]( 8552 CodeGenFunction &CGF, PrePostActionTy &) { 8553 if (RequiresOuterTask) { 8554 CodeGenFunction::OMPTargetDataInfo InputInfo; 8555 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo); 8556 } else { 8557 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen); 8558 } 8559 }; 8560 8561 // If we have a target function ID it means that we need to support 8562 // offloading, otherwise, just execute on the host. We need to execute on host 8563 // regardless of the conditional in the if clause if, e.g., the user do not 8564 // specify target triples. 8565 if (OutlinedFnID) { 8566 if (IfCond) { 8567 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen); 8568 } else { 8569 RegionCodeGenTy ThenRCG(TargetThenGen); 8570 ThenRCG(CGF); 8571 } 8572 } else { 8573 RegionCodeGenTy ElseRCG(TargetElseGen); 8574 ElseRCG(CGF); 8575 } 8576 } 8577 8578 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S, 8579 StringRef ParentName) { 8580 if (!S) 8581 return; 8582 8583 // Codegen OMP target directives that offload compute to the device. 8584 bool RequiresDeviceCodegen = 8585 isa<OMPExecutableDirective>(S) && 8586 isOpenMPTargetExecutionDirective( 8587 cast<OMPExecutableDirective>(S)->getDirectiveKind()); 8588 8589 if (RequiresDeviceCodegen) { 8590 const auto &E = *cast<OMPExecutableDirective>(S); 8591 unsigned DeviceID; 8592 unsigned FileID; 8593 unsigned Line; 8594 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID, 8595 FileID, Line); 8596 8597 // Is this a target region that should not be emitted as an entry point? If 8598 // so just signal we are done with this target region. 8599 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID, 8600 ParentName, Line)) 8601 return; 8602 8603 switch (E.getDirectiveKind()) { 8604 case OMPD_target: 8605 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName, 8606 cast<OMPTargetDirective>(E)); 8607 break; 8608 case OMPD_target_parallel: 8609 CodeGenFunction::EmitOMPTargetParallelDeviceFunction( 8610 CGM, ParentName, cast<OMPTargetParallelDirective>(E)); 8611 break; 8612 case OMPD_target_teams: 8613 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction( 8614 CGM, ParentName, cast<OMPTargetTeamsDirective>(E)); 8615 break; 8616 case OMPD_target_teams_distribute: 8617 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction( 8618 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E)); 8619 break; 8620 case OMPD_target_teams_distribute_simd: 8621 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction( 8622 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E)); 8623 break; 8624 case OMPD_target_parallel_for: 8625 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction( 8626 CGM, ParentName, cast<OMPTargetParallelForDirective>(E)); 8627 break; 8628 case OMPD_target_parallel_for_simd: 8629 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction( 8630 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E)); 8631 break; 8632 case OMPD_target_simd: 8633 CodeGenFunction::EmitOMPTargetSimdDeviceFunction( 8634 CGM, ParentName, cast<OMPTargetSimdDirective>(E)); 8635 break; 8636 case OMPD_target_teams_distribute_parallel_for: 8637 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 8638 CGM, ParentName, 8639 cast<OMPTargetTeamsDistributeParallelForDirective>(E)); 8640 break; 8641 case OMPD_target_teams_distribute_parallel_for_simd: 8642 CodeGenFunction:: 8643 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 8644 CGM, ParentName, 8645 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E)); 8646 break; 8647 case OMPD_parallel: 8648 case OMPD_for: 8649 case OMPD_parallel_for: 8650 case OMPD_parallel_sections: 8651 case OMPD_for_simd: 8652 case OMPD_parallel_for_simd: 8653 case OMPD_cancel: 8654 case OMPD_cancellation_point: 8655 case OMPD_ordered: 8656 case OMPD_threadprivate: 8657 case OMPD_allocate: 8658 case OMPD_task: 8659 case OMPD_simd: 8660 case OMPD_sections: 8661 case OMPD_section: 8662 case OMPD_single: 8663 case OMPD_master: 8664 case OMPD_critical: 8665 case OMPD_taskyield: 8666 case OMPD_barrier: 8667 case OMPD_taskwait: 8668 case OMPD_taskgroup: 8669 case OMPD_atomic: 8670 case OMPD_flush: 8671 case OMPD_teams: 8672 case OMPD_target_data: 8673 case OMPD_target_exit_data: 8674 case OMPD_target_enter_data: 8675 case OMPD_distribute: 8676 case OMPD_distribute_simd: 8677 case OMPD_distribute_parallel_for: 8678 case OMPD_distribute_parallel_for_simd: 8679 case OMPD_teams_distribute: 8680 case OMPD_teams_distribute_simd: 8681 case OMPD_teams_distribute_parallel_for: 8682 case OMPD_teams_distribute_parallel_for_simd: 8683 case OMPD_target_update: 8684 case OMPD_declare_simd: 8685 case OMPD_declare_target: 8686 case OMPD_end_declare_target: 8687 case OMPD_declare_reduction: 8688 case OMPD_declare_mapper: 8689 case OMPD_taskloop: 8690 case OMPD_taskloop_simd: 8691 case OMPD_requires: 8692 case OMPD_unknown: 8693 llvm_unreachable("Unknown target directive for OpenMP device codegen."); 8694 } 8695 return; 8696 } 8697 8698 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) { 8699 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt()) 8700 return; 8701 8702 scanForTargetRegionsFunctions( 8703 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName); 8704 return; 8705 } 8706 8707 // If this is a lambda function, look into its body. 8708 if (const auto *L = dyn_cast<LambdaExpr>(S)) 8709 S = L->getBody(); 8710 8711 // Keep looking for target regions recursively. 8712 for (const Stmt *II : S->children()) 8713 scanForTargetRegionsFunctions(II, ParentName); 8714 } 8715 8716 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) { 8717 // If emitting code for the host, we do not process FD here. Instead we do 8718 // the normal code generation. 8719 if (!CGM.getLangOpts().OpenMPIsDevice) 8720 return false; 8721 8722 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl()); 8723 StringRef Name = CGM.getMangledName(GD); 8724 // Try to detect target regions in the function. 8725 if (const auto *FD = dyn_cast<FunctionDecl>(VD)) 8726 scanForTargetRegionsFunctions(FD->getBody(), Name); 8727 8728 // Do not to emit function if it is not marked as declare target. 8729 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) && 8730 AlreadyEmittedTargetFunctions.count(Name) == 0; 8731 } 8732 8733 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) { 8734 if (!CGM.getLangOpts().OpenMPIsDevice) 8735 return false; 8736 8737 // Check if there are Ctors/Dtors in this declaration and look for target 8738 // regions in it. We use the complete variant to produce the kernel name 8739 // mangling. 8740 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType(); 8741 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) { 8742 for (const CXXConstructorDecl *Ctor : RD->ctors()) { 8743 StringRef ParentName = 8744 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete)); 8745 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName); 8746 } 8747 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) { 8748 StringRef ParentName = 8749 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete)); 8750 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName); 8751 } 8752 } 8753 8754 // Do not to emit variable if it is not marked as declare target. 8755 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 8756 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 8757 cast<VarDecl>(GD.getDecl())); 8758 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) { 8759 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl())); 8760 return true; 8761 } 8762 return false; 8763 } 8764 8765 llvm::Constant * 8766 CGOpenMPRuntime::registerTargetFirstprivateCopy(CodeGenFunction &CGF, 8767 const VarDecl *VD) { 8768 assert(VD->getType().isConstant(CGM.getContext()) && 8769 "Expected constant variable."); 8770 StringRef VarName; 8771 llvm::Constant *Addr; 8772 llvm::GlobalValue::LinkageTypes Linkage; 8773 QualType Ty = VD->getType(); 8774 SmallString<128> Buffer; 8775 { 8776 unsigned DeviceID; 8777 unsigned FileID; 8778 unsigned Line; 8779 getTargetEntryUniqueInfo(CGM.getContext(), VD->getLocation(), DeviceID, 8780 FileID, Line); 8781 llvm::raw_svector_ostream OS(Buffer); 8782 OS << "__omp_offloading_firstprivate_" << llvm::format("_%x", DeviceID) 8783 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line; 8784 VarName = OS.str(); 8785 } 8786 Linkage = llvm::GlobalValue::InternalLinkage; 8787 Addr = 8788 getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(Ty), VarName, 8789 getDefaultFirstprivateAddressSpace()); 8790 cast<llvm::GlobalValue>(Addr)->setLinkage(Linkage); 8791 CharUnits VarSize = CGM.getContext().getTypeSizeInChars(Ty); 8792 CGM.addCompilerUsedGlobal(cast<llvm::GlobalValue>(Addr)); 8793 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo( 8794 VarName, Addr, VarSize, 8795 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo, Linkage); 8796 return Addr; 8797 } 8798 8799 void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD, 8800 llvm::Constant *Addr) { 8801 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 8802 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 8803 if (!Res) { 8804 if (CGM.getLangOpts().OpenMPIsDevice) { 8805 // Register non-target variables being emitted in device code (debug info 8806 // may cause this). 8807 StringRef VarName = CGM.getMangledName(VD); 8808 EmittedNonTargetVariables.try_emplace(VarName, Addr); 8809 } 8810 return; 8811 } 8812 // Register declare target variables. 8813 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags; 8814 StringRef VarName; 8815 CharUnits VarSize; 8816 llvm::GlobalValue::LinkageTypes Linkage; 8817 switch (*Res) { 8818 case OMPDeclareTargetDeclAttr::MT_To: 8819 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo; 8820 VarName = CGM.getMangledName(VD); 8821 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) { 8822 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType()); 8823 assert(!VarSize.isZero() && "Expected non-zero size of the variable"); 8824 } else { 8825 VarSize = CharUnits::Zero(); 8826 } 8827 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false); 8828 // Temp solution to prevent optimizations of the internal variables. 8829 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) { 8830 std::string RefName = getName({VarName, "ref"}); 8831 if (!CGM.GetGlobalValue(RefName)) { 8832 llvm::Constant *AddrRef = 8833 getOrCreateInternalVariable(Addr->getType(), RefName); 8834 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef); 8835 GVAddrRef->setConstant(/*Val=*/true); 8836 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage); 8837 GVAddrRef->setInitializer(Addr); 8838 CGM.addCompilerUsedGlobal(GVAddrRef); 8839 } 8840 } 8841 break; 8842 case OMPDeclareTargetDeclAttr::MT_Link: 8843 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink; 8844 if (CGM.getLangOpts().OpenMPIsDevice) { 8845 VarName = Addr->getName(); 8846 Addr = nullptr; 8847 } else { 8848 VarName = getAddrOfDeclareTargetLink(VD).getName(); 8849 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer()); 8850 } 8851 VarSize = CGM.getPointerSize(); 8852 Linkage = llvm::GlobalValue::WeakAnyLinkage; 8853 break; 8854 } 8855 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo( 8856 VarName, Addr, VarSize, Flags, Linkage); 8857 } 8858 8859 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) { 8860 if (isa<FunctionDecl>(GD.getDecl()) || 8861 isa<OMPDeclareReductionDecl>(GD.getDecl())) 8862 return emitTargetFunctions(GD); 8863 8864 return emitTargetGlobalVariable(GD); 8865 } 8866 8867 void CGOpenMPRuntime::emitDeferredTargetDecls() const { 8868 for (const VarDecl *VD : DeferredGlobalVariables) { 8869 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 8870 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 8871 if (!Res) 8872 continue; 8873 if (*Res == OMPDeclareTargetDeclAttr::MT_To) { 8874 CGM.EmitGlobal(VD); 8875 } else { 8876 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link && 8877 "Expected to or link clauses."); 8878 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD); 8879 } 8880 } 8881 } 8882 8883 void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas( 8884 CodeGenFunction &CGF, const OMPExecutableDirective &D) const { 8885 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) && 8886 " Expected target-based directive."); 8887 } 8888 8889 CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII( 8890 CodeGenModule &CGM) 8891 : CGM(CGM) { 8892 if (CGM.getLangOpts().OpenMPIsDevice) { 8893 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal; 8894 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false; 8895 } 8896 } 8897 8898 CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() { 8899 if (CGM.getLangOpts().OpenMPIsDevice) 8900 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal; 8901 } 8902 8903 bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) { 8904 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal) 8905 return true; 8906 8907 StringRef Name = CGM.getMangledName(GD); 8908 const auto *D = cast<FunctionDecl>(GD.getDecl()); 8909 // Do not to emit function if it is marked as declare target as it was already 8910 // emitted. 8911 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) { 8912 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) { 8913 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name))) 8914 return !F->isDeclaration(); 8915 return false; 8916 } 8917 return true; 8918 } 8919 8920 return !AlreadyEmittedTargetFunctions.insert(Name).second; 8921 } 8922 8923 llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() { 8924 // If we have offloading in the current module, we need to emit the entries 8925 // now and register the offloading descriptor. 8926 createOffloadEntriesAndInfoMetadata(); 8927 8928 // Create and register the offloading binary descriptors. This is the main 8929 // entity that captures all the information about offloading in the current 8930 // compilation unit. 8931 return createOffloadingBinaryDescriptorRegistration(); 8932 } 8933 8934 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF, 8935 const OMPExecutableDirective &D, 8936 SourceLocation Loc, 8937 llvm::Function *OutlinedFn, 8938 ArrayRef<llvm::Value *> CapturedVars) { 8939 if (!CGF.HaveInsertPoint()) 8940 return; 8941 8942 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc); 8943 CodeGenFunction::RunCleanupsScope Scope(CGF); 8944 8945 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn); 8946 llvm::Value *Args[] = { 8947 RTLoc, 8948 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars 8949 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())}; 8950 llvm::SmallVector<llvm::Value *, 16> RealArgs; 8951 RealArgs.append(std::begin(Args), std::end(Args)); 8952 RealArgs.append(CapturedVars.begin(), CapturedVars.end()); 8953 8954 llvm::FunctionCallee RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams); 8955 CGF.EmitRuntimeCall(RTLFn, RealArgs); 8956 } 8957 8958 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF, 8959 const Expr *NumTeams, 8960 const Expr *ThreadLimit, 8961 SourceLocation Loc) { 8962 if (!CGF.HaveInsertPoint()) 8963 return; 8964 8965 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc); 8966 8967 llvm::Value *NumTeamsVal = 8968 NumTeams 8969 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams), 8970 CGF.CGM.Int32Ty, /* isSigned = */ true) 8971 : CGF.Builder.getInt32(0); 8972 8973 llvm::Value *ThreadLimitVal = 8974 ThreadLimit 8975 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit), 8976 CGF.CGM.Int32Ty, /* isSigned = */ true) 8977 : CGF.Builder.getInt32(0); 8978 8979 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit) 8980 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal, 8981 ThreadLimitVal}; 8982 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams), 8983 PushNumTeamsArgs); 8984 } 8985 8986 void CGOpenMPRuntime::emitTargetDataCalls( 8987 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, 8988 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) { 8989 if (!CGF.HaveInsertPoint()) 8990 return; 8991 8992 // Action used to replace the default codegen action and turn privatization 8993 // off. 8994 PrePostActionTy NoPrivAction; 8995 8996 // Generate the code for the opening of the data environment. Capture all the 8997 // arguments of the runtime call by reference because they are used in the 8998 // closing of the region. 8999 auto &&BeginThenGen = [this, &D, Device, &Info, 9000 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) { 9001 // Fill up the arrays with all the mapped variables. 9002 MappableExprsHandler::MapBaseValuesArrayTy BasePointers; 9003 MappableExprsHandler::MapValuesArrayTy Pointers; 9004 MappableExprsHandler::MapValuesArrayTy Sizes; 9005 MappableExprsHandler::MapFlagsArrayTy MapTypes; 9006 9007 // Get map clause information. 9008 MappableExprsHandler MCHandler(D, CGF); 9009 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes); 9010 9011 // Fill up the arrays and create the arguments. 9012 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info); 9013 9014 llvm::Value *BasePointersArrayArg = nullptr; 9015 llvm::Value *PointersArrayArg = nullptr; 9016 llvm::Value *SizesArrayArg = nullptr; 9017 llvm::Value *MapTypesArrayArg = nullptr; 9018 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg, 9019 SizesArrayArg, MapTypesArrayArg, Info); 9020 9021 // Emit device ID if any. 9022 llvm::Value *DeviceID = nullptr; 9023 if (Device) { 9024 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 9025 CGF.Int64Ty, /*isSigned=*/true); 9026 } else { 9027 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 9028 } 9029 9030 // Emit the number of elements in the offloading arrays. 9031 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs); 9032 9033 llvm::Value *OffloadingArgs[] = { 9034 DeviceID, PointerNum, BasePointersArrayArg, 9035 PointersArrayArg, SizesArrayArg, MapTypesArrayArg}; 9036 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin), 9037 OffloadingArgs); 9038 9039 // If device pointer privatization is required, emit the body of the region 9040 // here. It will have to be duplicated: with and without privatization. 9041 if (!Info.CaptureDeviceAddrMap.empty()) 9042 CodeGen(CGF); 9043 }; 9044 9045 // Generate code for the closing of the data region. 9046 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF, 9047 PrePostActionTy &) { 9048 assert(Info.isValid() && "Invalid data environment closing arguments."); 9049 9050 llvm::Value *BasePointersArrayArg = nullptr; 9051 llvm::Value *PointersArrayArg = nullptr; 9052 llvm::Value *SizesArrayArg = nullptr; 9053 llvm::Value *MapTypesArrayArg = nullptr; 9054 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg, 9055 SizesArrayArg, MapTypesArrayArg, Info); 9056 9057 // Emit device ID if any. 9058 llvm::Value *DeviceID = nullptr; 9059 if (Device) { 9060 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 9061 CGF.Int64Ty, /*isSigned=*/true); 9062 } else { 9063 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 9064 } 9065 9066 // Emit the number of elements in the offloading arrays. 9067 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs); 9068 9069 llvm::Value *OffloadingArgs[] = { 9070 DeviceID, PointerNum, BasePointersArrayArg, 9071 PointersArrayArg, SizesArrayArg, MapTypesArrayArg}; 9072 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end), 9073 OffloadingArgs); 9074 }; 9075 9076 // If we need device pointer privatization, we need to emit the body of the 9077 // region with no privatization in the 'else' branch of the conditional. 9078 // Otherwise, we don't have to do anything. 9079 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF, 9080 PrePostActionTy &) { 9081 if (!Info.CaptureDeviceAddrMap.empty()) { 9082 CodeGen.setAction(NoPrivAction); 9083 CodeGen(CGF); 9084 } 9085 }; 9086 9087 // We don't have to do anything to close the region if the if clause evaluates 9088 // to false. 9089 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {}; 9090 9091 if (IfCond) { 9092 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen); 9093 } else { 9094 RegionCodeGenTy RCG(BeginThenGen); 9095 RCG(CGF); 9096 } 9097 9098 // If we don't require privatization of device pointers, we emit the body in 9099 // between the runtime calls. This avoids duplicating the body code. 9100 if (Info.CaptureDeviceAddrMap.empty()) { 9101 CodeGen.setAction(NoPrivAction); 9102 CodeGen(CGF); 9103 } 9104 9105 if (IfCond) { 9106 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen); 9107 } else { 9108 RegionCodeGenTy RCG(EndThenGen); 9109 RCG(CGF); 9110 } 9111 } 9112 9113 void CGOpenMPRuntime::emitTargetDataStandAloneCall( 9114 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, 9115 const Expr *Device) { 9116 if (!CGF.HaveInsertPoint()) 9117 return; 9118 9119 assert((isa<OMPTargetEnterDataDirective>(D) || 9120 isa<OMPTargetExitDataDirective>(D) || 9121 isa<OMPTargetUpdateDirective>(D)) && 9122 "Expecting either target enter, exit data, or update directives."); 9123 9124 CodeGenFunction::OMPTargetDataInfo InputInfo; 9125 llvm::Value *MapTypesArray = nullptr; 9126 // Generate the code for the opening of the data environment. 9127 auto &&ThenGen = [this, &D, Device, &InputInfo, 9128 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) { 9129 // Emit device ID if any. 9130 llvm::Value *DeviceID = nullptr; 9131 if (Device) { 9132 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 9133 CGF.Int64Ty, /*isSigned=*/true); 9134 } else { 9135 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 9136 } 9137 9138 // Emit the number of elements in the offloading arrays. 9139 llvm::Constant *PointerNum = 9140 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems); 9141 9142 llvm::Value *OffloadingArgs[] = {DeviceID, 9143 PointerNum, 9144 InputInfo.BasePointersArray.getPointer(), 9145 InputInfo.PointersArray.getPointer(), 9146 InputInfo.SizesArray.getPointer(), 9147 MapTypesArray}; 9148 9149 // Select the right runtime function call for each expected standalone 9150 // directive. 9151 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>(); 9152 OpenMPRTLFunction RTLFn; 9153 switch (D.getDirectiveKind()) { 9154 case OMPD_target_enter_data: 9155 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait 9156 : OMPRTL__tgt_target_data_begin; 9157 break; 9158 case OMPD_target_exit_data: 9159 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait 9160 : OMPRTL__tgt_target_data_end; 9161 break; 9162 case OMPD_target_update: 9163 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait 9164 : OMPRTL__tgt_target_data_update; 9165 break; 9166 case OMPD_parallel: 9167 case OMPD_for: 9168 case OMPD_parallel_for: 9169 case OMPD_parallel_sections: 9170 case OMPD_for_simd: 9171 case OMPD_parallel_for_simd: 9172 case OMPD_cancel: 9173 case OMPD_cancellation_point: 9174 case OMPD_ordered: 9175 case OMPD_threadprivate: 9176 case OMPD_allocate: 9177 case OMPD_task: 9178 case OMPD_simd: 9179 case OMPD_sections: 9180 case OMPD_section: 9181 case OMPD_single: 9182 case OMPD_master: 9183 case OMPD_critical: 9184 case OMPD_taskyield: 9185 case OMPD_barrier: 9186 case OMPD_taskwait: 9187 case OMPD_taskgroup: 9188 case OMPD_atomic: 9189 case OMPD_flush: 9190 case OMPD_teams: 9191 case OMPD_target_data: 9192 case OMPD_distribute: 9193 case OMPD_distribute_simd: 9194 case OMPD_distribute_parallel_for: 9195 case OMPD_distribute_parallel_for_simd: 9196 case OMPD_teams_distribute: 9197 case OMPD_teams_distribute_simd: 9198 case OMPD_teams_distribute_parallel_for: 9199 case OMPD_teams_distribute_parallel_for_simd: 9200 case OMPD_declare_simd: 9201 case OMPD_declare_target: 9202 case OMPD_end_declare_target: 9203 case OMPD_declare_reduction: 9204 case OMPD_declare_mapper: 9205 case OMPD_taskloop: 9206 case OMPD_taskloop_simd: 9207 case OMPD_target: 9208 case OMPD_target_simd: 9209 case OMPD_target_teams_distribute: 9210 case OMPD_target_teams_distribute_simd: 9211 case OMPD_target_teams_distribute_parallel_for: 9212 case OMPD_target_teams_distribute_parallel_for_simd: 9213 case OMPD_target_teams: 9214 case OMPD_target_parallel: 9215 case OMPD_target_parallel_for: 9216 case OMPD_target_parallel_for_simd: 9217 case OMPD_requires: 9218 case OMPD_unknown: 9219 llvm_unreachable("Unexpected standalone target data directive."); 9220 break; 9221 } 9222 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs); 9223 }; 9224 9225 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray]( 9226 CodeGenFunction &CGF, PrePostActionTy &) { 9227 // Fill up the arrays with all the mapped variables. 9228 MappableExprsHandler::MapBaseValuesArrayTy BasePointers; 9229 MappableExprsHandler::MapValuesArrayTy Pointers; 9230 MappableExprsHandler::MapValuesArrayTy Sizes; 9231 MappableExprsHandler::MapFlagsArrayTy MapTypes; 9232 9233 // Get map clause information. 9234 MappableExprsHandler MEHandler(D, CGF); 9235 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes); 9236 9237 TargetDataInfo Info; 9238 // Fill up the arrays and create the arguments. 9239 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info); 9240 emitOffloadingArraysArgument(CGF, Info.BasePointersArray, 9241 Info.PointersArray, Info.SizesArray, 9242 Info.MapTypesArray, Info); 9243 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs; 9244 InputInfo.BasePointersArray = 9245 Address(Info.BasePointersArray, CGM.getPointerAlign()); 9246 InputInfo.PointersArray = 9247 Address(Info.PointersArray, CGM.getPointerAlign()); 9248 InputInfo.SizesArray = 9249 Address(Info.SizesArray, CGM.getPointerAlign()); 9250 MapTypesArray = Info.MapTypesArray; 9251 if (D.hasClausesOfKind<OMPDependClause>()) 9252 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo); 9253 else 9254 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen); 9255 }; 9256 9257 if (IfCond) { 9258 emitOMPIfClause(CGF, IfCond, TargetThenGen, 9259 [](CodeGenFunction &CGF, PrePostActionTy &) {}); 9260 } else { 9261 RegionCodeGenTy ThenRCG(TargetThenGen); 9262 ThenRCG(CGF); 9263 } 9264 } 9265 9266 namespace { 9267 /// Kind of parameter in a function with 'declare simd' directive. 9268 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector }; 9269 /// Attribute set of the parameter. 9270 struct ParamAttrTy { 9271 ParamKindTy Kind = Vector; 9272 llvm::APSInt StrideOrArg; 9273 llvm::APSInt Alignment; 9274 }; 9275 } // namespace 9276 9277 static unsigned evaluateCDTSize(const FunctionDecl *FD, 9278 ArrayRef<ParamAttrTy> ParamAttrs) { 9279 // Every vector variant of a SIMD-enabled function has a vector length (VLEN). 9280 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument 9281 // of that clause. The VLEN value must be power of 2. 9282 // In other case the notion of the function`s "characteristic data type" (CDT) 9283 // is used to compute the vector length. 9284 // CDT is defined in the following order: 9285 // a) For non-void function, the CDT is the return type. 9286 // b) If the function has any non-uniform, non-linear parameters, then the 9287 // CDT is the type of the first such parameter. 9288 // c) If the CDT determined by a) or b) above is struct, union, or class 9289 // type which is pass-by-value (except for the type that maps to the 9290 // built-in complex data type), the characteristic data type is int. 9291 // d) If none of the above three cases is applicable, the CDT is int. 9292 // The VLEN is then determined based on the CDT and the size of vector 9293 // register of that ISA for which current vector version is generated. The 9294 // VLEN is computed using the formula below: 9295 // VLEN = sizeof(vector_register) / sizeof(CDT), 9296 // where vector register size specified in section 3.2.1 Registers and the 9297 // Stack Frame of original AMD64 ABI document. 9298 QualType RetType = FD->getReturnType(); 9299 if (RetType.isNull()) 9300 return 0; 9301 ASTContext &C = FD->getASTContext(); 9302 QualType CDT; 9303 if (!RetType.isNull() && !RetType->isVoidType()) { 9304 CDT = RetType; 9305 } else { 9306 unsigned Offset = 0; 9307 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 9308 if (ParamAttrs[Offset].Kind == Vector) 9309 CDT = C.getPointerType(C.getRecordType(MD->getParent())); 9310 ++Offset; 9311 } 9312 if (CDT.isNull()) { 9313 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) { 9314 if (ParamAttrs[I + Offset].Kind == Vector) { 9315 CDT = FD->getParamDecl(I)->getType(); 9316 break; 9317 } 9318 } 9319 } 9320 } 9321 if (CDT.isNull()) 9322 CDT = C.IntTy; 9323 CDT = CDT->getCanonicalTypeUnqualified(); 9324 if (CDT->isRecordType() || CDT->isUnionType()) 9325 CDT = C.IntTy; 9326 return C.getTypeSize(CDT); 9327 } 9328 9329 static void 9330 emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn, 9331 const llvm::APSInt &VLENVal, 9332 ArrayRef<ParamAttrTy> ParamAttrs, 9333 OMPDeclareSimdDeclAttr::BranchStateTy State) { 9334 struct ISADataTy { 9335 char ISA; 9336 unsigned VecRegSize; 9337 }; 9338 ISADataTy ISAData[] = { 9339 { 9340 'b', 128 9341 }, // SSE 9342 { 9343 'c', 256 9344 }, // AVX 9345 { 9346 'd', 256 9347 }, // AVX2 9348 { 9349 'e', 512 9350 }, // AVX512 9351 }; 9352 llvm::SmallVector<char, 2> Masked; 9353 switch (State) { 9354 case OMPDeclareSimdDeclAttr::BS_Undefined: 9355 Masked.push_back('N'); 9356 Masked.push_back('M'); 9357 break; 9358 case OMPDeclareSimdDeclAttr::BS_Notinbranch: 9359 Masked.push_back('N'); 9360 break; 9361 case OMPDeclareSimdDeclAttr::BS_Inbranch: 9362 Masked.push_back('M'); 9363 break; 9364 } 9365 for (char Mask : Masked) { 9366 for (const ISADataTy &Data : ISAData) { 9367 SmallString<256> Buffer; 9368 llvm::raw_svector_ostream Out(Buffer); 9369 Out << "_ZGV" << Data.ISA << Mask; 9370 if (!VLENVal) { 9371 Out << llvm::APSInt::getUnsigned(Data.VecRegSize / 9372 evaluateCDTSize(FD, ParamAttrs)); 9373 } else { 9374 Out << VLENVal; 9375 } 9376 for (const ParamAttrTy &ParamAttr : ParamAttrs) { 9377 switch (ParamAttr.Kind){ 9378 case LinearWithVarStride: 9379 Out << 's' << ParamAttr.StrideOrArg; 9380 break; 9381 case Linear: 9382 Out << 'l'; 9383 if (!!ParamAttr.StrideOrArg) 9384 Out << ParamAttr.StrideOrArg; 9385 break; 9386 case Uniform: 9387 Out << 'u'; 9388 break; 9389 case Vector: 9390 Out << 'v'; 9391 break; 9392 } 9393 if (!!ParamAttr.Alignment) 9394 Out << 'a' << ParamAttr.Alignment; 9395 } 9396 Out << '_' << Fn->getName(); 9397 Fn->addFnAttr(Out.str()); 9398 } 9399 } 9400 } 9401 9402 void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD, 9403 llvm::Function *Fn) { 9404 ASTContext &C = CGM.getContext(); 9405 FD = FD->getMostRecentDecl(); 9406 // Map params to their positions in function decl. 9407 llvm::DenseMap<const Decl *, unsigned> ParamPositions; 9408 if (isa<CXXMethodDecl>(FD)) 9409 ParamPositions.try_emplace(FD, 0); 9410 unsigned ParamPos = ParamPositions.size(); 9411 for (const ParmVarDecl *P : FD->parameters()) { 9412 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos); 9413 ++ParamPos; 9414 } 9415 while (FD) { 9416 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) { 9417 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size()); 9418 // Mark uniform parameters. 9419 for (const Expr *E : Attr->uniforms()) { 9420 E = E->IgnoreParenImpCasts(); 9421 unsigned Pos; 9422 if (isa<CXXThisExpr>(E)) { 9423 Pos = ParamPositions[FD]; 9424 } else { 9425 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl()) 9426 ->getCanonicalDecl(); 9427 Pos = ParamPositions[PVD]; 9428 } 9429 ParamAttrs[Pos].Kind = Uniform; 9430 } 9431 // Get alignment info. 9432 auto NI = Attr->alignments_begin(); 9433 for (const Expr *E : Attr->aligneds()) { 9434 E = E->IgnoreParenImpCasts(); 9435 unsigned Pos; 9436 QualType ParmTy; 9437 if (isa<CXXThisExpr>(E)) { 9438 Pos = ParamPositions[FD]; 9439 ParmTy = E->getType(); 9440 } else { 9441 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl()) 9442 ->getCanonicalDecl(); 9443 Pos = ParamPositions[PVD]; 9444 ParmTy = PVD->getType(); 9445 } 9446 ParamAttrs[Pos].Alignment = 9447 (*NI) 9448 ? (*NI)->EvaluateKnownConstInt(C) 9449 : llvm::APSInt::getUnsigned( 9450 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy)) 9451 .getQuantity()); 9452 ++NI; 9453 } 9454 // Mark linear parameters. 9455 auto SI = Attr->steps_begin(); 9456 auto MI = Attr->modifiers_begin(); 9457 for (const Expr *E : Attr->linears()) { 9458 E = E->IgnoreParenImpCasts(); 9459 unsigned Pos; 9460 if (isa<CXXThisExpr>(E)) { 9461 Pos = ParamPositions[FD]; 9462 } else { 9463 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl()) 9464 ->getCanonicalDecl(); 9465 Pos = ParamPositions[PVD]; 9466 } 9467 ParamAttrTy &ParamAttr = ParamAttrs[Pos]; 9468 ParamAttr.Kind = Linear; 9469 if (*SI) { 9470 Expr::EvalResult Result; 9471 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) { 9472 if (const auto *DRE = 9473 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) { 9474 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) { 9475 ParamAttr.Kind = LinearWithVarStride; 9476 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned( 9477 ParamPositions[StridePVD->getCanonicalDecl()]); 9478 } 9479 } 9480 } else { 9481 ParamAttr.StrideOrArg = Result.Val.getInt(); 9482 } 9483 } 9484 ++SI; 9485 ++MI; 9486 } 9487 llvm::APSInt VLENVal; 9488 if (const Expr *VLEN = Attr->getSimdlen()) 9489 VLENVal = VLEN->EvaluateKnownConstInt(C); 9490 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState(); 9491 if (CGM.getTriple().getArch() == llvm::Triple::x86 || 9492 CGM.getTriple().getArch() == llvm::Triple::x86_64) 9493 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State); 9494 } 9495 FD = FD->getPreviousDecl(); 9496 } 9497 } 9498 9499 namespace { 9500 /// Cleanup action for doacross support. 9501 class DoacrossCleanupTy final : public EHScopeStack::Cleanup { 9502 public: 9503 static const int DoacrossFinArgs = 2; 9504 9505 private: 9506 llvm::FunctionCallee RTLFn; 9507 llvm::Value *Args[DoacrossFinArgs]; 9508 9509 public: 9510 DoacrossCleanupTy(llvm::FunctionCallee RTLFn, 9511 ArrayRef<llvm::Value *> CallArgs) 9512 : RTLFn(RTLFn) { 9513 assert(CallArgs.size() == DoacrossFinArgs); 9514 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args)); 9515 } 9516 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { 9517 if (!CGF.HaveInsertPoint()) 9518 return; 9519 CGF.EmitRuntimeCall(RTLFn, Args); 9520 } 9521 }; 9522 } // namespace 9523 9524 void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF, 9525 const OMPLoopDirective &D, 9526 ArrayRef<Expr *> NumIterations) { 9527 if (!CGF.HaveInsertPoint()) 9528 return; 9529 9530 ASTContext &C = CGM.getContext(); 9531 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true); 9532 RecordDecl *RD; 9533 if (KmpDimTy.isNull()) { 9534 // Build struct kmp_dim { // loop bounds info casted to kmp_int64 9535 // kmp_int64 lo; // lower 9536 // kmp_int64 up; // upper 9537 // kmp_int64 st; // stride 9538 // }; 9539 RD = C.buildImplicitRecord("kmp_dim"); 9540 RD->startDefinition(); 9541 addFieldToRecordDecl(C, RD, Int64Ty); 9542 addFieldToRecordDecl(C, RD, Int64Ty); 9543 addFieldToRecordDecl(C, RD, Int64Ty); 9544 RD->completeDefinition(); 9545 KmpDimTy = C.getRecordType(RD); 9546 } else { 9547 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl()); 9548 } 9549 llvm::APInt Size(/*numBits=*/32, NumIterations.size()); 9550 QualType ArrayTy = 9551 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0); 9552 9553 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims"); 9554 CGF.EmitNullInitialization(DimsAddr, ArrayTy); 9555 enum { LowerFD = 0, UpperFD, StrideFD }; 9556 // Fill dims with data. 9557 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) { 9558 LValue DimsLVal = CGF.MakeAddrLValue( 9559 CGF.Builder.CreateConstArrayGEP(DimsAddr, I), KmpDimTy); 9560 // dims.upper = num_iterations; 9561 LValue UpperLVal = CGF.EmitLValueForField( 9562 DimsLVal, *std::next(RD->field_begin(), UpperFD)); 9563 llvm::Value *NumIterVal = 9564 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]), 9565 D.getNumIterations()->getType(), Int64Ty, 9566 D.getNumIterations()->getExprLoc()); 9567 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal); 9568 // dims.stride = 1; 9569 LValue StrideLVal = CGF.EmitLValueForField( 9570 DimsLVal, *std::next(RD->field_begin(), StrideFD)); 9571 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1), 9572 StrideLVal); 9573 } 9574 9575 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, 9576 // kmp_int32 num_dims, struct kmp_dim * dims); 9577 llvm::Value *Args[] = { 9578 emitUpdateLocation(CGF, D.getBeginLoc()), 9579 getThreadID(CGF, D.getBeginLoc()), 9580 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()), 9581 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 9582 CGF.Builder.CreateConstArrayGEP(DimsAddr, 0).getPointer(), 9583 CGM.VoidPtrTy)}; 9584 9585 llvm::FunctionCallee RTLFn = 9586 createRuntimeFunction(OMPRTL__kmpc_doacross_init); 9587 CGF.EmitRuntimeCall(RTLFn, Args); 9588 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = { 9589 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())}; 9590 llvm::FunctionCallee FiniRTLFn = 9591 createRuntimeFunction(OMPRTL__kmpc_doacross_fini); 9592 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn, 9593 llvm::makeArrayRef(FiniArgs)); 9594 } 9595 9596 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF, 9597 const OMPDependClause *C) { 9598 QualType Int64Ty = 9599 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 9600 llvm::APInt Size(/*numBits=*/32, C->getNumLoops()); 9601 QualType ArrayTy = CGM.getContext().getConstantArrayType( 9602 Int64Ty, Size, ArrayType::Normal, 0); 9603 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr"); 9604 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) { 9605 const Expr *CounterVal = C->getLoopData(I); 9606 assert(CounterVal); 9607 llvm::Value *CntVal = CGF.EmitScalarConversion( 9608 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty, 9609 CounterVal->getExprLoc()); 9610 CGF.EmitStoreOfScalar(CntVal, CGF.Builder.CreateConstArrayGEP(CntAddr, I), 9611 /*Volatile=*/false, Int64Ty); 9612 } 9613 llvm::Value *Args[] = { 9614 emitUpdateLocation(CGF, C->getBeginLoc()), 9615 getThreadID(CGF, C->getBeginLoc()), 9616 CGF.Builder.CreateConstArrayGEP(CntAddr, 0).getPointer()}; 9617 llvm::FunctionCallee RTLFn; 9618 if (C->getDependencyKind() == OMPC_DEPEND_source) { 9619 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post); 9620 } else { 9621 assert(C->getDependencyKind() == OMPC_DEPEND_sink); 9622 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait); 9623 } 9624 CGF.EmitRuntimeCall(RTLFn, Args); 9625 } 9626 9627 void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc, 9628 llvm::FunctionCallee Callee, 9629 ArrayRef<llvm::Value *> Args) const { 9630 assert(Loc.isValid() && "Outlined function call location must be valid."); 9631 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc); 9632 9633 if (auto *Fn = dyn_cast<llvm::Function>(Callee.getCallee())) { 9634 if (Fn->doesNotThrow()) { 9635 CGF.EmitNounwindRuntimeCall(Fn, Args); 9636 return; 9637 } 9638 } 9639 CGF.EmitRuntimeCall(Callee, Args); 9640 } 9641 9642 void CGOpenMPRuntime::emitOutlinedFunctionCall( 9643 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, 9644 ArrayRef<llvm::Value *> Args) const { 9645 emitCall(CGF, Loc, OutlinedFn, Args); 9646 } 9647 9648 Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF, 9649 const VarDecl *NativeParam, 9650 const VarDecl *TargetParam) const { 9651 return CGF.GetAddrOfLocalVar(NativeParam); 9652 } 9653 9654 Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF, 9655 const VarDecl *VD) { 9656 return Address::invalid(); 9657 } 9658 9659 llvm::Function *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction( 9660 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 9661 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { 9662 llvm_unreachable("Not supported in SIMD-only mode"); 9663 } 9664 9665 llvm::Function *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction( 9666 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 9667 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { 9668 llvm_unreachable("Not supported in SIMD-only mode"); 9669 } 9670 9671 llvm::Function *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction( 9672 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 9673 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 9674 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 9675 bool Tied, unsigned &NumberOfParts) { 9676 llvm_unreachable("Not supported in SIMD-only mode"); 9677 } 9678 9679 void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF, 9680 SourceLocation Loc, 9681 llvm::Function *OutlinedFn, 9682 ArrayRef<llvm::Value *> CapturedVars, 9683 const Expr *IfCond) { 9684 llvm_unreachable("Not supported in SIMD-only mode"); 9685 } 9686 9687 void CGOpenMPSIMDRuntime::emitCriticalRegion( 9688 CodeGenFunction &CGF, StringRef CriticalName, 9689 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, 9690 const Expr *Hint) { 9691 llvm_unreachable("Not supported in SIMD-only mode"); 9692 } 9693 9694 void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF, 9695 const RegionCodeGenTy &MasterOpGen, 9696 SourceLocation Loc) { 9697 llvm_unreachable("Not supported in SIMD-only mode"); 9698 } 9699 9700 void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF, 9701 SourceLocation Loc) { 9702 llvm_unreachable("Not supported in SIMD-only mode"); 9703 } 9704 9705 void CGOpenMPSIMDRuntime::emitTaskgroupRegion( 9706 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, 9707 SourceLocation Loc) { 9708 llvm_unreachable("Not supported in SIMD-only mode"); 9709 } 9710 9711 void CGOpenMPSIMDRuntime::emitSingleRegion( 9712 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, 9713 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, 9714 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, 9715 ArrayRef<const Expr *> AssignmentOps) { 9716 llvm_unreachable("Not supported in SIMD-only mode"); 9717 } 9718 9719 void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF, 9720 const RegionCodeGenTy &OrderedOpGen, 9721 SourceLocation Loc, 9722 bool IsThreads) { 9723 llvm_unreachable("Not supported in SIMD-only mode"); 9724 } 9725 9726 void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF, 9727 SourceLocation Loc, 9728 OpenMPDirectiveKind Kind, 9729 bool EmitChecks, 9730 bool ForceSimpleCall) { 9731 llvm_unreachable("Not supported in SIMD-only mode"); 9732 } 9733 9734 void CGOpenMPSIMDRuntime::emitForDispatchInit( 9735 CodeGenFunction &CGF, SourceLocation Loc, 9736 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, 9737 bool Ordered, const DispatchRTInput &DispatchValues) { 9738 llvm_unreachable("Not supported in SIMD-only mode"); 9739 } 9740 9741 void CGOpenMPSIMDRuntime::emitForStaticInit( 9742 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, 9743 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) { 9744 llvm_unreachable("Not supported in SIMD-only mode"); 9745 } 9746 9747 void CGOpenMPSIMDRuntime::emitDistributeStaticInit( 9748 CodeGenFunction &CGF, SourceLocation Loc, 9749 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) { 9750 llvm_unreachable("Not supported in SIMD-only mode"); 9751 } 9752 9753 void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF, 9754 SourceLocation Loc, 9755 unsigned IVSize, 9756 bool IVSigned) { 9757 llvm_unreachable("Not supported in SIMD-only mode"); 9758 } 9759 9760 void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF, 9761 SourceLocation Loc, 9762 OpenMPDirectiveKind DKind) { 9763 llvm_unreachable("Not supported in SIMD-only mode"); 9764 } 9765 9766 llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF, 9767 SourceLocation Loc, 9768 unsigned IVSize, bool IVSigned, 9769 Address IL, Address LB, 9770 Address UB, Address ST) { 9771 llvm_unreachable("Not supported in SIMD-only mode"); 9772 } 9773 9774 void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF, 9775 llvm::Value *NumThreads, 9776 SourceLocation Loc) { 9777 llvm_unreachable("Not supported in SIMD-only mode"); 9778 } 9779 9780 void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF, 9781 OpenMPProcBindClauseKind ProcBind, 9782 SourceLocation Loc) { 9783 llvm_unreachable("Not supported in SIMD-only mode"); 9784 } 9785 9786 Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF, 9787 const VarDecl *VD, 9788 Address VDAddr, 9789 SourceLocation Loc) { 9790 llvm_unreachable("Not supported in SIMD-only mode"); 9791 } 9792 9793 llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition( 9794 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, 9795 CodeGenFunction *CGF) { 9796 llvm_unreachable("Not supported in SIMD-only mode"); 9797 } 9798 9799 Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate( 9800 CodeGenFunction &CGF, QualType VarType, StringRef Name) { 9801 llvm_unreachable("Not supported in SIMD-only mode"); 9802 } 9803 9804 void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF, 9805 ArrayRef<const Expr *> Vars, 9806 SourceLocation Loc) { 9807 llvm_unreachable("Not supported in SIMD-only mode"); 9808 } 9809 9810 void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 9811 const OMPExecutableDirective &D, 9812 llvm::Function *TaskFunction, 9813 QualType SharedsTy, Address Shareds, 9814 const Expr *IfCond, 9815 const OMPTaskDataTy &Data) { 9816 llvm_unreachable("Not supported in SIMD-only mode"); 9817 } 9818 9819 void CGOpenMPSIMDRuntime::emitTaskLoopCall( 9820 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, 9821 llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, 9822 const Expr *IfCond, const OMPTaskDataTy &Data) { 9823 llvm_unreachable("Not supported in SIMD-only mode"); 9824 } 9825 9826 void CGOpenMPSIMDRuntime::emitReduction( 9827 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, 9828 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, 9829 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) { 9830 assert(Options.SimpleReduction && "Only simple reduction is expected."); 9831 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs, 9832 ReductionOps, Options); 9833 } 9834 9835 llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit( 9836 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, 9837 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) { 9838 llvm_unreachable("Not supported in SIMD-only mode"); 9839 } 9840 9841 void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF, 9842 SourceLocation Loc, 9843 ReductionCodeGen &RCG, 9844 unsigned N) { 9845 llvm_unreachable("Not supported in SIMD-only mode"); 9846 } 9847 9848 Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF, 9849 SourceLocation Loc, 9850 llvm::Value *ReductionsPtr, 9851 LValue SharedLVal) { 9852 llvm_unreachable("Not supported in SIMD-only mode"); 9853 } 9854 9855 void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF, 9856 SourceLocation Loc) { 9857 llvm_unreachable("Not supported in SIMD-only mode"); 9858 } 9859 9860 void CGOpenMPSIMDRuntime::emitCancellationPointCall( 9861 CodeGenFunction &CGF, SourceLocation Loc, 9862 OpenMPDirectiveKind CancelRegion) { 9863 llvm_unreachable("Not supported in SIMD-only mode"); 9864 } 9865 9866 void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF, 9867 SourceLocation Loc, const Expr *IfCond, 9868 OpenMPDirectiveKind CancelRegion) { 9869 llvm_unreachable("Not supported in SIMD-only mode"); 9870 } 9871 9872 void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction( 9873 const OMPExecutableDirective &D, StringRef ParentName, 9874 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, 9875 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { 9876 llvm_unreachable("Not supported in SIMD-only mode"); 9877 } 9878 9879 void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF, 9880 const OMPExecutableDirective &D, 9881 llvm::Function *OutlinedFn, 9882 llvm::Value *OutlinedFnID, 9883 const Expr *IfCond, 9884 const Expr *Device) { 9885 llvm_unreachable("Not supported in SIMD-only mode"); 9886 } 9887 9888 bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) { 9889 llvm_unreachable("Not supported in SIMD-only mode"); 9890 } 9891 9892 bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) { 9893 llvm_unreachable("Not supported in SIMD-only mode"); 9894 } 9895 9896 bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) { 9897 return false; 9898 } 9899 9900 llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() { 9901 return nullptr; 9902 } 9903 9904 void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF, 9905 const OMPExecutableDirective &D, 9906 SourceLocation Loc, 9907 llvm::Function *OutlinedFn, 9908 ArrayRef<llvm::Value *> CapturedVars) { 9909 llvm_unreachable("Not supported in SIMD-only mode"); 9910 } 9911 9912 void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF, 9913 const Expr *NumTeams, 9914 const Expr *ThreadLimit, 9915 SourceLocation Loc) { 9916 llvm_unreachable("Not supported in SIMD-only mode"); 9917 } 9918 9919 void CGOpenMPSIMDRuntime::emitTargetDataCalls( 9920 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, 9921 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) { 9922 llvm_unreachable("Not supported in SIMD-only mode"); 9923 } 9924 9925 void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall( 9926 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, 9927 const Expr *Device) { 9928 llvm_unreachable("Not supported in SIMD-only mode"); 9929 } 9930 9931 void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF, 9932 const OMPLoopDirective &D, 9933 ArrayRef<Expr *> NumIterations) { 9934 llvm_unreachable("Not supported in SIMD-only mode"); 9935 } 9936 9937 void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF, 9938 const OMPDependClause *C) { 9939 llvm_unreachable("Not supported in SIMD-only mode"); 9940 } 9941 9942 const VarDecl * 9943 CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD, 9944 const VarDecl *NativeParam) const { 9945 llvm_unreachable("Not supported in SIMD-only mode"); 9946 } 9947 9948 Address 9949 CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF, 9950 const VarDecl *NativeParam, 9951 const VarDecl *TargetParam) const { 9952 llvm_unreachable("Not supported in SIMD-only mode"); 9953 } 9954