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