blob: 534d148209baf30b5f9f26241f93026964cb9084 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- 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 "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
Alexey Bataev36bf0112015-03-10 05:15:26 +000016#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000017#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000020#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Value.h"
24#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000025#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000026
27using namespace clang;
28using namespace CodeGen;
29
Benjamin Kramerc52193f2014-10-10 13:57:57 +000030namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000031/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000032class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
33public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000034 /// \brief Kinds of OpenMP regions used in codegen.
35 enum CGOpenMPRegionKind {
36 /// \brief Region with outlined function for standalone 'parallel'
37 /// directive.
38 ParallelOutlinedRegion,
39 /// \brief Region with outlined function for standalone 'task' directive.
40 TaskOutlinedRegion,
41 /// \brief Region for constructs that do not require function outlining,
42 /// like 'for', 'sections', 'atomic' etc. directives.
43 InlinedRegion,
44 };
Alexey Bataev18095712014-10-10 12:19:54 +000045
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 CGOpenMPRegionInfo(const CapturedStmt &CS,
47 const CGOpenMPRegionKind RegionKind,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000048 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev81c7ea02015-07-03 09:56:58 +000050 CodeGen(CodeGen), Kind(Kind) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051
52 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind)
54 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
55 Kind(Kind) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000056
57 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000058 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000059 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000060
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000061 /// \brief Emit the captured statement body.
62 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
63
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000065 /// \return LValue for thread id variable. This LValue always has type int32*.
66 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069
Alexey Bataev81c7ea02015-07-03 09:56:58 +000070 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
71
Alexey Bataev18095712014-10-10 12:19:54 +000072 static bool classof(const CGCapturedStmtInfo *Info) {
73 return Info->getKind() == CR_OpenMP;
74 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000076protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000077 CGOpenMPRegionKind RegionKind;
78 const RegionCodeGenTy &CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000079 OpenMPDirectiveKind Kind;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080};
Alexey Bataev18095712014-10-10 12:19:54 +000081
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000082/// \brief API for captured statement code generation in OpenMP constructs.
83class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
84public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000085 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000086 const RegionCodeGenTy &CodeGen,
87 OpenMPDirectiveKind Kind)
88 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000089 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
91 }
92 /// \brief Get a variable or parameter for storing global thread id
93 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +000094 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095
Alexey Bataev18095712014-10-10 12:19:54 +000096 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +000097 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +000098
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000099 static bool classof(const CGCapturedStmtInfo *Info) {
100 return CGOpenMPRegionInfo::classof(Info) &&
101 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
102 ParallelOutlinedRegion;
103 }
104
Alexey Bataev18095712014-10-10 12:19:54 +0000105private:
106 /// \brief A variable or parameter storing global thread id for OpenMP
107 /// constructs.
108 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109};
110
Alexey Bataev62b63b12015-03-10 07:28:44 +0000111/// \brief API for captured statement code generation in OpenMP constructs.
112class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
113public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000115 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000116 const RegionCodeGenTy &CodeGen,
117 OpenMPDirectiveKind Kind)
118 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000119 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000120 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
121 }
122 /// \brief Get a variable or parameter for storing global thread id
123 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000124 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000125
126 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000127 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000128
Alexey Bataev62b63b12015-03-10 07:28:44 +0000129 /// \brief Get the name of the capture helper.
130 StringRef getHelperName() const override { return ".omp_outlined."; }
131
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000132 static bool classof(const CGCapturedStmtInfo *Info) {
133 return CGOpenMPRegionInfo::classof(Info) &&
134 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
135 TaskOutlinedRegion;
136 }
137
Alexey Bataev62b63b12015-03-10 07:28:44 +0000138private:
139 /// \brief A variable or parameter storing global thread id for OpenMP
140 /// constructs.
141 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000142};
143
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000144/// \brief API for inlined captured statement code generation in OpenMP
145/// constructs.
146class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
147public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000148 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000149 const RegionCodeGenTy &CodeGen,
150 OpenMPDirectiveKind Kind)
151 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind), OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000152 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
153 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000154 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000155 if (OuterRegionInfo)
156 return OuterRegionInfo->getContextValue();
157 llvm_unreachable("No context value for inlined OpenMP region");
158 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000159 virtual void setContextValue(llvm::Value *V) override {
160 if (OuterRegionInfo) {
161 OuterRegionInfo->setContextValue(V);
162 return;
163 }
164 llvm_unreachable("No context value for inlined OpenMP region");
165 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000166 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000167 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000168 if (OuterRegionInfo)
169 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000170 // If there is no outer outlined region,no need to lookup in a list of
171 // captured variables, we can use the original one.
172 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000173 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000174 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000175 if (OuterRegionInfo)
176 return OuterRegionInfo->getThisFieldDecl();
177 return nullptr;
178 }
179 /// \brief Get a variable or parameter for storing global thread id
180 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000181 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000182 if (OuterRegionInfo)
183 return OuterRegionInfo->getThreadIDVariable();
184 return nullptr;
185 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000186
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000187 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000188 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000189 if (auto *OuterRegionInfo = getOldCSI())
190 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000191 llvm_unreachable("No helper name for inlined OpenMP construct");
192 }
193
194 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
195
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000196 static bool classof(const CGCapturedStmtInfo *Info) {
197 return CGOpenMPRegionInfo::classof(Info) &&
198 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
199 }
200
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000201private:
202 /// \brief CodeGen info about outer OpenMP region.
203 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
204 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000205};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000206
207/// \brief RAII for emitting code of OpenMP constructs.
208class InlinedOpenMPRegionRAII {
209 CodeGenFunction &CGF;
210
211public:
212 /// \brief Constructs region for combined constructs.
213 /// \param CodeGen Code generation sequence for combined directives. Includes
214 /// a list of functions used for code generation of implicitly inlined
215 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000216 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
217 OpenMPDirectiveKind Kind)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000218 : CGF(CGF) {
219 // Start emission for the construct.
220 CGF.CapturedStmtInfo =
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000221 new CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, CodeGen, Kind);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000222 }
223 ~InlinedOpenMPRegionRAII() {
224 // Restore original CapturedStmtInfo only if we're done with code emission.
225 auto *OldCSI =
226 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
227 delete CGF.CapturedStmtInfo;
228 CGF.CapturedStmtInfo = OldCSI;
229 }
230};
231
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000232} // namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000233
234LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
235 return CGF.MakeNaturalAlignAddrLValue(
Alexey Bataev62b63b12015-03-10 07:28:44 +0000236 CGF.Builder.CreateAlignedLoad(
237 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
238 CGF.PointerAlignInBytes),
239 getThreadIDVariable()
240 ->getType()
241 ->castAs<PointerType>()
242 ->getPointeeType());
Alexey Bataev18095712014-10-10 12:19:54 +0000243}
244
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000245void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
246 // 1.2.2 OpenMP Language Terminology
247 // Structured block - An executable statement with a single entry at the
248 // top and a single exit at the bottom.
249 // The point of exit cannot be a branch out of the structured block.
250 // longjmp() and throw() must not violate the entry/exit criteria.
251 CGF.EHStack.pushTerminate();
252 {
253 CodeGenFunction::RunCleanupsScope Scope(CGF);
254 CodeGen(CGF);
255 }
256 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000257}
258
Alexey Bataev62b63b12015-03-10 07:28:44 +0000259LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
260 CodeGenFunction &CGF) {
261 return CGF.MakeNaturalAlignAddrLValue(
262 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
263 getThreadIDVariable()->getType());
264}
265
Alexey Bataev9959db52014-05-06 10:08:46 +0000266CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000268 IdentTy = llvm::StructType::create(
269 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
270 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000271 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000272 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000273 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
274 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000275 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000276 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000277}
278
Alexey Bataev91797552015-03-18 04:13:55 +0000279void CGOpenMPRuntime::clear() {
280 InternalVars.clear();
281}
282
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000283llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
284 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
285 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000286 assert(ThreadIDVar->getType()->isPointerType() &&
287 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000288 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
289 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000290 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind);
Alexey Bataevd157d472015-06-24 03:35:38 +0000291 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev18095712014-10-10 12:19:54 +0000292 return CGF.GenerateCapturedStmtFunction(*CS);
293}
294
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000295llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
296 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
297 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000298 assert(!ThreadIDVar->getType()->isPointerType() &&
299 "thread id variable must be of type kmp_int32 for tasks");
300 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
301 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000302 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
303 InnermostKind);
Alexey Bataevd157d472015-06-24 03:35:38 +0000304 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000305 return CGF.GenerateCapturedStmtFunction(*CS);
306}
307
308llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000309CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000310 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000311 if (!Entry) {
312 if (!DefaultOpenMPPSource) {
313 // Initialize default location for psource field of ident_t structure of
314 // all ident_t objects. Format is ";file;function;line;column;;".
315 // Taken from
316 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
317 DefaultOpenMPPSource =
318 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
319 DefaultOpenMPPSource =
320 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
321 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000322 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
323 CGM.getModule(), IdentTy, /*isConstant*/ true,
324 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000325 DefaultOpenMPLocation->setUnnamedAddr(true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000326
327 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000328 llvm::Constant *Values[] = {Zero,
329 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
330 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000331 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
332 DefaultOpenMPLocation->setInitializer(Init);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000333 OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000334 return DefaultOpenMPLocation;
335 }
336 return Entry;
337}
338
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000339llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
340 SourceLocation Loc,
341 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000342 // If no debug info is generated - return global default location.
343 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
344 Loc.isInvalid())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000345 return getOrCreateDefaultLocation(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000346
347 assert(CGF.CurFn && "No function in current CodeGenFunction.");
348
Alexey Bataev9959db52014-05-06 10:08:46 +0000349 llvm::Value *LocValue = nullptr;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000350 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
351 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataev18095712014-10-10 12:19:54 +0000352 LocValue = I->second.DebugLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +0000353 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
354 // GetOpenMPThreadID was called before this routine.
355 if (LocValue == nullptr) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000356 // Generate "ident_t .kmpc_loc.addr;"
357 llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
Alexey Bataev9959db52014-05-06 10:08:46 +0000358 AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
Alexey Bataev18095712014-10-10 12:19:54 +0000359 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
360 Elem.second.DebugLoc = AI;
Alexey Bataev9959db52014-05-06 10:08:46 +0000361 LocValue = AI;
362
363 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
364 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000365 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataev9959db52014-05-06 10:08:46 +0000366 llvm::ConstantExpr::getSizeOf(IdentTy),
367 CGM.PointerAlignInBytes);
368 }
369
370 // char **psource = &.kmpc_loc_<flags>.addr.psource;
David Blaikie1ed728c2015-04-05 22:45:47 +0000371 auto *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(IdentTy, LocValue, 0,
372 IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000373
Alexey Bataevf002aca2014-05-30 05:48:40 +0000374 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
375 if (OMPDebugLoc == nullptr) {
376 SmallString<128> Buffer2;
377 llvm::raw_svector_ostream OS2(Buffer2);
378 // Build debug location
379 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
380 OS2 << ";" << PLoc.getFilename() << ";";
381 if (const FunctionDecl *FD =
382 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
383 OS2 << FD->getQualifiedNameAsString();
384 }
385 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
386 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
387 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000388 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000389 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000390 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
391
Alexey Bataev9959db52014-05-06 10:08:46 +0000392 return LocValue;
393}
394
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000395llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
396 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000397 assert(CGF.CurFn && "No function in current CodeGenFunction.");
398
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000399 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000400 // Check whether we've already cached a load of the thread id in this
401 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000402 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000403 if (I != OpenMPLocThreadIDMap.end()) {
404 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000405 if (ThreadID != nullptr)
406 return ThreadID;
407 }
408 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000409 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000410 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000411 // Check if this an outlined function with thread id passed as argument.
412 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000413 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
414 // If value loaded in entry block, cache it and use it everywhere in
415 // function.
416 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
417 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
418 Elem.second.ThreadID = ThreadID;
419 }
420 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000421 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000422 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000423
424 // This is not an outlined function region - need to call __kmpc_int32
425 // kmpc_global_thread_num(ident_t *loc).
426 // Generate thread id value and cache this value for use across the
427 // function.
428 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
429 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
430 ThreadID =
431 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
432 emitUpdateLocation(CGF, Loc));
433 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
434 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000435 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000436}
437
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000438void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000439 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000440 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
441 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000442}
443
444llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
445 return llvm::PointerType::getUnqual(IdentTy);
446}
447
448llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
449 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
450}
451
452llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000453CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000454 llvm::Constant *RTLFn = nullptr;
455 switch (Function) {
456 case OMPRTL__kmpc_fork_call: {
457 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
458 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000459 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
460 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000461 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000462 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000463 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
464 break;
465 }
466 case OMPRTL__kmpc_global_thread_num: {
467 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000468 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000469 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000470 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000471 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
472 break;
473 }
Alexey Bataev97720002014-11-11 04:05:39 +0000474 case OMPRTL__kmpc_threadprivate_cached: {
475 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
476 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
477 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
478 CGM.VoidPtrTy, CGM.SizeTy,
479 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
480 llvm::FunctionType *FnTy =
481 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
482 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
483 break;
484 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000485 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000486 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
487 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000488 llvm::Type *TypeParams[] = {
489 getIdentTyPointerTy(), CGM.Int32Ty,
490 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
491 llvm::FunctionType *FnTy =
492 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
493 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
494 break;
495 }
Alexey Bataev97720002014-11-11 04:05:39 +0000496 case OMPRTL__kmpc_threadprivate_register: {
497 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
498 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
499 // typedef void *(*kmpc_ctor)(void *);
500 auto KmpcCtorTy =
501 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
502 /*isVarArg*/ false)->getPointerTo();
503 // typedef void *(*kmpc_cctor)(void *, void *);
504 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
505 auto KmpcCopyCtorTy =
506 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
507 /*isVarArg*/ false)->getPointerTo();
508 // typedef void (*kmpc_dtor)(void *);
509 auto KmpcDtorTy =
510 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
511 ->getPointerTo();
512 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
513 KmpcCopyCtorTy, KmpcDtorTy};
514 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
515 /*isVarArg*/ false);
516 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
517 break;
518 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000519 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000520 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
521 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000522 llvm::Type *TypeParams[] = {
523 getIdentTyPointerTy(), CGM.Int32Ty,
524 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
525 llvm::FunctionType *FnTy =
526 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
527 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
528 break;
529 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000530 case OMPRTL__kmpc_cancel_barrier: {
531 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
532 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000533 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
534 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000535 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
536 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000537 break;
538 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000539 case OMPRTL__kmpc_barrier: {
540 // Build void __kmpc_cancel_barrier(ident_t *loc, kmp_int32 global_tid);
541 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
542 llvm::FunctionType *FnTy =
543 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
544 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
545 break;
546 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000547 case OMPRTL__kmpc_for_static_fini: {
548 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
549 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
550 llvm::FunctionType *FnTy =
551 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
552 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
553 break;
554 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000555 case OMPRTL__kmpc_push_num_threads: {
556 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
557 // kmp_int32 num_threads)
558 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
559 CGM.Int32Ty};
560 llvm::FunctionType *FnTy =
561 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
562 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
563 break;
564 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000565 case OMPRTL__kmpc_serialized_parallel: {
566 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
567 // global_tid);
568 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
569 llvm::FunctionType *FnTy =
570 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
571 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
572 break;
573 }
574 case OMPRTL__kmpc_end_serialized_parallel: {
575 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
576 // global_tid);
577 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
578 llvm::FunctionType *FnTy =
579 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
580 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
581 break;
582 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000583 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000584 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000585 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
586 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000587 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000588 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
589 break;
590 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000591 case OMPRTL__kmpc_master: {
592 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
593 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
594 llvm::FunctionType *FnTy =
595 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
596 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
597 break;
598 }
599 case OMPRTL__kmpc_end_master: {
600 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
601 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
602 llvm::FunctionType *FnTy =
603 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
604 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
605 break;
606 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000607 case OMPRTL__kmpc_omp_taskyield: {
608 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
609 // int end_part);
610 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
611 llvm::FunctionType *FnTy =
612 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
613 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
614 break;
615 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000616 case OMPRTL__kmpc_single: {
617 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
618 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
619 llvm::FunctionType *FnTy =
620 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
621 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
622 break;
623 }
624 case OMPRTL__kmpc_end_single: {
625 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
626 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
627 llvm::FunctionType *FnTy =
628 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
629 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
630 break;
631 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000632 case OMPRTL__kmpc_omp_task_alloc: {
633 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
634 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
635 // kmp_routine_entry_t *task_entry);
636 assert(KmpRoutineEntryPtrTy != nullptr &&
637 "Type kmp_routine_entry_t must be created.");
638 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
639 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
640 // Return void * and then cast to particular kmp_task_t type.
641 llvm::FunctionType *FnTy =
642 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
643 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
644 break;
645 }
646 case OMPRTL__kmpc_omp_task: {
647 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
648 // *new_task);
649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
650 CGM.VoidPtrTy};
651 llvm::FunctionType *FnTy =
652 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
653 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
654 break;
655 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000656 case OMPRTL__kmpc_copyprivate: {
657 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +0000658 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +0000659 // kmp_int32 didit);
660 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
661 auto *CpyFnTy =
662 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +0000663 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +0000664 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
665 CGM.Int32Ty};
666 llvm::FunctionType *FnTy =
667 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
668 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
669 break;
670 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000671 case OMPRTL__kmpc_reduce: {
672 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
673 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
674 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
675 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
676 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
677 /*isVarArg=*/false);
678 llvm::Type *TypeParams[] = {
679 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
680 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
681 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
682 llvm::FunctionType *FnTy =
683 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
684 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
685 break;
686 }
687 case OMPRTL__kmpc_reduce_nowait: {
688 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
689 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
690 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
691 // *lck);
692 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
693 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
694 /*isVarArg=*/false);
695 llvm::Type *TypeParams[] = {
696 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
697 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
698 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
699 llvm::FunctionType *FnTy =
700 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
701 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
702 break;
703 }
704 case OMPRTL__kmpc_end_reduce: {
705 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
706 // kmp_critical_name *lck);
707 llvm::Type *TypeParams[] = {
708 getIdentTyPointerTy(), CGM.Int32Ty,
709 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
710 llvm::FunctionType *FnTy =
711 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
712 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
713 break;
714 }
715 case OMPRTL__kmpc_end_reduce_nowait: {
716 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
717 // kmp_critical_name *lck);
718 llvm::Type *TypeParams[] = {
719 getIdentTyPointerTy(), CGM.Int32Ty,
720 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
721 llvm::FunctionType *FnTy =
722 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
723 RTLFn =
724 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
725 break;
726 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000727 case OMPRTL__kmpc_omp_task_begin_if0: {
728 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
729 // *new_task);
730 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
731 CGM.VoidPtrTy};
732 llvm::FunctionType *FnTy =
733 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
734 RTLFn =
735 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
736 break;
737 }
738 case OMPRTL__kmpc_omp_task_complete_if0: {
739 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
740 // *new_task);
741 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
742 CGM.VoidPtrTy};
743 llvm::FunctionType *FnTy =
744 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
745 RTLFn = CGM.CreateRuntimeFunction(FnTy,
746 /*Name=*/"__kmpc_omp_task_complete_if0");
747 break;
748 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000749 case OMPRTL__kmpc_ordered: {
750 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
751 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
752 llvm::FunctionType *FnTy =
753 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
754 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
755 break;
756 }
757 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000758 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000759 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
760 llvm::FunctionType *FnTy =
761 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
762 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
763 break;
764 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +0000765 case OMPRTL__kmpc_omp_taskwait: {
766 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
767 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
768 llvm::FunctionType *FnTy =
769 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
770 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
771 break;
772 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000773 case OMPRTL__kmpc_taskgroup: {
774 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
775 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
776 llvm::FunctionType *FnTy =
777 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
778 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
779 break;
780 }
781 case OMPRTL__kmpc_end_taskgroup: {
782 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
783 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
784 llvm::FunctionType *FnTy =
785 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
786 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
787 break;
788 }
Alexey Bataev7f210c62015-06-18 13:40:03 +0000789 case OMPRTL__kmpc_push_proc_bind: {
790 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
791 // int proc_bind)
792 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
793 llvm::FunctionType *FnTy =
794 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
795 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
796 break;
797 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +0000798 case OMPRTL__kmpc_omp_task_with_deps: {
799 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
800 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
801 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
802 llvm::Type *TypeParams[] = {
803 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
804 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
805 llvm::FunctionType *FnTy =
806 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
807 RTLFn =
808 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
809 break;
810 }
811 case OMPRTL__kmpc_omp_wait_deps: {
812 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
813 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
814 // kmp_depend_info_t *noalias_dep_list);
815 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
816 CGM.Int32Ty, CGM.VoidPtrTy,
817 CGM.Int32Ty, CGM.VoidPtrTy};
818 llvm::FunctionType *FnTy =
819 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
820 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
821 break;
822 }
Alexey Bataev0f34da12015-07-02 04:17:07 +0000823 case OMPRTL__kmpc_cancellationpoint: {
824 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
825 // global_tid, kmp_int32 cncl_kind)
826 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
827 llvm::FunctionType *FnTy =
828 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
829 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
830 break;
831 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000832 }
833 return RTLFn;
834}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000835
Alexander Musman21212e42015-03-13 10:38:23 +0000836llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
837 bool IVSigned) {
838 assert((IVSize == 32 || IVSize == 64) &&
839 "IV size is not compatible with the omp runtime");
840 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
841 : "__kmpc_for_static_init_4u")
842 : (IVSigned ? "__kmpc_for_static_init_8"
843 : "__kmpc_for_static_init_8u");
844 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
845 auto PtrTy = llvm::PointerType::getUnqual(ITy);
846 llvm::Type *TypeParams[] = {
847 getIdentTyPointerTy(), // loc
848 CGM.Int32Ty, // tid
849 CGM.Int32Ty, // schedtype
850 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
851 PtrTy, // p_lower
852 PtrTy, // p_upper
853 PtrTy, // p_stride
854 ITy, // incr
855 ITy // chunk
856 };
857 llvm::FunctionType *FnTy =
858 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
859 return CGM.CreateRuntimeFunction(FnTy, Name);
860}
861
Alexander Musman92bdaab2015-03-12 13:37:50 +0000862llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
863 bool IVSigned) {
864 assert((IVSize == 32 || IVSize == 64) &&
865 "IV size is not compatible with the omp runtime");
866 auto Name =
867 IVSize == 32
868 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
869 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
870 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
871 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
872 CGM.Int32Ty, // tid
873 CGM.Int32Ty, // schedtype
874 ITy, // lower
875 ITy, // upper
876 ITy, // stride
877 ITy // chunk
878 };
879 llvm::FunctionType *FnTy =
880 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
881 return CGM.CreateRuntimeFunction(FnTy, Name);
882}
883
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000884llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
885 bool IVSigned) {
886 assert((IVSize == 32 || IVSize == 64) &&
887 "IV size is not compatible with the omp runtime");
888 auto Name =
889 IVSize == 32
890 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
891 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
892 llvm::Type *TypeParams[] = {
893 getIdentTyPointerTy(), // loc
894 CGM.Int32Ty, // tid
895 };
896 llvm::FunctionType *FnTy =
897 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
898 return CGM.CreateRuntimeFunction(FnTy, Name);
899}
900
Alexander Musman92bdaab2015-03-12 13:37:50 +0000901llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
902 bool IVSigned) {
903 assert((IVSize == 32 || IVSize == 64) &&
904 "IV size is not compatible with the omp runtime");
905 auto Name =
906 IVSize == 32
907 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
908 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
909 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
910 auto PtrTy = llvm::PointerType::getUnqual(ITy);
911 llvm::Type *TypeParams[] = {
912 getIdentTyPointerTy(), // loc
913 CGM.Int32Ty, // tid
914 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
915 PtrTy, // p_lower
916 PtrTy, // p_upper
917 PtrTy // p_stride
918 };
919 llvm::FunctionType *FnTy =
920 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
921 return CGM.CreateRuntimeFunction(FnTy, Name);
922}
923
Alexey Bataev97720002014-11-11 04:05:39 +0000924llvm::Constant *
925CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
926 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000927 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000928 Twine(CGM.getMangledName(VD)) + ".cache.");
929}
930
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000931llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
932 const VarDecl *VD,
933 llvm::Value *VDAddr,
934 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000935 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000936 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000937 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
938 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
939 getOrCreateThreadPrivateCache(VD)};
940 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000941 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000942}
943
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000944void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000945 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
946 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
947 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
948 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000949 auto OMPLoc = emitUpdateLocation(CGF, Loc);
950 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000951 OMPLoc);
952 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
953 // to register constructor/destructor for variable.
954 llvm::Value *Args[] = {OMPLoc,
955 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
956 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000957 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000958 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000959}
960
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000961llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000962 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
963 bool PerformInit, CodeGenFunction *CGF) {
964 VD = VD->getDefinition(CGM.getContext());
965 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
966 ThreadPrivateWithDefinition.insert(VD);
967 QualType ASTTy = VD->getType();
968
969 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
970 auto Init = VD->getAnyInitializer();
971 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
972 // Generate function that re-emits the declaration's initializer into the
973 // threadprivate copy of the variable VD
974 CodeGenFunction CtorCGF(CGM);
975 FunctionArgList Args;
976 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
977 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
978 Args.push_back(&Dst);
979
980 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
981 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
982 /*isVariadic=*/false);
983 auto FTy = CGM.getTypes().GetFunctionType(FI);
984 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
985 FTy, ".__kmpc_global_ctor_.", Loc);
986 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
987 Args, SourceLocation());
988 auto ArgVal = CtorCGF.EmitLoadOfScalar(
989 CtorCGF.GetAddrOfLocalVar(&Dst),
990 /*Volatile=*/false, CGM.PointerAlignInBytes,
991 CGM.getContext().VoidPtrTy, Dst.getLocation());
992 auto Arg = CtorCGF.Builder.CreatePointerCast(
993 ArgVal,
994 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
995 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
996 /*IsInitializer=*/true);
997 ArgVal = CtorCGF.EmitLoadOfScalar(
998 CtorCGF.GetAddrOfLocalVar(&Dst),
999 /*Volatile=*/false, CGM.PointerAlignInBytes,
1000 CGM.getContext().VoidPtrTy, Dst.getLocation());
1001 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1002 CtorCGF.FinishFunction();
1003 Ctor = Fn;
1004 }
1005 if (VD->getType().isDestructedType() != QualType::DK_none) {
1006 // Generate function that emits destructor call for the threadprivate copy
1007 // of the variable VD
1008 CodeGenFunction DtorCGF(CGM);
1009 FunctionArgList Args;
1010 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1011 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1012 Args.push_back(&Dst);
1013
1014 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1015 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1016 /*isVariadic=*/false);
1017 auto FTy = CGM.getTypes().GetFunctionType(FI);
1018 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1019 FTy, ".__kmpc_global_dtor_.", Loc);
1020 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1021 SourceLocation());
1022 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1023 DtorCGF.GetAddrOfLocalVar(&Dst),
1024 /*Volatile=*/false, CGM.PointerAlignInBytes,
1025 CGM.getContext().VoidPtrTy, Dst.getLocation());
1026 DtorCGF.emitDestroy(ArgVal, ASTTy,
1027 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1028 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1029 DtorCGF.FinishFunction();
1030 Dtor = Fn;
1031 }
1032 // Do not emit init function if it is not required.
1033 if (!Ctor && !Dtor)
1034 return nullptr;
1035
1036 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1037 auto CopyCtorTy =
1038 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1039 /*isVarArg=*/false)->getPointerTo();
1040 // Copying constructor for the threadprivate variable.
1041 // Must be NULL - reserved by runtime, but currently it requires that this
1042 // parameter is always NULL. Otherwise it fires assertion.
1043 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1044 if (Ctor == nullptr) {
1045 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1046 /*isVarArg=*/false)->getPointerTo();
1047 Ctor = llvm::Constant::getNullValue(CtorTy);
1048 }
1049 if (Dtor == nullptr) {
1050 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1051 /*isVarArg=*/false)->getPointerTo();
1052 Dtor = llvm::Constant::getNullValue(DtorTy);
1053 }
1054 if (!CGF) {
1055 auto InitFunctionTy =
1056 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1057 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1058 InitFunctionTy, ".__omp_threadprivate_init_.");
1059 CodeGenFunction InitCGF(CGM);
1060 FunctionArgList ArgList;
1061 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1062 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1063 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001064 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001065 InitCGF.FinishFunction();
1066 return InitFunction;
1067 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001068 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001069 }
1070 return nullptr;
1071}
1072
Alexey Bataev1d677132015-04-22 13:57:31 +00001073/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1074/// function. Here is the logic:
1075/// if (Cond) {
1076/// ThenGen();
1077/// } else {
1078/// ElseGen();
1079/// }
1080static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1081 const RegionCodeGenTy &ThenGen,
1082 const RegionCodeGenTy &ElseGen) {
1083 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1084
1085 // If the condition constant folds and can be elided, try to avoid emitting
1086 // the condition and the dead arm of the if/else.
1087 bool CondConstant;
1088 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1089 CodeGenFunction::RunCleanupsScope Scope(CGF);
1090 if (CondConstant) {
1091 ThenGen(CGF);
1092 } else {
1093 ElseGen(CGF);
1094 }
1095 return;
1096 }
1097
1098 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1099 // emit the conditional branch.
1100 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1101 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1102 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1103 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1104
1105 // Emit the 'then' code.
1106 CGF.EmitBlock(ThenBlock);
1107 {
1108 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1109 ThenGen(CGF);
1110 }
1111 CGF.EmitBranch(ContBlock);
1112 // Emit the 'else' code if present.
1113 {
1114 // There is no need to emit line number for unconditional branch.
1115 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1116 CGF.EmitBlock(ElseBlock);
1117 }
1118 {
1119 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1120 ElseGen(CGF);
1121 }
1122 {
1123 // There is no need to emit line number for unconditional branch.
1124 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1125 CGF.EmitBranch(ContBlock);
1126 }
1127 // Emit the continuation block for code after the if.
1128 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001129}
1130
Alexey Bataev1d677132015-04-22 13:57:31 +00001131void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1132 llvm::Value *OutlinedFn,
1133 llvm::Value *CapturedStruct,
1134 const Expr *IfCond) {
1135 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1136 auto &&ThenGen =
1137 [this, OutlinedFn, CapturedStruct, RTLoc](CodeGenFunction &CGF) {
1138 // Build call __kmpc_fork_call(loc, 1, microtask,
1139 // captured_struct/*context*/)
1140 llvm::Value *Args[] = {
1141 RTLoc,
1142 CGF.Builder.getInt32(
1143 1), // Number of arguments after 'microtask' argument
1144 // (there is only one additional argument - 'context')
1145 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
1146 CGF.EmitCastToVoidPtr(CapturedStruct)};
1147 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1148 CGF.EmitRuntimeCall(RTLFn, Args);
1149 };
1150 auto &&ElseGen = [this, OutlinedFn, CapturedStruct, RTLoc, Loc](
1151 CodeGenFunction &CGF) {
1152 auto ThreadID = getThreadID(CGF, Loc);
1153 // Build calls:
1154 // __kmpc_serialized_parallel(&Loc, GTid);
1155 llvm::Value *Args[] = {RTLoc, ThreadID};
1156 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1157 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001158
Alexey Bataev1d677132015-04-22 13:57:31 +00001159 // OutlinedFn(&GTid, &zero, CapturedStruct);
1160 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1161 auto Int32Ty = CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32,
1162 /*Signed*/ true);
1163 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
1164 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1165 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
1166 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001167
Alexey Bataev1d677132015-04-22 13:57:31 +00001168 // __kmpc_end_serialized_parallel(&Loc, GTid);
1169 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1170 CGF.EmitRuntimeCall(
1171 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1172 };
1173 if (IfCond) {
1174 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1175 } else {
1176 CodeGenFunction::RunCleanupsScope Scope(CGF);
1177 ThenGen(CGF);
1178 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001179}
1180
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001181// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001182// thread-ID variable (it is passed in a first argument of the outlined function
1183// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1184// regular serial code region, get thread ID by calling kmp_int32
1185// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1186// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001187llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +00001188 SourceLocation Loc) {
1189 if (auto OMPRegionInfo =
1190 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001191 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001192 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001193
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001194 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001195 auto Int32Ty =
1196 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1197 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1198 CGF.EmitStoreOfScalar(ThreadID,
1199 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
1200
1201 return ThreadIDTemp;
1202}
1203
Alexey Bataev97720002014-11-11 04:05:39 +00001204llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001205CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001206 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001207 SmallString<256> Buffer;
1208 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001209 Out << Name;
1210 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001211 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1212 if (Elem.second) {
1213 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001214 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001215 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001216 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001217
David Blaikie13156b62014-11-19 03:06:06 +00001218 return Elem.second = new llvm::GlobalVariable(
1219 CGM.getModule(), Ty, /*IsConstant*/ false,
1220 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1221 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001222}
1223
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001224llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001225 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001226 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001227}
1228
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001229namespace {
Alexey Bataeva744ff52015-05-05 09:24:37 +00001230template <size_t N> class CallEndCleanup : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001231 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001232 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001233
1234public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001235 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1236 : Callee(Callee) {
1237 assert(CleanupArgs.size() == N);
1238 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1239 }
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001240 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1241 CGF.EmitRuntimeCall(Callee, Args);
1242 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001243};
1244} // namespace
1245
1246void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1247 StringRef CriticalName,
1248 const RegionCodeGenTy &CriticalOpGen,
1249 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001250 // __kmpc_critical(ident_t *, gtid, Lock);
1251 // CriticalOpGen();
1252 // __kmpc_end_critical(ident_t *, gtid, Lock);
1253 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001254 {
1255 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001256 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1257 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001258 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001259 // Build a call to __kmpc_end_critical
Alexey Bataeva744ff52015-05-05 09:24:37 +00001260 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001261 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1262 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001263 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001265}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001266
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001267static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001268 OpenMPDirectiveKind Kind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001269 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001270 llvm::Value *CallBool = CGF.EmitScalarConversion(
1271 IfCond,
1272 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1273 CGF.getContext().BoolTy);
1274
1275 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1276 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1277 // Generate the branch (If-stmt)
1278 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1279 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001280 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001281 // Emit the rest of bblocks/branches
1282 CGF.EmitBranch(ContBlock);
1283 CGF.EmitBlock(ContBlock, true);
1284}
1285
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001286void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001287 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001288 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001289 // if(__kmpc_master(ident_t *, gtid)) {
1290 // MasterOpGen();
1291 // __kmpc_end_master(ident_t *, gtid);
1292 // }
1293 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001294 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001295 auto *IsMaster =
1296 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001297 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1298 MasterCallEndCleanup;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001299 emitIfStmt(CGF, IsMaster, OMPD_master, [&](CodeGenFunction &CGF) -> void {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001300 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001301 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001302 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1303 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001304 MasterOpGen(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001305 });
1306}
1307
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001308void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1309 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001310 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1311 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001312 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001313 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001314 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001315}
1316
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001317void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1318 const RegionCodeGenTy &TaskgroupOpGen,
1319 SourceLocation Loc) {
1320 // __kmpc_taskgroup(ident_t *, gtid);
1321 // TaskgroupOpGen();
1322 // __kmpc_end_taskgroup(ident_t *, gtid);
1323 // Prepare arguments and build a call to __kmpc_taskgroup
1324 {
1325 CodeGenFunction::RunCleanupsScope Scope(CGF);
1326 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1327 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1328 // Build a call to __kmpc_end_taskgroup
1329 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1330 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1331 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001332 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001333 }
1334}
1335
Alexey Bataeva63048e2015-03-23 06:18:07 +00001336static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001337 CodeGenModule &CGM, llvm::Type *ArgsType,
1338 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1339 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001340 auto &C = CGM.getContext();
1341 // void copy_func(void *LHSArg, void *RHSArg);
1342 FunctionArgList Args;
1343 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1344 C.VoidPtrTy);
1345 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1346 C.VoidPtrTy);
1347 Args.push_back(&LHSArg);
1348 Args.push_back(&RHSArg);
1349 FunctionType::ExtInfo EI;
1350 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1351 C.VoidTy, Args, EI, /*isVariadic=*/false);
1352 auto *Fn = llvm::Function::Create(
1353 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1354 ".omp.copyprivate.copy_func", &CGM.getModule());
1355 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1356 CodeGenFunction CGF(CGM);
1357 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001358 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001359 // Src = (void*[n])(RHSArg);
1360 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1361 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1362 CGF.PointerAlignInBytes),
1363 ArgsType);
1364 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1365 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1366 CGF.PointerAlignInBytes),
1367 ArgsType);
1368 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1369 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1370 // ...
1371 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001372 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataev420d45b2015-04-14 05:11:24 +00001373 auto *DestAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1374 CGF.Builder.CreateAlignedLoad(
1375 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1376 CGM.PointerAlignInBytes),
1377 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1378 auto *SrcAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1379 CGF.Builder.CreateAlignedLoad(
1380 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1381 CGM.PointerAlignInBytes),
1382 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001383 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1384 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001385 CGF.EmitOMPCopy(CGF, Type, DestAddr, SrcAddr,
Alexey Bataev420d45b2015-04-14 05:11:24 +00001386 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()),
1387 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1388 AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001389 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001390 CGF.FinishFunction();
1391 return Fn;
1392}
1393
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001394void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001395 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001396 SourceLocation Loc,
1397 ArrayRef<const Expr *> CopyprivateVars,
1398 ArrayRef<const Expr *> SrcExprs,
1399 ArrayRef<const Expr *> DstExprs,
1400 ArrayRef<const Expr *> AssignmentOps) {
1401 assert(CopyprivateVars.size() == SrcExprs.size() &&
1402 CopyprivateVars.size() == DstExprs.size() &&
1403 CopyprivateVars.size() == AssignmentOps.size());
1404 auto &C = CGM.getContext();
1405 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001406 // if(__kmpc_single(ident_t *, gtid)) {
1407 // SingleOpGen();
1408 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001409 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001410 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001411 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1412 // <copy_func>, did_it);
1413
1414 llvm::AllocaInst *DidIt = nullptr;
1415 if (!CopyprivateVars.empty()) {
1416 // int32 did_it = 0;
1417 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1418 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
Alexey Bataev66beaa92015-04-30 03:47:32 +00001419 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(0), DidIt,
1420 DidIt->getAlignment());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001421 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001422 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001423 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001424 auto *IsSingle =
1425 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001426 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1427 SingleCallEndCleanup;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001428 emitIfStmt(CGF, IsSingle, OMPD_single, [&](CodeGenFunction &CGF) -> void {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001429 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001430 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001431 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1432 llvm::makeArrayRef(Args));
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001433 SingleOpGen(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001434 if (DidIt) {
1435 // did_it = 1;
1436 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1437 DidIt->getAlignment());
1438 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001439 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001440 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1441 // <copy_func>, did_it);
1442 if (DidIt) {
1443 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1444 auto CopyprivateArrayTy =
1445 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1446 /*IndexTypeQuals=*/0);
1447 // Create a list of all private variables for copyprivate.
1448 auto *CopyprivateList =
1449 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1450 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001451 auto *Elem = CGF.Builder.CreateStructGEP(
1452 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001453 CGF.Builder.CreateAlignedStore(
1454 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1455 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1456 Elem, CGM.PointerAlignInBytes);
1457 }
1458 // Build function that copies private values from single region to all other
1459 // threads in the corresponding parallel region.
1460 auto *CpyFn = emitCopyprivateCopyFunction(
1461 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001462 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001463 auto *BufSize = llvm::ConstantInt::get(
1464 CGM.SizeTy, C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001465 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1466 CGF.VoidPtrTy);
1467 auto *DidItVal =
1468 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1469 llvm::Value *Args[] = {
1470 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1471 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001472 BufSize, // size_t <buf_size>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001473 CL, // void *<copyprivate list>
1474 CpyFn, // void (*) (void *, void *) <copy_func>
1475 DidItVal // i32 did_it
1476 };
1477 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1478 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001479}
1480
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001481void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1482 const RegionCodeGenTy &OrderedOpGen,
1483 SourceLocation Loc) {
1484 // __kmpc_ordered(ident_t *, gtid);
1485 // OrderedOpGen();
1486 // __kmpc_end_ordered(ident_t *, gtid);
1487 // Prepare arguments and build a call to __kmpc_ordered
1488 {
1489 CodeGenFunction::RunCleanupsScope Scope(CGF);
1490 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1491 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1492 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001493 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001494 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1495 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001496 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001497 }
1498}
1499
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001500void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001501 OpenMPDirectiveKind Kind,
1502 bool CheckForCancel) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001503 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001504 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001505 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1506 if (Kind == OMPD_for) {
1507 Flags =
1508 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1509 } else if (Kind == OMPD_sections) {
1510 Flags = static_cast<OpenMPLocationFlags>(Flags |
1511 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1512 } else if (Kind == OMPD_single) {
1513 Flags =
1514 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1515 } else if (Kind == OMPD_barrier) {
1516 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1517 } else {
1518 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1519 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001520 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
1521 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001522 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1523 getThreadID(CGF, Loc)};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001524 if (auto *OMPRegionInfo =
1525 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1526 auto CancelDestination =
1527 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
1528 if (CancelDestination.isValid()) {
1529 auto *Result = CGF.EmitRuntimeCall(
1530 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
1531 if (CheckForCancel) {
1532 // if (__kmpc_cancel_barrier()) {
1533 // exit from construct;
1534 // }
1535 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
1536 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
1537 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
1538 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
1539 CGF.EmitBlock(ExitBB);
1540 // exit from construct;
1541 CGF.EmitBranchThroughCleanup(CancelDestination);
1542 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
1543 }
1544 return;
1545 }
1546 }
1547 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001548}
1549
Alexander Musmanc6388682014-12-15 07:07:06 +00001550/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1551/// the enum sched_type in kmp.h).
1552enum OpenMPSchedType {
1553 /// \brief Lower bound for default (unordered) versions.
1554 OMP_sch_lower = 32,
1555 OMP_sch_static_chunked = 33,
1556 OMP_sch_static = 34,
1557 OMP_sch_dynamic_chunked = 35,
1558 OMP_sch_guided_chunked = 36,
1559 OMP_sch_runtime = 37,
1560 OMP_sch_auto = 38,
1561 /// \brief Lower bound for 'ordered' versions.
1562 OMP_ord_lower = 64,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001563 OMP_ord_static_chunked = 65,
1564 OMP_ord_static = 66,
1565 OMP_ord_dynamic_chunked = 67,
1566 OMP_ord_guided_chunked = 68,
1567 OMP_ord_runtime = 69,
1568 OMP_ord_auto = 70,
1569 OMP_sch_default = OMP_sch_static,
Alexander Musmanc6388682014-12-15 07:07:06 +00001570};
1571
1572/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1573static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001574 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001575 switch (ScheduleKind) {
1576 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001577 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
1578 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00001579 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001580 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001581 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001582 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001583 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001584 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
1585 case OMPC_SCHEDULE_auto:
1586 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00001587 case OMPC_SCHEDULE_unknown:
1588 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001589 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00001590 }
1591 llvm_unreachable("Unexpected runtime schedule");
1592}
1593
1594bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1595 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001596 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00001597 return Schedule == OMP_sch_static;
1598}
1599
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001600bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001601 auto Schedule =
1602 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001603 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1604 return Schedule != OMP_sch_static;
1605}
1606
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001607void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1608 OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001609 unsigned IVSize, bool IVSigned, bool Ordered,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001610 llvm::Value *IL, llvm::Value *LB,
1611 llvm::Value *UB, llvm::Value *ST,
1612 llvm::Value *Chunk) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001613 OpenMPSchedType Schedule =
1614 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
1615 if (Ordered ||
1616 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
1617 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked)) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001618 // Call __kmpc_dispatch_init(
1619 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1620 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1621 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001622
Alexander Musman92bdaab2015-03-12 13:37:50 +00001623 // If the Chunk was not specified in the clause - use default value 1.
1624 if (Chunk == nullptr)
1625 Chunk = CGF.Builder.getIntN(IVSize, 1);
1626 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1627 getThreadID(CGF, Loc),
1628 CGF.Builder.getInt32(Schedule), // Schedule type
1629 CGF.Builder.getIntN(IVSize, 0), // Lower
1630 UB, // Upper
1631 CGF.Builder.getIntN(IVSize, 1), // Stride
1632 Chunk // Chunk
1633 };
1634 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1635 } else {
1636 // Call __kmpc_for_static_init(
1637 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1638 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1639 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1640 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1641 if (Chunk == nullptr) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001642 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
Alexander Musman92bdaab2015-03-12 13:37:50 +00001643 "expected static non-chunked schedule");
1644 // If the Chunk was not specified in the clause - use default value 1.
1645 Chunk = CGF.Builder.getIntN(IVSize, 1);
1646 } else
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001647 assert((Schedule == OMP_sch_static_chunked ||
1648 Schedule == OMP_ord_static_chunked) &&
Alexander Musman92bdaab2015-03-12 13:37:50 +00001649 "expected static chunked schedule");
1650 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1651 getThreadID(CGF, Loc),
1652 CGF.Builder.getInt32(Schedule), // Schedule type
1653 IL, // &isLastIter
1654 LB, // &LB
1655 UB, // &UB
1656 ST, // &Stride
1657 CGF.Builder.getIntN(IVSize, 1), // Incr
1658 Chunk // Chunk
1659 };
Alexander Musman21212e42015-03-13 10:38:23 +00001660 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001661 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001662}
1663
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001664void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1665 SourceLocation Loc) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001666 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001667 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1668 getThreadID(CGF, Loc)};
1669 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1670 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001671}
1672
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001673void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
1674 SourceLocation Loc,
1675 unsigned IVSize,
1676 bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001677 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1678 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1679 getThreadID(CGF, Loc)};
1680 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1681}
1682
Alexander Musman92bdaab2015-03-12 13:37:50 +00001683llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1684 SourceLocation Loc, unsigned IVSize,
1685 bool IVSigned, llvm::Value *IL,
1686 llvm::Value *LB, llvm::Value *UB,
1687 llvm::Value *ST) {
1688 // Call __kmpc_dispatch_next(
1689 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1690 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1691 // kmp_int[32|64] *p_stride);
1692 llvm::Value *Args[] = {
1693 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1694 IL, // &isLastIter
1695 LB, // &Lower
1696 UB, // &Upper
1697 ST // &Stride
1698 };
1699 llvm::Value *Call =
1700 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1701 return CGF.EmitScalarConversion(
1702 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1703 CGF.getContext().BoolTy);
1704}
1705
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001706void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1707 llvm::Value *NumThreads,
1708 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001709 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1710 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001711 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001712 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001713 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1714 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001715}
1716
Alexey Bataev7f210c62015-06-18 13:40:03 +00001717void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
1718 OpenMPProcBindClauseKind ProcBind,
1719 SourceLocation Loc) {
1720 // Constants for proc bind value accepted by the runtime.
1721 enum ProcBindTy {
1722 ProcBindFalse = 0,
1723 ProcBindTrue,
1724 ProcBindMaster,
1725 ProcBindClose,
1726 ProcBindSpread,
1727 ProcBindIntel,
1728 ProcBindDefault
1729 } RuntimeProcBind;
1730 switch (ProcBind) {
1731 case OMPC_PROC_BIND_master:
1732 RuntimeProcBind = ProcBindMaster;
1733 break;
1734 case OMPC_PROC_BIND_close:
1735 RuntimeProcBind = ProcBindClose;
1736 break;
1737 case OMPC_PROC_BIND_spread:
1738 RuntimeProcBind = ProcBindSpread;
1739 break;
1740 case OMPC_PROC_BIND_unknown:
1741 llvm_unreachable("Unsupported proc_bind value.");
1742 }
1743 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
1744 llvm::Value *Args[] = {
1745 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1746 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
1747 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
1748}
1749
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001750void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1751 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001752 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001753 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1754 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001755}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001756
Alexey Bataev62b63b12015-03-10 07:28:44 +00001757namespace {
1758/// \brief Indexes of fields for type kmp_task_t.
1759enum KmpTaskTFields {
1760 /// \brief List of shared variables.
1761 KmpTaskTShareds,
1762 /// \brief Task routine.
1763 KmpTaskTRoutine,
1764 /// \brief Partition id for the untied tasks.
1765 KmpTaskTPartId,
1766 /// \brief Function with call of destructors for private variables.
1767 KmpTaskTDestructors,
1768};
1769} // namespace
1770
1771void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1772 if (!KmpRoutineEntryPtrTy) {
1773 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1774 auto &C = CGM.getContext();
1775 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1776 FunctionProtoType::ExtProtoInfo EPI;
1777 KmpRoutineEntryPtrQTy = C.getPointerType(
1778 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1779 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1780 }
1781}
1782
1783static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1784 QualType FieldTy) {
1785 auto *Field = FieldDecl::Create(
1786 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1787 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1788 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1789 Field->setAccess(AS_public);
1790 DC->addDecl(Field);
1791}
1792
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001793namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00001794struct PrivateHelpersTy {
1795 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
1796 const VarDecl *PrivateElemInit)
1797 : Original(Original), PrivateCopy(PrivateCopy),
1798 PrivateElemInit(PrivateElemInit) {}
1799 const VarDecl *Original;
1800 const VarDecl *PrivateCopy;
1801 const VarDecl *PrivateElemInit;
1802};
1803typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001804} // namespace
1805
Alexey Bataev9e034042015-05-05 04:05:12 +00001806static RecordDecl *
1807createPrivatesRecordDecl(CodeGenModule &CGM,
1808 const ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001809 if (!Privates.empty()) {
1810 auto &C = CGM.getContext();
1811 // Build struct .kmp_privates_t. {
1812 // /* private vars */
1813 // };
1814 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
1815 RD->startDefinition();
1816 for (auto &&Pair : Privates) {
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001817 auto Type = Pair.second.Original->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001818 Type = Type.getNonReferenceType();
1819 addFieldToRecordDecl(C, RD, Type);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001820 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001821 RD->completeDefinition();
1822 return RD;
1823 }
1824 return nullptr;
1825}
1826
Alexey Bataev9e034042015-05-05 04:05:12 +00001827static RecordDecl *
1828createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001829 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001830 auto &C = CGM.getContext();
1831 // Build struct kmp_task_t {
1832 // void * shareds;
1833 // kmp_routine_entry_t routine;
1834 // kmp_int32 part_id;
1835 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001836 // };
1837 auto *RD = C.buildImplicitRecord("kmp_task_t");
1838 RD->startDefinition();
1839 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1840 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1841 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1842 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001843 RD->completeDefinition();
1844 return RD;
1845}
1846
1847static RecordDecl *
1848createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
1849 const ArrayRef<PrivateDataTy> Privates) {
1850 auto &C = CGM.getContext();
1851 // Build struct kmp_task_t_with_privates {
1852 // kmp_task_t task_data;
1853 // .kmp_privates_t. privates;
1854 // };
1855 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
1856 RD->startDefinition();
1857 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001858 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
1859 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
1860 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001861 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001862 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001863}
1864
1865/// \brief Emit a proxy function which accepts kmp_task_t as the second
1866/// argument.
1867/// \code
1868/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001869/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
1870/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001871/// return 0;
1872/// }
1873/// \endcode
1874static llvm::Value *
1875emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001876 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
1877 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001878 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1879 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001880 auto &C = CGM.getContext();
1881 FunctionArgList Args;
1882 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1883 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001884 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001885 Args.push_back(&GtidArg);
1886 Args.push_back(&TaskTypeArg);
1887 FunctionType::ExtInfo Info;
1888 auto &TaskEntryFnInfo =
1889 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1890 /*isVariadic=*/false);
1891 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1892 auto *TaskEntry =
1893 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1894 ".omp_task_entry.", &CGM.getModule());
1895 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1896 CodeGenFunction CGF(CGM);
1897 CGF.disableDebugInfo();
1898 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1899
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001900 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
1901 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001902 auto *GtidParam = CGF.EmitLoadOfScalar(
1903 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1904 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001905 auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
1906 CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001907 LValue TDBase =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001908 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1909 auto *KmpTaskTWithPrivatesQTyRD =
1910 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001911 LValue Base =
1912 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001913 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
1914 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
1915 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
1916 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
1917
1918 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
1919 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001920 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001921 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001922 CGF.ConvertTypeForMem(SharedsPtrTy));
1923
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001924 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
1925 llvm::Value *PrivatesParam;
1926 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
1927 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
1928 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1929 PrivatesLVal.getAddress(), CGF.VoidPtrTy);
1930 } else {
1931 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
1932 }
1933
1934 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
1935 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00001936 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1937 CGF.EmitStoreThroughLValue(
1938 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1939 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1940 CGF.FinishFunction();
1941 return TaskEntry;
1942}
1943
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001944static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
1945 SourceLocation Loc,
1946 QualType KmpInt32Ty,
1947 QualType KmpTaskTWithPrivatesPtrQTy,
1948 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001949 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001950 FunctionArgList Args;
1951 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1952 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001953 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001954 Args.push_back(&GtidArg);
1955 Args.push_back(&TaskTypeArg);
1956 FunctionType::ExtInfo Info;
1957 auto &DestructorFnInfo =
1958 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1959 /*isVariadic=*/false);
1960 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
1961 auto *DestructorFn =
1962 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
1963 ".omp_task_destructor.", &CGM.getModule());
1964 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, DestructorFnInfo, DestructorFn);
1965 CodeGenFunction CGF(CGM);
1966 CGF.disableDebugInfo();
1967 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
1968 Args);
1969
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001970 auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
1971 CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
1972 LValue Base =
1973 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1974 auto *KmpTaskTWithPrivatesQTyRD =
1975 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
1976 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001977 Base = CGF.EmitLValueForField(Base, *FI);
1978 for (auto *Field :
1979 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
1980 if (auto DtorKind = Field->getType().isDestructedType()) {
1981 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
1982 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
1983 }
1984 }
1985 CGF.FinishFunction();
1986 return DestructorFn;
1987}
1988
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001989/// \brief Emit a privates mapping function for correct handling of private and
1990/// firstprivate variables.
1991/// \code
1992/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
1993/// **noalias priv1,..., <tyn> **noalias privn) {
1994/// *priv1 = &.privates.priv1;
1995/// ...;
1996/// *privn = &.privates.privn;
1997/// }
1998/// \endcode
1999static llvm::Value *
2000emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
2001 const ArrayRef<const Expr *> PrivateVars,
2002 const ArrayRef<const Expr *> FirstprivateVars,
2003 QualType PrivatesQTy,
2004 const ArrayRef<PrivateDataTy> Privates) {
2005 auto &C = CGM.getContext();
2006 FunctionArgList Args;
2007 ImplicitParamDecl TaskPrivatesArg(
2008 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2009 C.getPointerType(PrivatesQTy).withConst().withRestrict());
2010 Args.push_back(&TaskPrivatesArg);
2011 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
2012 unsigned Counter = 1;
2013 for (auto *E: PrivateVars) {
2014 Args.push_back(ImplicitParamDecl::Create(
2015 C, /*DC=*/nullptr, Loc,
2016 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2017 .withConst()
2018 .withRestrict()));
2019 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2020 PrivateVarsPos[VD] = Counter;
2021 ++Counter;
2022 }
2023 for (auto *E : FirstprivateVars) {
2024 Args.push_back(ImplicitParamDecl::Create(
2025 C, /*DC=*/nullptr, Loc,
2026 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2027 .withConst()
2028 .withRestrict()));
2029 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2030 PrivateVarsPos[VD] = Counter;
2031 ++Counter;
2032 }
2033 FunctionType::ExtInfo Info;
2034 auto &TaskPrivatesMapFnInfo =
2035 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2036 /*isVariadic=*/false);
2037 auto *TaskPrivatesMapTy =
2038 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2039 auto *TaskPrivatesMap = llvm::Function::Create(
2040 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2041 ".omp_task_privates_map.", &CGM.getModule());
2042 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskPrivatesMapFnInfo,
2043 TaskPrivatesMap);
2044 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
2045 CodeGenFunction CGF(CGM);
2046 CGF.disableDebugInfo();
2047 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2048 TaskPrivatesMapFnInfo, Args);
2049
2050 // *privi = &.privates.privi;
2051 auto *TaskPrivatesArgAddr = CGF.Builder.CreateAlignedLoad(
2052 CGF.GetAddrOfLocalVar(&TaskPrivatesArg), CGM.PointerAlignInBytes);
2053 LValue Base =
2054 CGF.MakeNaturalAlignAddrLValue(TaskPrivatesArgAddr, PrivatesQTy);
2055 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2056 Counter = 0;
2057 for (auto *Field : PrivatesQTyRD->fields()) {
2058 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2059 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
2060 auto RefLVal = CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(VD),
2061 VD->getType());
2062 auto RefLoadRVal = CGF.EmitLoadOfLValue(RefLVal, Loc);
2063 CGF.EmitStoreOfScalar(
2064 FieldLVal.getAddress(),
2065 CGF.MakeNaturalAlignAddrLValue(RefLoadRVal.getScalarVal(),
2066 RefLVal.getType()->getPointeeType()));
2067 ++Counter;
2068 }
2069 CGF.FinishFunction();
2070 return TaskPrivatesMap;
2071}
2072
Alexey Bataev9e034042015-05-05 04:05:12 +00002073static int array_pod_sort_comparator(const PrivateDataTy *P1,
2074 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002075 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2076}
2077
2078void CGOpenMPRuntime::emitTaskCall(
2079 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
2080 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
2081 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002082 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
2083 ArrayRef<const Expr *> PrivateCopies,
2084 ArrayRef<const Expr *> FirstprivateVars,
2085 ArrayRef<const Expr *> FirstprivateCopies,
2086 ArrayRef<const Expr *> FirstprivateInits,
2087 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002088 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00002089 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002090 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00002091 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002092 for (auto *E : PrivateVars) {
2093 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2094 Privates.push_back(std::make_pair(
2095 C.getTypeAlignInChars(VD->getType()),
Alexey Bataev9e034042015-05-05 04:05:12 +00002096 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2097 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002098 ++I;
2099 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002100 I = FirstprivateCopies.begin();
2101 auto IElemInitRef = FirstprivateInits.begin();
2102 for (auto *E : FirstprivateVars) {
2103 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2104 Privates.push_back(std::make_pair(
2105 C.getTypeAlignInChars(VD->getType()),
2106 PrivateHelpersTy(
2107 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2108 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
2109 ++I, ++IElemInitRef;
2110 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002111 llvm::array_pod_sort(Privates.begin(), Privates.end(),
2112 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002113 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2114 // Build type kmp_routine_entry_t (if not built yet).
2115 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002116 // Build type kmp_task_t (if not built yet).
2117 if (KmpTaskTQTy.isNull()) {
2118 KmpTaskTQTy = C.getRecordType(
2119 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2120 }
2121 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002122 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002123 auto *KmpTaskTWithPrivatesQTyRD =
2124 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2125 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2126 QualType KmpTaskTWithPrivatesPtrQTy =
2127 C.getPointerType(KmpTaskTWithPrivatesQTy);
2128 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2129 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
2130 auto KmpTaskTWithPrivatesTySize =
2131 CGM.getSize(C.getTypeSizeInChars(KmpTaskTWithPrivatesQTy));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002132 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2133
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002134 // Emit initial values for private copies (if any).
2135 llvm::Value *TaskPrivatesMap = nullptr;
2136 auto *TaskPrivatesMapTy =
2137 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2138 3)
2139 ->getType();
2140 if (!Privates.empty()) {
2141 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2142 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2143 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2144 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2145 TaskPrivatesMap, TaskPrivatesMapTy);
2146 } else {
2147 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2148 cast<llvm::PointerType>(TaskPrivatesMapTy));
2149 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002150 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2151 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002152 auto *TaskEntry = emitProxyTaskFunction(
2153 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002154 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002155
2156 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2157 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2158 // kmp_routine_entry_t *task_entry);
2159 // Task flags. Format is taken from
2160 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2161 // description of kmp_tasking_flags struct.
2162 const unsigned TiedFlag = 0x1;
2163 const unsigned FinalFlag = 0x2;
2164 unsigned Flags = Tied ? TiedFlag : 0;
2165 auto *TaskFlags =
2166 Final.getPointer()
2167 ? CGF.Builder.CreateSelect(Final.getPointer(),
2168 CGF.Builder.getInt32(FinalFlag),
2169 CGF.Builder.getInt32(/*C=*/0))
2170 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2171 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
2172 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002173 llvm::Value *AllocArgs[] = {
2174 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), TaskFlags,
2175 KmpTaskTWithPrivatesTySize, CGM.getSize(SharedsSize),
2176 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskEntry,
2177 KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002178 auto *NewTask = CGF.EmitRuntimeCall(
2179 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002180 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2181 NewTask, KmpTaskTWithPrivatesPtrTy);
2182 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2183 KmpTaskTWithPrivatesQTy);
2184 LValue TDBase =
2185 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002186 // Fill the data in the resulting kmp_task_t record.
2187 // Copy shareds if there are any.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002188 llvm::Value *KmpTaskSharedsPtr = nullptr;
2189 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
2190 KmpTaskSharedsPtr = CGF.EmitLoadOfScalar(
2191 CGF.EmitLValueForField(
2192 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)),
2193 Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002194 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002195 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002196 // Emit initial values for private copies (if any).
2197 bool NeedsCleanup = false;
2198 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002199 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2200 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002201 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002202 LValue SharedsBase;
2203 if (!FirstprivateVars.empty()) {
2204 SharedsBase = CGF.MakeNaturalAlignAddrLValue(
2205 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2206 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2207 SharedsTy);
2208 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002209 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2210 cast<CapturedStmt>(*D.getAssociatedStmt()));
2211 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002212 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002213 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002214 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002215 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002216 if (auto *Elem = Pair.second.PrivateElemInit) {
2217 auto *OriginalVD = Pair.second.Original;
2218 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2219 auto SharedRefLValue =
2220 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002221 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002222 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002223 // Initialize firstprivate array.
2224 if (!isa<CXXConstructExpr>(Init) ||
2225 CGF.isTrivialInitializer(Init)) {
2226 // Perform simple memcpy.
2227 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002228 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002229 } else {
2230 // Initialize firstprivate array using element-by-element
2231 // intialization.
2232 CGF.EmitOMPAggregateAssign(
2233 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002234 Type, [&CGF, Elem, Init, &CapturesInfo](
2235 llvm::Value *DestElement, llvm::Value *SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002236 // Clean up any temporaries needed by the initialization.
2237 CodeGenFunction::OMPPrivateScope InitScope(CGF);
2238 InitScope.addPrivate(Elem, [SrcElement]() -> llvm::Value *{
2239 return SrcElement;
2240 });
2241 (void)InitScope.Privatize();
2242 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00002243 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
2244 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002245 CGF.EmitAnyExprToMem(Init, DestElement,
2246 Init->getType().getQualifiers(),
2247 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002248 });
2249 }
2250 } else {
2251 CodeGenFunction::OMPPrivateScope InitScope(CGF);
2252 InitScope.addPrivate(Elem, [SharedRefLValue]() -> llvm::Value *{
2253 return SharedRefLValue.getAddress();
2254 });
2255 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00002256 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002257 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2258 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002259 }
2260 } else {
2261 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2262 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002263 }
2264 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002265 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002266 }
2267 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002268 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002269 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002270 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2271 KmpTaskTWithPrivatesPtrQTy,
2272 KmpTaskTWithPrivatesQTy)
2273 : llvm::ConstantPointerNull::get(
2274 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2275 LValue Destructor = CGF.EmitLValueForField(
2276 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2277 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2278 DestructorFn, KmpRoutineEntryPtrTy),
2279 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002280
2281 // Process list of dependences.
2282 llvm::Value *DependInfo = nullptr;
2283 unsigned DependencesNumber = Dependences.size();
2284 if (!Dependences.empty()) {
2285 // Dependence kind for RTL.
2286 enum RTLDependenceKindTy { DepIn = 1, DepOut = 2, DepInOut = 3 };
2287 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
2288 RecordDecl *KmpDependInfoRD;
2289 QualType FlagsTy = C.getIntTypeForBitwidth(
2290 C.toBits(C.getTypeSizeInChars(C.BoolTy)), /*Signed=*/false);
2291 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
2292 if (KmpDependInfoTy.isNull()) {
2293 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
2294 KmpDependInfoRD->startDefinition();
2295 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
2296 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
2297 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
2298 KmpDependInfoRD->completeDefinition();
2299 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
2300 } else {
2301 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
2302 }
2303 // Define type kmp_depend_info[<Dependences.size()>];
2304 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
2305 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, Dependences.size()),
2306 ArrayType::Normal, /*IndexTypeQuals=*/0);
2307 // kmp_depend_info[<Dependences.size()>] deps;
2308 DependInfo = CGF.CreateMemTemp(KmpDependInfoArrayTy);
2309 for (unsigned i = 0; i < DependencesNumber; ++i) {
2310 auto Addr = CGF.EmitLValue(Dependences[i].second);
2311 auto *Size = llvm::ConstantInt::get(
2312 CGF.SizeTy,
2313 C.getTypeSizeInChars(Dependences[i].second->getType()).getQuantity());
2314 auto Base = CGF.MakeNaturalAlignAddrLValue(
2315 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, DependInfo, i),
2316 KmpDependInfoTy);
2317 // deps[i].base_addr = &<Dependences[i].second>;
2318 auto BaseAddrLVal = CGF.EmitLValueForField(
2319 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
2320 CGF.EmitStoreOfScalar(
2321 CGF.Builder.CreatePtrToInt(Addr.getAddress(), CGF.IntPtrTy),
2322 BaseAddrLVal);
2323 // deps[i].len = sizeof(<Dependences[i].second>);
2324 auto LenLVal = CGF.EmitLValueForField(
2325 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
2326 CGF.EmitStoreOfScalar(Size, LenLVal);
2327 // deps[i].flags = <Dependences[i].first>;
2328 RTLDependenceKindTy DepKind;
2329 switch (Dependences[i].first) {
2330 case OMPC_DEPEND_in:
2331 DepKind = DepIn;
2332 break;
2333 case OMPC_DEPEND_out:
2334 DepKind = DepOut;
2335 break;
2336 case OMPC_DEPEND_inout:
2337 DepKind = DepInOut;
2338 break;
2339 case OMPC_DEPEND_unknown:
2340 llvm_unreachable("Unknown task dependence type");
2341 }
2342 auto FlagsLVal = CGF.EmitLValueForField(
2343 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
2344 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
2345 FlagsLVal);
2346 }
2347 DependInfo = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2348 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, DependInfo, 0),
2349 CGF.VoidPtrTy);
2350 }
2351
Alexey Bataev62b63b12015-03-10 07:28:44 +00002352 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
2353 // libcall.
2354 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
2355 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002356 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2357 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2358 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
2359 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00002360 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002361 auto *UpLoc = emitUpdateLocation(CGF, Loc);
2362 llvm::Value *TaskArgs[] = {UpLoc, ThreadID, NewTask};
2363 llvm::Value *DepTaskArgs[] = {
2364 UpLoc,
2365 ThreadID,
2366 NewTask,
2367 DependInfo ? CGF.Builder.getInt32(DependencesNumber) : nullptr,
2368 DependInfo,
2369 DependInfo ? CGF.Builder.getInt32(0) : nullptr,
2370 DependInfo ? llvm::ConstantPointerNull::get(CGF.VoidPtrTy) : nullptr};
2371 auto &&ThenCodeGen = [this, DependInfo, &TaskArgs,
2372 &DepTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002373 // TODO: add check for untied tasks.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002374 CGF.EmitRuntimeCall(
2375 createRuntimeFunction(DependInfo ? OMPRTL__kmpc_omp_task_with_deps
2376 : OMPRTL__kmpc_omp_task),
2377 DependInfo ? makeArrayRef(DepTaskArgs) : makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002378 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002379 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
2380 IfCallEndCleanup;
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002381 llvm::Value *DepWaitTaskArgs[] = {
2382 UpLoc,
2383 ThreadID,
2384 DependInfo ? CGF.Builder.getInt32(DependencesNumber) : nullptr,
2385 DependInfo,
2386 DependInfo ? CGF.Builder.getInt32(0) : nullptr,
2387 DependInfo ? llvm::ConstantPointerNull::get(CGF.VoidPtrTy) : nullptr};
2388 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
2389 DependInfo, &DepWaitTaskArgs](CodeGenFunction &CGF) {
2390 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
2391 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2392 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
2393 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
2394 // is specified.
2395 if (DependInfo)
2396 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
2397 DepWaitTaskArgs);
2398 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
2399 // kmp_task_t *new_task);
2400 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
2401 TaskArgs);
2402 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
2403 // kmp_task_t *new_task);
2404 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
2405 NormalAndEHCleanup,
2406 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
2407 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002408
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002409 // Call proxy_task_entry(gtid, new_task);
2410 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
2411 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
2412 };
Alexey Bataev1d677132015-04-22 13:57:31 +00002413 if (IfCond) {
2414 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
2415 } else {
2416 CodeGenFunction::RunCleanupsScope Scope(CGF);
2417 ThenCodeGen(CGF);
2418 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002419}
2420
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002421static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
2422 llvm::Type *ArgsType,
2423 ArrayRef<const Expr *> LHSExprs,
2424 ArrayRef<const Expr *> RHSExprs,
2425 ArrayRef<const Expr *> ReductionOps) {
2426 auto &C = CGM.getContext();
2427
2428 // void reduction_func(void *LHSArg, void *RHSArg);
2429 FunctionArgList Args;
2430 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2431 C.VoidPtrTy);
2432 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2433 C.VoidPtrTy);
2434 Args.push_back(&LHSArg);
2435 Args.push_back(&RHSArg);
2436 FunctionType::ExtInfo EI;
2437 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2438 C.VoidTy, Args, EI, /*isVariadic=*/false);
2439 auto *Fn = llvm::Function::Create(
2440 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2441 ".omp.reduction.reduction_func", &CGM.getModule());
2442 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
2443 CodeGenFunction CGF(CGM);
2444 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2445
2446 // Dst = (void*[n])(LHSArg);
2447 // Src = (void*[n])(RHSArg);
2448 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2449 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
2450 CGF.PointerAlignInBytes),
2451 ArgsType);
2452 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2453 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
2454 CGF.PointerAlignInBytes),
2455 ArgsType);
2456
2457 // ...
2458 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
2459 // ...
2460 CodeGenFunction::OMPPrivateScope Scope(CGF);
2461 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
2462 Scope.addPrivate(
2463 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()),
2464 [&]() -> llvm::Value *{
2465 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2466 CGF.Builder.CreateAlignedLoad(
2467 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, RHS, I),
2468 CGM.PointerAlignInBytes),
2469 CGF.ConvertTypeForMem(C.getPointerType(RHSExprs[I]->getType())));
2470 });
2471 Scope.addPrivate(
2472 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()),
2473 [&]() -> llvm::Value *{
2474 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2475 CGF.Builder.CreateAlignedLoad(
2476 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, LHS, I),
2477 CGM.PointerAlignInBytes),
2478 CGF.ConvertTypeForMem(C.getPointerType(LHSExprs[I]->getType())));
2479 });
2480 }
2481 Scope.Privatize();
2482 for (auto *E : ReductionOps) {
2483 CGF.EmitIgnoredExpr(E);
2484 }
2485 Scope.ForceCleanup();
2486 CGF.FinishFunction();
2487 return Fn;
2488}
2489
2490void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
2491 ArrayRef<const Expr *> LHSExprs,
2492 ArrayRef<const Expr *> RHSExprs,
2493 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002494 bool WithNowait, bool SimpleReduction) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002495 // Next code should be emitted for reduction:
2496 //
2497 // static kmp_critical_name lock = { 0 };
2498 //
2499 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
2500 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
2501 // ...
2502 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
2503 // *(Type<n>-1*)rhs[<n>-1]);
2504 // }
2505 //
2506 // ...
2507 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
2508 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2509 // RedList, reduce_func, &<lock>)) {
2510 // case 1:
2511 // ...
2512 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2513 // ...
2514 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2515 // break;
2516 // case 2:
2517 // ...
2518 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2519 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00002520 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002521 // break;
2522 // default:;
2523 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002524 //
2525 // if SimpleReduction is true, only the next code is generated:
2526 // ...
2527 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2528 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002529
2530 auto &C = CGM.getContext();
2531
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002532 if (SimpleReduction) {
2533 CodeGenFunction::RunCleanupsScope Scope(CGF);
2534 for (auto *E : ReductionOps) {
2535 CGF.EmitIgnoredExpr(E);
2536 }
2537 return;
2538 }
2539
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002540 // 1. Build a list of reduction variables.
2541 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2542 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
2543 QualType ReductionArrayTy =
2544 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2545 /*IndexTypeQuals=*/0);
2546 auto *ReductionList =
2547 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2548 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
2549 auto *Elem = CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, ReductionList, I);
2550 CGF.Builder.CreateAlignedStore(
2551 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2552 CGF.EmitLValue(RHSExprs[I]).getAddress(), CGF.VoidPtrTy),
2553 Elem, CGM.PointerAlignInBytes);
2554 }
2555
2556 // 2. Emit reduce_func().
2557 auto *ReductionFn = emitReductionFunction(
2558 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
2559 RHSExprs, ReductionOps);
2560
2561 // 3. Create static kmp_critical_name lock = { 0 };
2562 auto *Lock = getCriticalRegionLock(".reduction");
2563
2564 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2565 // RedList, reduce_func, &<lock>);
2566 auto *IdentTLoc = emitUpdateLocation(
2567 CGF, Loc,
2568 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
2569 auto *ThreadId = getThreadID(CGF, Loc);
2570 auto *ReductionArrayTySize = llvm::ConstantInt::get(
2571 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
2572 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList,
2573 CGF.VoidPtrTy);
2574 llvm::Value *Args[] = {
2575 IdentTLoc, // ident_t *<loc>
2576 ThreadId, // i32 <gtid>
2577 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
2578 ReductionArrayTySize, // size_type sizeof(RedList)
2579 RL, // void *RedList
2580 ReductionFn, // void (*) (void *, void *) <reduce_func>
2581 Lock // kmp_critical_name *&<lock>
2582 };
2583 auto Res = CGF.EmitRuntimeCall(
2584 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
2585 : OMPRTL__kmpc_reduce),
2586 Args);
2587
2588 // 5. Build switch(res)
2589 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2590 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
2591
2592 // 6. Build case 1:
2593 // ...
2594 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2595 // ...
2596 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2597 // break;
2598 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2599 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2600 CGF.EmitBlock(Case1BB);
2601
2602 {
2603 CodeGenFunction::RunCleanupsScope Scope(CGF);
2604 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2605 llvm::Value *EndArgs[] = {
2606 IdentTLoc, // ident_t *<loc>
2607 ThreadId, // i32 <gtid>
2608 Lock // kmp_critical_name *&<lock>
2609 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002610 CGF.EHStack
2611 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2612 NormalAndEHCleanup,
2613 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
2614 : OMPRTL__kmpc_end_reduce),
2615 llvm::makeArrayRef(EndArgs));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002616 for (auto *E : ReductionOps) {
2617 CGF.EmitIgnoredExpr(E);
2618 }
2619 }
2620
2621 CGF.EmitBranch(DefaultBB);
2622
2623 // 7. Build case 2:
2624 // ...
2625 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2626 // ...
2627 // break;
2628 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
2629 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
2630 CGF.EmitBlock(Case2BB);
2631
2632 {
2633 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00002634 if (!WithNowait) {
2635 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
2636 llvm::Value *EndArgs[] = {
2637 IdentTLoc, // ident_t *<loc>
2638 ThreadId, // i32 <gtid>
2639 Lock // kmp_critical_name *&<lock>
2640 };
2641 CGF.EHStack
2642 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2643 NormalAndEHCleanup,
2644 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
2645 llvm::makeArrayRef(EndArgs));
2646 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002647 auto I = LHSExprs.begin();
2648 for (auto *E : ReductionOps) {
2649 const Expr *XExpr = nullptr;
2650 const Expr *EExpr = nullptr;
2651 const Expr *UpExpr = nullptr;
2652 BinaryOperatorKind BO = BO_Comma;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002653 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2654 if (BO->getOpcode() == BO_Assign) {
2655 XExpr = BO->getLHS();
2656 UpExpr = BO->getRHS();
2657 }
2658 }
Alexey Bataev69a47792015-05-07 03:54:03 +00002659 // Try to emit update expression as a simple atomic.
2660 auto *RHSExpr = UpExpr;
2661 if (RHSExpr) {
2662 // Analyze RHS part of the whole expression.
2663 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
2664 RHSExpr->IgnoreParenImpCasts())) {
2665 // If this is a conditional operator, analyze its condition for
2666 // min/max reduction operator.
2667 RHSExpr = ACO->getCond();
2668 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002669 if (auto *BORHS =
Alexey Bataev69a47792015-05-07 03:54:03 +00002670 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002671 EExpr = BORHS->getRHS();
2672 BO = BORHS->getOpcode();
2673 }
2674 }
2675 if (XExpr) {
2676 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2677 LValue X = CGF.EmitLValue(XExpr);
2678 RValue E;
2679 if (EExpr)
2680 E = CGF.EmitAnyExpr(EExpr);
2681 CGF.EmitOMPAtomicSimpleUpdateExpr(
2682 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
2683 [&CGF, UpExpr, VD](RValue XRValue) {
2684 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
2685 PrivateScope.addPrivate(
2686 VD, [&CGF, VD, XRValue]() -> llvm::Value *{
2687 auto *LHSTemp = CGF.CreateMemTemp(VD->getType());
2688 CGF.EmitStoreThroughLValue(
2689 XRValue,
2690 CGF.MakeNaturalAlignAddrLValue(LHSTemp, VD->getType()));
2691 return LHSTemp;
2692 });
2693 (void)PrivateScope.Privatize();
2694 return CGF.EmitAnyExpr(UpExpr);
2695 });
2696 } else {
2697 // Emit as a critical region.
2698 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
2699 CGF.EmitIgnoredExpr(E);
2700 }, Loc);
2701 }
2702 ++I;
2703 }
2704 }
2705
2706 CGF.EmitBranch(DefaultBB);
2707 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2708}
2709
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002710void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
2711 SourceLocation Loc) {
2712 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2713 // global_tid);
2714 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2715 // Ignore return result until untied tasks are supported.
2716 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
2717}
2718
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002719void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002720 OpenMPDirectiveKind InnerKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002721 const RegionCodeGenTy &CodeGen) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002722 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002723 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002724}
2725
Alexey Bataev0f34da12015-07-02 04:17:07 +00002726void CGOpenMPRuntime::emitCancellationPointCall(
2727 CodeGenFunction &CGF, SourceLocation Loc,
2728 OpenMPDirectiveKind CancelRegion) {
2729 // Build call kmp_int32 OMPRTL__kmpc_cancellationpoint(ident_t *loc, kmp_int32
2730 // global_tid, kmp_int32 cncl_kind);
2731 enum {
2732 CancelNoreq = 0,
2733 CancelParallel = 1,
2734 CancelLoop = 2,
2735 CancelSections = 3,
2736 CancelTaskgroup = 4
2737 } CancelKind = CancelNoreq;
2738 if (CancelRegion == OMPD_parallel)
2739 CancelKind = CancelParallel;
2740 else if (CancelRegion == OMPD_for)
2741 CancelKind = CancelLoop;
2742 else if (CancelRegion == OMPD_sections)
2743 CancelKind = CancelSections;
2744 else {
2745 assert(CancelRegion == OMPD_taskgroup);
2746 CancelKind = CancelTaskgroup;
2747 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002748 if (auto *OMPRegionInfo =
2749 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2750 auto CancelDest =
2751 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2752 if (CancelDest.isValid()) {
2753 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc),
2754 getThreadID(CGF, Loc),
2755 CGF.Builder.getInt32(CancelKind)};
2756 // Ignore return result until untied tasks are supported.
2757 auto *Result = CGF.EmitRuntimeCall(
2758 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
2759 // if (__kmpc_cancellationpoint()) {
2760 // __kmpc_cancel_barrier();
2761 // exit from construct;
2762 // }
2763 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2764 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2765 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2766 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2767 CGF.EmitBlock(ExitBB);
2768 // __kmpc_cancel_barrier();
2769 emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
2770 // exit from construct;
2771 CGF.EmitBranchThroughCleanup(CancelDest);
2772 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2773 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002774 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002775}
2776