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