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