blob: a0b3ee5ab01417c9693de881939c0c33dc44031f [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(
John McCall7f416cc2015-09-08 08:05:57 +0000236 CGF.Builder.CreateLoad(
237 CGF.GetAddrOfLocalVar(getThreadIDVariable())),
Alexey Bataev62b63b12015-03-10 07:28:44 +0000238 getThreadIDVariable()
239 ->getType()
240 ->castAs<PointerType>()
241 ->getPointeeType());
Alexey Bataev18095712014-10-10 12:19:54 +0000242}
243
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000244void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
245 // 1.2.2 OpenMP Language Terminology
246 // Structured block - An executable statement with a single entry at the
247 // top and a single exit at the bottom.
248 // The point of exit cannot be a branch out of the structured block.
249 // longjmp() and throw() must not violate the entry/exit criteria.
250 CGF.EHStack.pushTerminate();
251 {
252 CodeGenFunction::RunCleanupsScope Scope(CGF);
253 CodeGen(CGF);
254 }
255 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000256}
257
Alexey Bataev62b63b12015-03-10 07:28:44 +0000258LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
259 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +0000260 return CGF.MakeAddrLValue(
Alexey Bataev62b63b12015-03-10 07:28:44 +0000261 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
262 getThreadIDVariable()->getType());
263}
264
Alexey Bataev9959db52014-05-06 10:08:46 +0000265CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000266 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000267 IdentTy = llvm::StructType::create(
268 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
269 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000270 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000271 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000272 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
273 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000274 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000275 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000276}
277
Alexey Bataev91797552015-03-18 04:13:55 +0000278void CGOpenMPRuntime::clear() {
279 InternalVars.clear();
280}
281
John McCall7f416cc2015-09-08 08:05:57 +0000282// Layout information for ident_t.
283static CharUnits getIdentAlign(CodeGenModule &CGM) {
284 return CGM.getPointerAlign();
285}
286static CharUnits getIdentSize(CodeGenModule &CGM) {
287 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
288 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
289}
290static CharUnits getOffsetOfIdentField(CGOpenMPRuntime::IdentFieldIndex Field) {
291 // All the fields except the last are i32, so this works beautifully.
292 return unsigned(Field) * CharUnits::fromQuantity(4);
293}
294static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
295 CGOpenMPRuntime::IdentFieldIndex Field,
296 const llvm::Twine &Name = "") {
297 auto Offset = getOffsetOfIdentField(Field);
298 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
299}
300
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000301llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
302 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
303 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000304 assert(ThreadIDVar->getType()->isPointerType() &&
305 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000306 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
307 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000308 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind);
Alexey Bataevd157d472015-06-24 03:35:38 +0000309 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev18095712014-10-10 12:19:54 +0000310 return CGF.GenerateCapturedStmtFunction(*CS);
311}
312
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000313llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
314 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
315 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000316 assert(!ThreadIDVar->getType()->isPointerType() &&
317 "thread id variable must be of type kmp_int32 for tasks");
318 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
319 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000320 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
321 InnermostKind);
Alexey Bataevd157d472015-06-24 03:35:38 +0000322 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000323 return CGF.GenerateCapturedStmtFunction(*CS);
324}
325
John McCall7f416cc2015-09-08 08:05:57 +0000326Address CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
327 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000328 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000329 if (!Entry) {
330 if (!DefaultOpenMPPSource) {
331 // Initialize default location for psource field of ident_t structure of
332 // all ident_t objects. Format is ";file;function;line;column;;".
333 // Taken from
334 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
335 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000336 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000337 DefaultOpenMPPSource =
338 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
339 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000340 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
341 CGM.getModule(), IdentTy, /*isConstant*/ true,
342 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000343 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000344 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000345
346 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000347 llvm::Constant *Values[] = {Zero,
348 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
349 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000350 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
351 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000352 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000353 }
John McCall7f416cc2015-09-08 08:05:57 +0000354 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000355}
356
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000357llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
358 SourceLocation Loc,
359 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000360 // If no debug info is generated - return global default location.
361 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
362 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000363 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000364
365 assert(CGF.CurFn && "No function in current CodeGenFunction.");
366
John McCall7f416cc2015-09-08 08:05:57 +0000367 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000368 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
369 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000370 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
371
Alexander Musmanc6388682014-12-15 07:07:06 +0000372 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
373 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000374 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000375 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000376 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
377 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000378 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000379 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000380 LocValue = AI;
381
382 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
383 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000384 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000385 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000386 }
387
388 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000389 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000390
Alexey Bataevf002aca2014-05-30 05:48:40 +0000391 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
392 if (OMPDebugLoc == nullptr) {
393 SmallString<128> Buffer2;
394 llvm::raw_svector_ostream OS2(Buffer2);
395 // Build debug location
396 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
397 OS2 << ";" << PLoc.getFilename() << ";";
398 if (const FunctionDecl *FD =
399 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
400 OS2 << FD->getQualifiedNameAsString();
401 }
402 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
403 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
404 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000405 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000406 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000407 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
408
John McCall7f416cc2015-09-08 08:05:57 +0000409 // Our callers always pass this to a runtime function, so for
410 // convenience, go ahead and return a naked pointer.
411 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000412}
413
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000414llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
415 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000416 assert(CGF.CurFn && "No function in current CodeGenFunction.");
417
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000418 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000419 // Check whether we've already cached a load of the thread id in this
420 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000421 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000422 if (I != OpenMPLocThreadIDMap.end()) {
423 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000424 if (ThreadID != nullptr)
425 return ThreadID;
426 }
427 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000428 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000429 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000430 // Check if this an outlined function with thread id passed as argument.
431 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000432 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
433 // If value loaded in entry block, cache it and use it everywhere in
434 // function.
435 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
436 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
437 Elem.second.ThreadID = ThreadID;
438 }
439 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000440 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000441 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000442
443 // This is not an outlined function region - need to call __kmpc_int32
444 // kmpc_global_thread_num(ident_t *loc).
445 // Generate thread id value and cache this value for use across the
446 // function.
447 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
448 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
449 ThreadID =
450 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
451 emitUpdateLocation(CGF, Loc));
452 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
453 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000454 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000455}
456
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000457void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000458 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000459 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
460 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000461}
462
463llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
464 return llvm::PointerType::getUnqual(IdentTy);
465}
466
467llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
468 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
469}
470
471llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000472CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000473 llvm::Constant *RTLFn = nullptr;
474 switch (Function) {
475 case OMPRTL__kmpc_fork_call: {
476 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
477 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000478 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
479 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000480 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000481 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000482 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
483 break;
484 }
485 case OMPRTL__kmpc_global_thread_num: {
486 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000487 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000488 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000489 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000490 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
491 break;
492 }
Alexey Bataev97720002014-11-11 04:05:39 +0000493 case OMPRTL__kmpc_threadprivate_cached: {
494 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
495 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
496 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
497 CGM.VoidPtrTy, CGM.SizeTy,
498 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
499 llvm::FunctionType *FnTy =
500 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
501 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
502 break;
503 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000504 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000505 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
506 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000507 llvm::Type *TypeParams[] = {
508 getIdentTyPointerTy(), CGM.Int32Ty,
509 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
510 llvm::FunctionType *FnTy =
511 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
512 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
513 break;
514 }
Alexey Bataev97720002014-11-11 04:05:39 +0000515 case OMPRTL__kmpc_threadprivate_register: {
516 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
517 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
518 // typedef void *(*kmpc_ctor)(void *);
519 auto KmpcCtorTy =
520 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
521 /*isVarArg*/ false)->getPointerTo();
522 // typedef void *(*kmpc_cctor)(void *, void *);
523 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
524 auto KmpcCopyCtorTy =
525 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
526 /*isVarArg*/ false)->getPointerTo();
527 // typedef void (*kmpc_dtor)(void *);
528 auto KmpcDtorTy =
529 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
530 ->getPointerTo();
531 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
532 KmpcCopyCtorTy, KmpcDtorTy};
533 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
534 /*isVarArg*/ false);
535 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
536 break;
537 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000538 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000539 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
540 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000541 llvm::Type *TypeParams[] = {
542 getIdentTyPointerTy(), CGM.Int32Ty,
543 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
544 llvm::FunctionType *FnTy =
545 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
546 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
547 break;
548 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000549 case OMPRTL__kmpc_cancel_barrier: {
550 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
551 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000552 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
553 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000554 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
555 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000556 break;
557 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000558 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000559 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000560 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
561 llvm::FunctionType *FnTy =
562 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
563 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
564 break;
565 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000566 case OMPRTL__kmpc_for_static_fini: {
567 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 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_for_static_fini");
572 break;
573 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000574 case OMPRTL__kmpc_push_num_threads: {
575 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
576 // kmp_int32 num_threads)
577 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
578 CGM.Int32Ty};
579 llvm::FunctionType *FnTy =
580 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
581 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
582 break;
583 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000584 case OMPRTL__kmpc_serialized_parallel: {
585 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
586 // global_tid);
587 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
588 llvm::FunctionType *FnTy =
589 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
590 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
591 break;
592 }
593 case OMPRTL__kmpc_end_serialized_parallel: {
594 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
595 // global_tid);
596 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
597 llvm::FunctionType *FnTy =
598 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
599 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
600 break;
601 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000602 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000603 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000604 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
605 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000606 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000607 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
608 break;
609 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000610 case OMPRTL__kmpc_master: {
611 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
612 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
613 llvm::FunctionType *FnTy =
614 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
615 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
616 break;
617 }
618 case OMPRTL__kmpc_end_master: {
619 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
620 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
621 llvm::FunctionType *FnTy =
622 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
623 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
624 break;
625 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000626 case OMPRTL__kmpc_omp_taskyield: {
627 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
628 // int end_part);
629 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
630 llvm::FunctionType *FnTy =
631 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
632 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
633 break;
634 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000635 case OMPRTL__kmpc_single: {
636 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
637 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
638 llvm::FunctionType *FnTy =
639 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
640 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
641 break;
642 }
643 case OMPRTL__kmpc_end_single: {
644 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
645 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
646 llvm::FunctionType *FnTy =
647 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
648 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
649 break;
650 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000651 case OMPRTL__kmpc_omp_task_alloc: {
652 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
653 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
654 // kmp_routine_entry_t *task_entry);
655 assert(KmpRoutineEntryPtrTy != nullptr &&
656 "Type kmp_routine_entry_t must be created.");
657 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
658 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
659 // Return void * and then cast to particular kmp_task_t type.
660 llvm::FunctionType *FnTy =
661 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
662 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
663 break;
664 }
665 case OMPRTL__kmpc_omp_task: {
666 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
667 // *new_task);
668 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
669 CGM.VoidPtrTy};
670 llvm::FunctionType *FnTy =
671 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
672 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
673 break;
674 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000675 case OMPRTL__kmpc_copyprivate: {
676 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +0000677 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +0000678 // kmp_int32 didit);
679 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
680 auto *CpyFnTy =
681 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +0000682 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +0000683 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
684 CGM.Int32Ty};
685 llvm::FunctionType *FnTy =
686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
687 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
688 break;
689 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000690 case OMPRTL__kmpc_reduce: {
691 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
692 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
693 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
694 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
695 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
696 /*isVarArg=*/false);
697 llvm::Type *TypeParams[] = {
698 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
699 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
700 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
701 llvm::FunctionType *FnTy =
702 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
703 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
704 break;
705 }
706 case OMPRTL__kmpc_reduce_nowait: {
707 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
708 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
709 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
710 // *lck);
711 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
712 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
713 /*isVarArg=*/false);
714 llvm::Type *TypeParams[] = {
715 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
716 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
717 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
718 llvm::FunctionType *FnTy =
719 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
720 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
721 break;
722 }
723 case OMPRTL__kmpc_end_reduce: {
724 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
725 // kmp_critical_name *lck);
726 llvm::Type *TypeParams[] = {
727 getIdentTyPointerTy(), CGM.Int32Ty,
728 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
729 llvm::FunctionType *FnTy =
730 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
731 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
732 break;
733 }
734 case OMPRTL__kmpc_end_reduce_nowait: {
735 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
736 // kmp_critical_name *lck);
737 llvm::Type *TypeParams[] = {
738 getIdentTyPointerTy(), CGM.Int32Ty,
739 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
740 llvm::FunctionType *FnTy =
741 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
742 RTLFn =
743 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
744 break;
745 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000746 case OMPRTL__kmpc_omp_task_begin_if0: {
747 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
748 // *new_task);
749 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
750 CGM.VoidPtrTy};
751 llvm::FunctionType *FnTy =
752 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
753 RTLFn =
754 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
755 break;
756 }
757 case OMPRTL__kmpc_omp_task_complete_if0: {
758 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
759 // *new_task);
760 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
761 CGM.VoidPtrTy};
762 llvm::FunctionType *FnTy =
763 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
764 RTLFn = CGM.CreateRuntimeFunction(FnTy,
765 /*Name=*/"__kmpc_omp_task_complete_if0");
766 break;
767 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000768 case OMPRTL__kmpc_ordered: {
769 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
770 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
771 llvm::FunctionType *FnTy =
772 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
773 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
774 break;
775 }
776 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000777 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000778 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
779 llvm::FunctionType *FnTy =
780 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
781 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
782 break;
783 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +0000784 case OMPRTL__kmpc_omp_taskwait: {
785 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
786 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
787 llvm::FunctionType *FnTy =
788 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
789 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
790 break;
791 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000792 case OMPRTL__kmpc_taskgroup: {
793 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
794 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
795 llvm::FunctionType *FnTy =
796 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
797 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
798 break;
799 }
800 case OMPRTL__kmpc_end_taskgroup: {
801 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
802 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
803 llvm::FunctionType *FnTy =
804 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
805 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
806 break;
807 }
Alexey Bataev7f210c62015-06-18 13:40:03 +0000808 case OMPRTL__kmpc_push_proc_bind: {
809 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
810 // int proc_bind)
811 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
812 llvm::FunctionType *FnTy =
813 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
814 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
815 break;
816 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +0000817 case OMPRTL__kmpc_omp_task_with_deps: {
818 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
819 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
820 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
821 llvm::Type *TypeParams[] = {
822 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
823 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
824 llvm::FunctionType *FnTy =
825 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
826 RTLFn =
827 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
828 break;
829 }
830 case OMPRTL__kmpc_omp_wait_deps: {
831 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
832 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
833 // kmp_depend_info_t *noalias_dep_list);
834 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
835 CGM.Int32Ty, CGM.VoidPtrTy,
836 CGM.Int32Ty, CGM.VoidPtrTy};
837 llvm::FunctionType *FnTy =
838 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
839 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
840 break;
841 }
Alexey Bataev0f34da12015-07-02 04:17:07 +0000842 case OMPRTL__kmpc_cancellationpoint: {
843 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
844 // global_tid, kmp_int32 cncl_kind)
845 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
846 llvm::FunctionType *FnTy =
847 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
848 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
849 break;
850 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000851 case OMPRTL__kmpc_cancel: {
852 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
853 // kmp_int32 cncl_kind)
854 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
855 llvm::FunctionType *FnTy =
856 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
857 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
858 break;
859 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000860 }
861 return RTLFn;
862}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000863
Alexander Musman21212e42015-03-13 10:38:23 +0000864llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
865 bool IVSigned) {
866 assert((IVSize == 32 || IVSize == 64) &&
867 "IV size is not compatible with the omp runtime");
868 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
869 : "__kmpc_for_static_init_4u")
870 : (IVSigned ? "__kmpc_for_static_init_8"
871 : "__kmpc_for_static_init_8u");
872 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
873 auto PtrTy = llvm::PointerType::getUnqual(ITy);
874 llvm::Type *TypeParams[] = {
875 getIdentTyPointerTy(), // loc
876 CGM.Int32Ty, // tid
877 CGM.Int32Ty, // schedtype
878 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
879 PtrTy, // p_lower
880 PtrTy, // p_upper
881 PtrTy, // p_stride
882 ITy, // incr
883 ITy // chunk
884 };
885 llvm::FunctionType *FnTy =
886 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
887 return CGM.CreateRuntimeFunction(FnTy, Name);
888}
889
Alexander Musman92bdaab2015-03-12 13:37:50 +0000890llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
891 bool IVSigned) {
892 assert((IVSize == 32 || IVSize == 64) &&
893 "IV size is not compatible with the omp runtime");
894 auto Name =
895 IVSize == 32
896 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
897 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
898 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
899 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
900 CGM.Int32Ty, // tid
901 CGM.Int32Ty, // schedtype
902 ITy, // lower
903 ITy, // upper
904 ITy, // stride
905 ITy // chunk
906 };
907 llvm::FunctionType *FnTy =
908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
909 return CGM.CreateRuntimeFunction(FnTy, Name);
910}
911
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000912llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
913 bool IVSigned) {
914 assert((IVSize == 32 || IVSize == 64) &&
915 "IV size is not compatible with the omp runtime");
916 auto Name =
917 IVSize == 32
918 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
919 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
920 llvm::Type *TypeParams[] = {
921 getIdentTyPointerTy(), // loc
922 CGM.Int32Ty, // tid
923 };
924 llvm::FunctionType *FnTy =
925 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
926 return CGM.CreateRuntimeFunction(FnTy, Name);
927}
928
Alexander Musman92bdaab2015-03-12 13:37:50 +0000929llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
930 bool IVSigned) {
931 assert((IVSize == 32 || IVSize == 64) &&
932 "IV size is not compatible with the omp runtime");
933 auto Name =
934 IVSize == 32
935 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
936 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
937 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
938 auto PtrTy = llvm::PointerType::getUnqual(ITy);
939 llvm::Type *TypeParams[] = {
940 getIdentTyPointerTy(), // loc
941 CGM.Int32Ty, // tid
942 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
943 PtrTy, // p_lower
944 PtrTy, // p_upper
945 PtrTy // p_stride
946 };
947 llvm::FunctionType *FnTy =
948 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
949 return CGM.CreateRuntimeFunction(FnTy, Name);
950}
951
Alexey Bataev97720002014-11-11 04:05:39 +0000952llvm::Constant *
953CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +0000954 assert(!CGM.getLangOpts().OpenMPUseTLS ||
955 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +0000956 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000957 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000958 Twine(CGM.getMangledName(VD)) + ".cache.");
959}
960
John McCall7f416cc2015-09-08 08:05:57 +0000961Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
962 const VarDecl *VD,
963 Address VDAddr,
964 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +0000965 if (CGM.getLangOpts().OpenMPUseTLS &&
966 CGM.getContext().getTargetInfo().isTLSSupported())
967 return VDAddr;
968
John McCall7f416cc2015-09-08 08:05:57 +0000969 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000970 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +0000971 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
972 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +0000973 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
974 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +0000975 return Address(CGF.EmitRuntimeCall(
976 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
977 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +0000978}
979
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000980void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +0000981 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +0000982 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
983 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
984 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000985 auto OMPLoc = emitUpdateLocation(CGF, Loc);
986 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000987 OMPLoc);
988 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
989 // to register constructor/destructor for variable.
990 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +0000991 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
992 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +0000993 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000994 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000995 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000996}
997
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000998llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +0000999 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001000 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001001 if (CGM.getLangOpts().OpenMPUseTLS &&
1002 CGM.getContext().getTargetInfo().isTLSSupported())
1003 return nullptr;
1004
Alexey Bataev97720002014-11-11 04:05:39 +00001005 VD = VD->getDefinition(CGM.getContext());
1006 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1007 ThreadPrivateWithDefinition.insert(VD);
1008 QualType ASTTy = VD->getType();
1009
1010 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1011 auto Init = VD->getAnyInitializer();
1012 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1013 // Generate function that re-emits the declaration's initializer into the
1014 // threadprivate copy of the variable VD
1015 CodeGenFunction CtorCGF(CGM);
1016 FunctionArgList Args;
1017 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1018 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1019 Args.push_back(&Dst);
1020
1021 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1022 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
1023 /*isVariadic=*/false);
1024 auto FTy = CGM.getTypes().GetFunctionType(FI);
1025 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1026 FTy, ".__kmpc_global_ctor_.", Loc);
1027 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1028 Args, SourceLocation());
1029 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001030 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001031 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001032 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1033 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1034 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001035 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1036 /*IsInitializer=*/true);
1037 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001038 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001039 CGM.getContext().VoidPtrTy, Dst.getLocation());
1040 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1041 CtorCGF.FinishFunction();
1042 Ctor = Fn;
1043 }
1044 if (VD->getType().isDestructedType() != QualType::DK_none) {
1045 // Generate function that emits destructor call for the threadprivate copy
1046 // of the variable VD
1047 CodeGenFunction DtorCGF(CGM);
1048 FunctionArgList Args;
1049 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1050 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1051 Args.push_back(&Dst);
1052
1053 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1054 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1055 /*isVariadic=*/false);
1056 auto FTy = CGM.getTypes().GetFunctionType(FI);
1057 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1058 FTy, ".__kmpc_global_dtor_.", Loc);
1059 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1060 SourceLocation());
1061 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1062 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001063 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1064 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001065 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1066 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1067 DtorCGF.FinishFunction();
1068 Dtor = Fn;
1069 }
1070 // Do not emit init function if it is not required.
1071 if (!Ctor && !Dtor)
1072 return nullptr;
1073
1074 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1075 auto CopyCtorTy =
1076 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1077 /*isVarArg=*/false)->getPointerTo();
1078 // Copying constructor for the threadprivate variable.
1079 // Must be NULL - reserved by runtime, but currently it requires that this
1080 // parameter is always NULL. Otherwise it fires assertion.
1081 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1082 if (Ctor == nullptr) {
1083 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1084 /*isVarArg=*/false)->getPointerTo();
1085 Ctor = llvm::Constant::getNullValue(CtorTy);
1086 }
1087 if (Dtor == nullptr) {
1088 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1089 /*isVarArg=*/false)->getPointerTo();
1090 Dtor = llvm::Constant::getNullValue(DtorTy);
1091 }
1092 if (!CGF) {
1093 auto InitFunctionTy =
1094 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1095 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1096 InitFunctionTy, ".__omp_threadprivate_init_.");
1097 CodeGenFunction InitCGF(CGM);
1098 FunctionArgList ArgList;
1099 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1100 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1101 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001102 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001103 InitCGF.FinishFunction();
1104 return InitFunction;
1105 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001106 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001107 }
1108 return nullptr;
1109}
1110
Alexey Bataev1d677132015-04-22 13:57:31 +00001111/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1112/// function. Here is the logic:
1113/// if (Cond) {
1114/// ThenGen();
1115/// } else {
1116/// ElseGen();
1117/// }
1118static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1119 const RegionCodeGenTy &ThenGen,
1120 const RegionCodeGenTy &ElseGen) {
1121 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1122
1123 // If the condition constant folds and can be elided, try to avoid emitting
1124 // the condition and the dead arm of the if/else.
1125 bool CondConstant;
1126 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1127 CodeGenFunction::RunCleanupsScope Scope(CGF);
1128 if (CondConstant) {
1129 ThenGen(CGF);
1130 } else {
1131 ElseGen(CGF);
1132 }
1133 return;
1134 }
1135
1136 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1137 // emit the conditional branch.
1138 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1139 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1140 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1141 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1142
1143 // Emit the 'then' code.
1144 CGF.EmitBlock(ThenBlock);
1145 {
1146 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1147 ThenGen(CGF);
1148 }
1149 CGF.EmitBranch(ContBlock);
1150 // Emit the 'else' code if present.
1151 {
1152 // There is no need to emit line number for unconditional branch.
1153 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1154 CGF.EmitBlock(ElseBlock);
1155 }
1156 {
1157 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1158 ElseGen(CGF);
1159 }
1160 {
1161 // There is no need to emit line number for unconditional branch.
1162 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1163 CGF.EmitBranch(ContBlock);
1164 }
1165 // Emit the continuation block for code after the if.
1166 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001167}
1168
Alexey Bataev1d677132015-04-22 13:57:31 +00001169void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1170 llvm::Value *OutlinedFn,
John McCall7f416cc2015-09-08 08:05:57 +00001171 Address CapturedStruct,
Alexey Bataev1d677132015-04-22 13:57:31 +00001172 const Expr *IfCond) {
1173 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1174 auto &&ThenGen =
1175 [this, OutlinedFn, CapturedStruct, RTLoc](CodeGenFunction &CGF) {
1176 // Build call __kmpc_fork_call(loc, 1, microtask,
1177 // captured_struct/*context*/)
1178 llvm::Value *Args[] = {
1179 RTLoc,
1180 CGF.Builder.getInt32(
1181 1), // Number of arguments after 'microtask' argument
1182 // (there is only one additional argument - 'context')
1183 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
John McCall7f416cc2015-09-08 08:05:57 +00001184 CGF.EmitCastToVoidPtr(CapturedStruct.getPointer())};
Alexey Bataev1d677132015-04-22 13:57:31 +00001185 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1186 CGF.EmitRuntimeCall(RTLFn, Args);
1187 };
1188 auto &&ElseGen = [this, OutlinedFn, CapturedStruct, RTLoc, Loc](
1189 CodeGenFunction &CGF) {
1190 auto ThreadID = getThreadID(CGF, Loc);
1191 // Build calls:
1192 // __kmpc_serialized_parallel(&Loc, GTid);
1193 llvm::Value *Args[] = {RTLoc, ThreadID};
1194 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1195 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001196
Alexey Bataev1d677132015-04-22 13:57:31 +00001197 // OutlinedFn(&GTid, &zero, CapturedStruct);
1198 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001199 Address ZeroAddr =
1200 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1201 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001202 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
John McCall7f416cc2015-09-08 08:05:57 +00001203 llvm::Value *OutlinedFnArgs[] = {
1204 ThreadIDAddr.getPointer(),
1205 ZeroAddr.getPointer(),
1206 CapturedStruct.getPointer()
1207 };
Alexey Bataev1d677132015-04-22 13:57:31 +00001208 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001209
Alexey Bataev1d677132015-04-22 13:57:31 +00001210 // __kmpc_end_serialized_parallel(&Loc, GTid);
1211 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1212 CGF.EmitRuntimeCall(
1213 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1214 };
1215 if (IfCond) {
1216 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1217 } else {
1218 CodeGenFunction::RunCleanupsScope Scope(CGF);
1219 ThenGen(CGF);
1220 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001221}
1222
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001223// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001224// thread-ID variable (it is passed in a first argument of the outlined function
1225// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1226// regular serial code region, get thread ID by calling kmp_int32
1227// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1228// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001229Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1230 SourceLocation Loc) {
Alexey Bataevd74d0602014-10-13 06:02:40 +00001231 if (auto OMPRegionInfo =
1232 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001233 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001234 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001235
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001236 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001237 auto Int32Ty =
1238 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1239 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1240 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001241 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001242
1243 return ThreadIDTemp;
1244}
1245
Alexey Bataev97720002014-11-11 04:05:39 +00001246llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001247CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001248 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001249 SmallString<256> Buffer;
1250 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001251 Out << Name;
1252 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001253 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1254 if (Elem.second) {
1255 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001256 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001257 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001258 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001259
David Blaikie13156b62014-11-19 03:06:06 +00001260 return Elem.second = new llvm::GlobalVariable(
1261 CGM.getModule(), Ty, /*IsConstant*/ false,
1262 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1263 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001264}
1265
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001266llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001267 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001268 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001269}
1270
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001271namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001272template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001273 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001274 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001275
1276public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001277 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1278 : Callee(Callee) {
1279 assert(CleanupArgs.size() == N);
1280 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1281 }
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001282 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1283 CGF.EmitRuntimeCall(Callee, Args);
1284 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001285};
1286} // namespace
1287
1288void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1289 StringRef CriticalName,
1290 const RegionCodeGenTy &CriticalOpGen,
1291 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001292 // __kmpc_critical(ident_t *, gtid, Lock);
1293 // CriticalOpGen();
1294 // __kmpc_end_critical(ident_t *, gtid, Lock);
1295 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001296 {
1297 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001298 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1299 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001300 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001301 // Build a call to __kmpc_end_critical
Alexey Bataeva744ff52015-05-05 09:24:37 +00001302 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001303 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1304 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001305 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001306 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001307}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001308
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001309static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001310 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001311 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001312 llvm::Value *CallBool = CGF.EmitScalarConversion(
1313 IfCond,
1314 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001315 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001316
1317 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1318 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1319 // Generate the branch (If-stmt)
1320 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1321 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001322 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001323 // Emit the rest of bblocks/branches
1324 CGF.EmitBranch(ContBlock);
1325 CGF.EmitBlock(ContBlock, true);
1326}
1327
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001328void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001329 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001330 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001331 // if(__kmpc_master(ident_t *, gtid)) {
1332 // MasterOpGen();
1333 // __kmpc_end_master(ident_t *, gtid);
1334 // }
1335 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001336 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001337 auto *IsMaster =
1338 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001339 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1340 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001341 emitIfStmt(
1342 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1343 CodeGenFunction::RunCleanupsScope Scope(CGF);
1344 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1345 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1346 llvm::makeArrayRef(Args));
1347 MasterOpGen(CGF);
1348 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001349}
1350
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001351void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1352 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001353 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1354 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001355 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001356 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001357 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001358}
1359
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001360void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1361 const RegionCodeGenTy &TaskgroupOpGen,
1362 SourceLocation Loc) {
1363 // __kmpc_taskgroup(ident_t *, gtid);
1364 // TaskgroupOpGen();
1365 // __kmpc_end_taskgroup(ident_t *, gtid);
1366 // Prepare arguments and build a call to __kmpc_taskgroup
1367 {
1368 CodeGenFunction::RunCleanupsScope Scope(CGF);
1369 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1370 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1371 // Build a call to __kmpc_end_taskgroup
1372 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1373 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1374 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001375 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001376 }
1377}
1378
John McCall7f416cc2015-09-08 08:05:57 +00001379/// Given an array of pointers to variables, project the address of a
1380/// given variable.
1381static Address emitAddrOfVarFromArray(CodeGenFunction &CGF,
1382 Address Array, unsigned Index,
1383 const VarDecl *Var) {
1384 // Pull out the pointer to the variable.
1385 Address PtrAddr =
1386 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
1387 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1388
1389 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
1390 Addr = CGF.Builder.CreateElementBitCast(Addr,
1391 CGF.ConvertTypeForMem(Var->getType()));
1392 return Addr;
1393}
1394
Alexey Bataeva63048e2015-03-23 06:18:07 +00001395static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001396 CodeGenModule &CGM, llvm::Type *ArgsType,
1397 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1398 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001399 auto &C = CGM.getContext();
1400 // void copy_func(void *LHSArg, void *RHSArg);
1401 FunctionArgList Args;
1402 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1403 C.VoidPtrTy);
1404 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1405 C.VoidPtrTy);
1406 Args.push_back(&LHSArg);
1407 Args.push_back(&RHSArg);
1408 FunctionType::ExtInfo EI;
1409 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1410 C.VoidTy, Args, EI, /*isVariadic=*/false);
1411 auto *Fn = llvm::Function::Create(
1412 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1413 ".omp.copyprivate.copy_func", &CGM.getModule());
1414 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1415 CodeGenFunction CGF(CGM);
1416 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001417 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001418 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001419 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1420 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1421 ArgsType), CGF.getPointerAlign());
1422 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1423 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1424 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001425 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1426 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1427 // ...
1428 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001429 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001430 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1431 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1432
1433 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1434 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1435
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001436 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1437 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001438 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001439 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001440 CGF.FinishFunction();
1441 return Fn;
1442}
1443
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001444void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001445 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001446 SourceLocation Loc,
1447 ArrayRef<const Expr *> CopyprivateVars,
1448 ArrayRef<const Expr *> SrcExprs,
1449 ArrayRef<const Expr *> DstExprs,
1450 ArrayRef<const Expr *> AssignmentOps) {
1451 assert(CopyprivateVars.size() == SrcExprs.size() &&
1452 CopyprivateVars.size() == DstExprs.size() &&
1453 CopyprivateVars.size() == AssignmentOps.size());
1454 auto &C = CGM.getContext();
1455 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001456 // if(__kmpc_single(ident_t *, gtid)) {
1457 // SingleOpGen();
1458 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001459 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001460 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001461 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1462 // <copy_func>, did_it);
1463
John McCall7f416cc2015-09-08 08:05:57 +00001464 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001465 if (!CopyprivateVars.empty()) {
1466 // int32 did_it = 0;
1467 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1468 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00001469 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001470 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001471 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001472 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001473 auto *IsSingle =
1474 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001475 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1476 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001477 emitIfStmt(
1478 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
1479 CodeGenFunction::RunCleanupsScope Scope(CGF);
1480 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
1481 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1482 llvm::makeArrayRef(Args));
1483 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001484 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001485 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00001486 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001487 }
1488 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001489 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1490 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00001491 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001492 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1493 auto CopyprivateArrayTy =
1494 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1495 /*IndexTypeQuals=*/0);
1496 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00001497 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001498 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1499 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001500 Address Elem = CGF.Builder.CreateConstArrayGEP(
1501 CopyprivateList, I, CGF.getPointerSize());
1502 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00001503 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00001504 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
1505 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001506 }
1507 // Build function that copies private values from single region to all other
1508 // threads in the corresponding parallel region.
1509 auto *CpyFn = emitCopyprivateCopyFunction(
1510 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001511 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001512 auto *BufSize = llvm::ConstantInt::get(
1513 CGM.SizeTy, C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00001514 Address CL =
1515 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1516 CGF.VoidPtrTy);
1517 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001518 llvm::Value *Args[] = {
1519 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1520 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001521 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00001522 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001523 CpyFn, // void (*) (void *, void *) <copy_func>
1524 DidItVal // i32 did_it
1525 };
1526 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1527 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001528}
1529
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001530void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1531 const RegionCodeGenTy &OrderedOpGen,
1532 SourceLocation Loc) {
1533 // __kmpc_ordered(ident_t *, gtid);
1534 // OrderedOpGen();
1535 // __kmpc_end_ordered(ident_t *, gtid);
1536 // Prepare arguments and build a call to __kmpc_ordered
1537 {
1538 CodeGenFunction::RunCleanupsScope Scope(CGF);
1539 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1540 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1541 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001542 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001543 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1544 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001545 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001546 }
1547}
1548
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001549void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001550 OpenMPDirectiveKind Kind,
1551 bool CheckForCancel) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001552 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001553 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001554 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1555 if (Kind == OMPD_for) {
1556 Flags =
1557 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1558 } else if (Kind == OMPD_sections) {
1559 Flags = static_cast<OpenMPLocationFlags>(Flags |
1560 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1561 } else if (Kind == OMPD_single) {
1562 Flags =
1563 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1564 } else if (Kind == OMPD_barrier) {
1565 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1566 } else {
1567 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1568 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001569 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
1570 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001571 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1572 getThreadID(CGF, Loc)};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001573 if (auto *OMPRegionInfo =
1574 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1575 auto CancelDestination =
1576 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
1577 if (CancelDestination.isValid()) {
1578 auto *Result = CGF.EmitRuntimeCall(
1579 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
1580 if (CheckForCancel) {
1581 // if (__kmpc_cancel_barrier()) {
1582 // exit from construct;
1583 // }
1584 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
1585 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
1586 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
1587 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
1588 CGF.EmitBlock(ExitBB);
1589 // exit from construct;
1590 CGF.EmitBranchThroughCleanup(CancelDestination);
1591 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
1592 }
1593 return;
1594 }
1595 }
1596 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001597}
1598
Alexander Musmanc6388682014-12-15 07:07:06 +00001599/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1600/// the enum sched_type in kmp.h).
1601enum OpenMPSchedType {
1602 /// \brief Lower bound for default (unordered) versions.
1603 OMP_sch_lower = 32,
1604 OMP_sch_static_chunked = 33,
1605 OMP_sch_static = 34,
1606 OMP_sch_dynamic_chunked = 35,
1607 OMP_sch_guided_chunked = 36,
1608 OMP_sch_runtime = 37,
1609 OMP_sch_auto = 38,
1610 /// \brief Lower bound for 'ordered' versions.
1611 OMP_ord_lower = 64,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001612 OMP_ord_static_chunked = 65,
1613 OMP_ord_static = 66,
1614 OMP_ord_dynamic_chunked = 67,
1615 OMP_ord_guided_chunked = 68,
1616 OMP_ord_runtime = 69,
1617 OMP_ord_auto = 70,
1618 OMP_sch_default = OMP_sch_static,
Alexander Musmanc6388682014-12-15 07:07:06 +00001619};
1620
1621/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1622static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001623 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001624 switch (ScheduleKind) {
1625 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001626 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
1627 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00001628 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001629 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001630 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001631 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001632 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001633 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
1634 case OMPC_SCHEDULE_auto:
1635 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00001636 case OMPC_SCHEDULE_unknown:
1637 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001638 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00001639 }
1640 llvm_unreachable("Unexpected runtime schedule");
1641}
1642
1643bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1644 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001645 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00001646 return Schedule == OMP_sch_static;
1647}
1648
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001649bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001650 auto Schedule =
1651 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001652 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1653 return Schedule != OMP_sch_static;
1654}
1655
John McCall7f416cc2015-09-08 08:05:57 +00001656void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
1657 SourceLocation Loc,
1658 OpenMPScheduleClauseKind ScheduleKind,
1659 unsigned IVSize, bool IVSigned,
1660 bool Ordered, llvm::Value *UB,
1661 llvm::Value *Chunk) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001662 OpenMPSchedType Schedule =
1663 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00001664 assert(Ordered ||
1665 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
1666 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
1667 // Call __kmpc_dispatch_init(
1668 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1669 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1670 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001671
John McCall7f416cc2015-09-08 08:05:57 +00001672 // If the Chunk was not specified in the clause - use default value 1.
1673 if (Chunk == nullptr)
1674 Chunk = CGF.Builder.getIntN(IVSize, 1);
1675 llvm::Value *Args[] = {
1676 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1677 getThreadID(CGF, Loc),
1678 CGF.Builder.getInt32(Schedule), // Schedule type
1679 CGF.Builder.getIntN(IVSize, 0), // Lower
1680 UB, // Upper
1681 CGF.Builder.getIntN(IVSize, 1), // Stride
1682 Chunk // Chunk
1683 };
1684 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1685}
1686
1687void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
1688 SourceLocation Loc,
1689 OpenMPScheduleClauseKind ScheduleKind,
1690 unsigned IVSize, bool IVSigned,
1691 bool Ordered, Address IL, Address LB,
1692 Address UB, Address ST,
1693 llvm::Value *Chunk) {
1694 OpenMPSchedType Schedule =
1695 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
1696 assert(!Ordered);
1697 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
1698 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked);
1699
1700 // Call __kmpc_for_static_init(
1701 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1702 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1703 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1704 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1705 if (Chunk == nullptr) {
1706 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
1707 "expected static non-chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00001708 // If the Chunk was not specified in the clause - use default value 1.
Alexander Musman92bdaab2015-03-12 13:37:50 +00001709 Chunk = CGF.Builder.getIntN(IVSize, 1);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001710 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001711 assert((Schedule == OMP_sch_static_chunked ||
1712 Schedule == OMP_ord_static_chunked) &&
1713 "expected static chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00001714 }
John McCall7f416cc2015-09-08 08:05:57 +00001715 llvm::Value *Args[] = {
1716 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1717 getThreadID(CGF, Loc),
1718 CGF.Builder.getInt32(Schedule), // Schedule type
1719 IL.getPointer(), // &isLastIter
1720 LB.getPointer(), // &LB
1721 UB.getPointer(), // &UB
1722 ST.getPointer(), // &Stride
1723 CGF.Builder.getIntN(IVSize, 1), // Incr
1724 Chunk // Chunk
1725 };
1726 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001727}
1728
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001729void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1730 SourceLocation Loc) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001731 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001732 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1733 getThreadID(CGF, Loc)};
1734 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1735 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001736}
1737
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001738void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
1739 SourceLocation Loc,
1740 unsigned IVSize,
1741 bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001742 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1743 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1744 getThreadID(CGF, Loc)};
1745 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1746}
1747
Alexander Musman92bdaab2015-03-12 13:37:50 +00001748llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1749 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00001750 bool IVSigned, Address IL,
1751 Address LB, Address UB,
1752 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001753 // Call __kmpc_dispatch_next(
1754 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1755 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1756 // kmp_int[32|64] *p_stride);
1757 llvm::Value *Args[] = {
1758 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001759 IL.getPointer(), // &isLastIter
1760 LB.getPointer(), // &Lower
1761 UB.getPointer(), // &Upper
1762 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00001763 };
1764 llvm::Value *Call =
1765 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1766 return CGF.EmitScalarConversion(
1767 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001768 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001769}
1770
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001771void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1772 llvm::Value *NumThreads,
1773 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001774 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1775 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001776 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001777 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001778 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1779 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001780}
1781
Alexey Bataev7f210c62015-06-18 13:40:03 +00001782void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
1783 OpenMPProcBindClauseKind ProcBind,
1784 SourceLocation Loc) {
1785 // Constants for proc bind value accepted by the runtime.
1786 enum ProcBindTy {
1787 ProcBindFalse = 0,
1788 ProcBindTrue,
1789 ProcBindMaster,
1790 ProcBindClose,
1791 ProcBindSpread,
1792 ProcBindIntel,
1793 ProcBindDefault
1794 } RuntimeProcBind;
1795 switch (ProcBind) {
1796 case OMPC_PROC_BIND_master:
1797 RuntimeProcBind = ProcBindMaster;
1798 break;
1799 case OMPC_PROC_BIND_close:
1800 RuntimeProcBind = ProcBindClose;
1801 break;
1802 case OMPC_PROC_BIND_spread:
1803 RuntimeProcBind = ProcBindSpread;
1804 break;
1805 case OMPC_PROC_BIND_unknown:
1806 llvm_unreachable("Unsupported proc_bind value.");
1807 }
1808 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
1809 llvm::Value *Args[] = {
1810 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1811 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
1812 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
1813}
1814
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001815void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1816 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001817 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001818 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1819 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001820}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001821
Alexey Bataev62b63b12015-03-10 07:28:44 +00001822namespace {
1823/// \brief Indexes of fields for type kmp_task_t.
1824enum KmpTaskTFields {
1825 /// \brief List of shared variables.
1826 KmpTaskTShareds,
1827 /// \brief Task routine.
1828 KmpTaskTRoutine,
1829 /// \brief Partition id for the untied tasks.
1830 KmpTaskTPartId,
1831 /// \brief Function with call of destructors for private variables.
1832 KmpTaskTDestructors,
1833};
1834} // namespace
1835
1836void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1837 if (!KmpRoutineEntryPtrTy) {
1838 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1839 auto &C = CGM.getContext();
1840 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1841 FunctionProtoType::ExtProtoInfo EPI;
1842 KmpRoutineEntryPtrQTy = C.getPointerType(
1843 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1844 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1845 }
1846}
1847
1848static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1849 QualType FieldTy) {
1850 auto *Field = FieldDecl::Create(
1851 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1852 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1853 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1854 Field->setAccess(AS_public);
1855 DC->addDecl(Field);
1856}
1857
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001858namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00001859struct PrivateHelpersTy {
1860 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
1861 const VarDecl *PrivateElemInit)
1862 : Original(Original), PrivateCopy(PrivateCopy),
1863 PrivateElemInit(PrivateElemInit) {}
1864 const VarDecl *Original;
1865 const VarDecl *PrivateCopy;
1866 const VarDecl *PrivateElemInit;
1867};
1868typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001869} // namespace
1870
Alexey Bataev9e034042015-05-05 04:05:12 +00001871static RecordDecl *
1872createPrivatesRecordDecl(CodeGenModule &CGM,
1873 const ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001874 if (!Privates.empty()) {
1875 auto &C = CGM.getContext();
1876 // Build struct .kmp_privates_t. {
1877 // /* private vars */
1878 // };
1879 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
1880 RD->startDefinition();
1881 for (auto &&Pair : Privates) {
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001882 auto Type = Pair.second.Original->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001883 Type = Type.getNonReferenceType();
1884 addFieldToRecordDecl(C, RD, Type);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001885 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001886 RD->completeDefinition();
1887 return RD;
1888 }
1889 return nullptr;
1890}
1891
Alexey Bataev9e034042015-05-05 04:05:12 +00001892static RecordDecl *
1893createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001894 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001895 auto &C = CGM.getContext();
1896 // Build struct kmp_task_t {
1897 // void * shareds;
1898 // kmp_routine_entry_t routine;
1899 // kmp_int32 part_id;
1900 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001901 // };
1902 auto *RD = C.buildImplicitRecord("kmp_task_t");
1903 RD->startDefinition();
1904 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1905 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1906 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1907 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001908 RD->completeDefinition();
1909 return RD;
1910}
1911
1912static RecordDecl *
1913createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
1914 const ArrayRef<PrivateDataTy> Privates) {
1915 auto &C = CGM.getContext();
1916 // Build struct kmp_task_t_with_privates {
1917 // kmp_task_t task_data;
1918 // .kmp_privates_t. privates;
1919 // };
1920 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
1921 RD->startDefinition();
1922 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001923 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
1924 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
1925 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001926 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001927 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001928}
1929
1930/// \brief Emit a proxy function which accepts kmp_task_t as the second
1931/// argument.
1932/// \code
1933/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001934/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
1935/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001936/// return 0;
1937/// }
1938/// \endcode
1939static llvm::Value *
1940emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001941 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
1942 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001943 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1944 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001945 auto &C = CGM.getContext();
1946 FunctionArgList Args;
1947 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1948 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001949 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001950 Args.push_back(&GtidArg);
1951 Args.push_back(&TaskTypeArg);
1952 FunctionType::ExtInfo Info;
1953 auto &TaskEntryFnInfo =
1954 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1955 /*isVariadic=*/false);
1956 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1957 auto *TaskEntry =
1958 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1959 ".omp_task_entry.", &CGM.getModule());
1960 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1961 CodeGenFunction CGF(CGM);
1962 CGF.disableDebugInfo();
1963 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1964
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001965 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
1966 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001967 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001968 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
1969 auto *TaskTypeArgAddr = CGF.Builder.CreateLoad(
1970 CGF.GetAddrOfLocalVar(&TaskTypeArg));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001971 LValue TDBase =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001972 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1973 auto *KmpTaskTWithPrivatesQTyRD =
1974 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001975 LValue Base =
1976 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001977 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
1978 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
1979 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
1980 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
1981
1982 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
1983 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001984 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001985 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001986 CGF.ConvertTypeForMem(SharedsPtrTy));
1987
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001988 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
1989 llvm::Value *PrivatesParam;
1990 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
1991 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
1992 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00001993 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001994 } else {
1995 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
1996 }
1997
1998 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
1999 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002000 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
2001 CGF.EmitStoreThroughLValue(
2002 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00002003 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002004 CGF.FinishFunction();
2005 return TaskEntry;
2006}
2007
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002008static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
2009 SourceLocation Loc,
2010 QualType KmpInt32Ty,
2011 QualType KmpTaskTWithPrivatesPtrQTy,
2012 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002013 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002014 FunctionArgList Args;
2015 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2016 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002017 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002018 Args.push_back(&GtidArg);
2019 Args.push_back(&TaskTypeArg);
2020 FunctionType::ExtInfo Info;
2021 auto &DestructorFnInfo =
2022 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2023 /*isVariadic=*/false);
2024 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
2025 auto *DestructorFn =
2026 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
2027 ".omp_task_destructor.", &CGM.getModule());
2028 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, DestructorFnInfo, DestructorFn);
2029 CodeGenFunction CGF(CGM);
2030 CGF.disableDebugInfo();
2031 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
2032 Args);
2033
John McCall7f416cc2015-09-08 08:05:57 +00002034 auto *TaskTypeArgAddr = CGF.Builder.CreateLoad(
2035 CGF.GetAddrOfLocalVar(&TaskTypeArg));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002036 LValue Base =
2037 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
2038 auto *KmpTaskTWithPrivatesQTyRD =
2039 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
2040 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002041 Base = CGF.EmitLValueForField(Base, *FI);
2042 for (auto *Field :
2043 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
2044 if (auto DtorKind = Field->getType().isDestructedType()) {
2045 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
2046 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
2047 }
2048 }
2049 CGF.FinishFunction();
2050 return DestructorFn;
2051}
2052
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002053/// \brief Emit a privates mapping function for correct handling of private and
2054/// firstprivate variables.
2055/// \code
2056/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
2057/// **noalias priv1,..., <tyn> **noalias privn) {
2058/// *priv1 = &.privates.priv1;
2059/// ...;
2060/// *privn = &.privates.privn;
2061/// }
2062/// \endcode
2063static llvm::Value *
2064emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
2065 const ArrayRef<const Expr *> PrivateVars,
2066 const ArrayRef<const Expr *> FirstprivateVars,
2067 QualType PrivatesQTy,
2068 const ArrayRef<PrivateDataTy> Privates) {
2069 auto &C = CGM.getContext();
2070 FunctionArgList Args;
2071 ImplicitParamDecl TaskPrivatesArg(
2072 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2073 C.getPointerType(PrivatesQTy).withConst().withRestrict());
2074 Args.push_back(&TaskPrivatesArg);
2075 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
2076 unsigned Counter = 1;
2077 for (auto *E: PrivateVars) {
2078 Args.push_back(ImplicitParamDecl::Create(
2079 C, /*DC=*/nullptr, Loc,
2080 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2081 .withConst()
2082 .withRestrict()));
2083 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2084 PrivateVarsPos[VD] = Counter;
2085 ++Counter;
2086 }
2087 for (auto *E : FirstprivateVars) {
2088 Args.push_back(ImplicitParamDecl::Create(
2089 C, /*DC=*/nullptr, Loc,
2090 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2091 .withConst()
2092 .withRestrict()));
2093 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2094 PrivateVarsPos[VD] = Counter;
2095 ++Counter;
2096 }
2097 FunctionType::ExtInfo Info;
2098 auto &TaskPrivatesMapFnInfo =
2099 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2100 /*isVariadic=*/false);
2101 auto *TaskPrivatesMapTy =
2102 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2103 auto *TaskPrivatesMap = llvm::Function::Create(
2104 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2105 ".omp_task_privates_map.", &CGM.getModule());
2106 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskPrivatesMapFnInfo,
2107 TaskPrivatesMap);
2108 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
2109 CodeGenFunction CGF(CGM);
2110 CGF.disableDebugInfo();
2111 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2112 TaskPrivatesMapFnInfo, Args);
2113
2114 // *privi = &.privates.privi;
John McCall7f416cc2015-09-08 08:05:57 +00002115 auto *TaskPrivatesArgAddr = CGF.Builder.CreateLoad(
2116 CGF.GetAddrOfLocalVar(&TaskPrivatesArg));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002117 LValue Base =
2118 CGF.MakeNaturalAlignAddrLValue(TaskPrivatesArgAddr, PrivatesQTy);
2119 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2120 Counter = 0;
2121 for (auto *Field : PrivatesQTyRD->fields()) {
2122 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2123 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00002124 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002125 auto RefLoadRVal = CGF.EmitLoadOfLValue(RefLVal, Loc);
2126 CGF.EmitStoreOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002127 FieldLVal.getPointer(),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002128 CGF.MakeNaturalAlignAddrLValue(RefLoadRVal.getScalarVal(),
2129 RefLVal.getType()->getPointeeType()));
2130 ++Counter;
2131 }
2132 CGF.FinishFunction();
2133 return TaskPrivatesMap;
2134}
2135
Benjamin Kramer9b819032015-09-02 15:31:05 +00002136static llvm::Value *getTypeSize(CodeGenFunction &CGF, QualType Ty) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002137 auto &C = CGF.getContext();
2138 llvm::Value *Size;
2139 auto SizeInChars = C.getTypeSizeInChars(Ty);
2140 if (SizeInChars.isZero()) {
2141 // getTypeSizeInChars() returns 0 for a VLA.
2142 Size = nullptr;
2143 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
2144 llvm::Value *ArraySize;
2145 std::tie(ArraySize, Ty) = CGF.getVLASize(VAT);
2146 Size = Size ? CGF.Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
2147 }
2148 SizeInChars = C.getTypeSizeInChars(Ty);
2149 assert(!SizeInChars.isZero());
2150 Size = CGF.Builder.CreateNUWMul(
2151 Size, llvm::ConstantInt::get(CGF.SizeTy, SizeInChars.getQuantity()));
2152 } else
2153 Size = llvm::ConstantInt::get(CGF.SizeTy, SizeInChars.getQuantity());
2154 return Size;
2155}
2156
Alexey Bataev9e034042015-05-05 04:05:12 +00002157static int array_pod_sort_comparator(const PrivateDataTy *P1,
2158 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002159 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2160}
2161
2162void CGOpenMPRuntime::emitTaskCall(
2163 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
2164 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00002165 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002166 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
2167 ArrayRef<const Expr *> PrivateCopies,
2168 ArrayRef<const Expr *> FirstprivateVars,
2169 ArrayRef<const Expr *> FirstprivateCopies,
2170 ArrayRef<const Expr *> FirstprivateInits,
2171 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002172 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00002173 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002174 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00002175 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002176 for (auto *E : PrivateVars) {
2177 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2178 Privates.push_back(std::make_pair(
2179 C.getTypeAlignInChars(VD->getType()),
Alexey Bataev9e034042015-05-05 04:05:12 +00002180 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2181 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002182 ++I;
2183 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002184 I = FirstprivateCopies.begin();
2185 auto IElemInitRef = FirstprivateInits.begin();
2186 for (auto *E : FirstprivateVars) {
2187 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2188 Privates.push_back(std::make_pair(
2189 C.getTypeAlignInChars(VD->getType()),
2190 PrivateHelpersTy(
2191 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2192 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
2193 ++I, ++IElemInitRef;
2194 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002195 llvm::array_pod_sort(Privates.begin(), Privates.end(),
2196 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002197 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2198 // Build type kmp_routine_entry_t (if not built yet).
2199 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002200 // Build type kmp_task_t (if not built yet).
2201 if (KmpTaskTQTy.isNull()) {
2202 KmpTaskTQTy = C.getRecordType(
2203 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2204 }
2205 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002206 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002207 auto *KmpTaskTWithPrivatesQTyRD =
2208 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2209 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2210 QualType KmpTaskTWithPrivatesPtrQTy =
2211 C.getPointerType(KmpTaskTWithPrivatesQTy);
2212 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2213 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
2214 auto KmpTaskTWithPrivatesTySize =
2215 CGM.getSize(C.getTypeSizeInChars(KmpTaskTWithPrivatesQTy));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002216 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2217
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002218 // Emit initial values for private copies (if any).
2219 llvm::Value *TaskPrivatesMap = nullptr;
2220 auto *TaskPrivatesMapTy =
2221 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2222 3)
2223 ->getType();
2224 if (!Privates.empty()) {
2225 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2226 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2227 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2228 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2229 TaskPrivatesMap, TaskPrivatesMapTy);
2230 } else {
2231 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2232 cast<llvm::PointerType>(TaskPrivatesMapTy));
2233 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002234 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2235 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002236 auto *TaskEntry = emitProxyTaskFunction(
2237 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002238 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002239
2240 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2241 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2242 // kmp_routine_entry_t *task_entry);
2243 // Task flags. Format is taken from
2244 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2245 // description of kmp_tasking_flags struct.
2246 const unsigned TiedFlag = 0x1;
2247 const unsigned FinalFlag = 0x2;
2248 unsigned Flags = Tied ? TiedFlag : 0;
2249 auto *TaskFlags =
2250 Final.getPointer()
2251 ? CGF.Builder.CreateSelect(Final.getPointer(),
2252 CGF.Builder.getInt32(FinalFlag),
2253 CGF.Builder.getInt32(/*C=*/0))
2254 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2255 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
2256 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002257 llvm::Value *AllocArgs[] = {
2258 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), TaskFlags,
2259 KmpTaskTWithPrivatesTySize, CGM.getSize(SharedsSize),
2260 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskEntry,
2261 KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002262 auto *NewTask = CGF.EmitRuntimeCall(
2263 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002264 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2265 NewTask, KmpTaskTWithPrivatesPtrTy);
2266 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2267 KmpTaskTWithPrivatesQTy);
2268 LValue TDBase =
2269 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002270 // Fill the data in the resulting kmp_task_t record.
2271 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00002272 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002273 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002274 KmpTaskSharedsPtr = Address(CGF.EmitLoadOfScalar(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002275 CGF.EmitLValueForField(
2276 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)),
John McCall7f416cc2015-09-08 08:05:57 +00002277 Loc), CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002278 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002279 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002280 // Emit initial values for private copies (if any).
2281 bool NeedsCleanup = false;
2282 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002283 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2284 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002285 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002286 LValue SharedsBase;
2287 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002288 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002289 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2290 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2291 SharedsTy);
2292 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002293 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2294 cast<CapturedStmt>(*D.getAssociatedStmt()));
2295 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002296 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002297 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002298 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002299 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002300 if (auto *Elem = Pair.second.PrivateElemInit) {
2301 auto *OriginalVD = Pair.second.Original;
2302 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2303 auto SharedRefLValue =
2304 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002305 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002306 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002307 // Initialize firstprivate array.
2308 if (!isa<CXXConstructExpr>(Init) ||
2309 CGF.isTrivialInitializer(Init)) {
2310 // Perform simple memcpy.
2311 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002312 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002313 } else {
2314 // Initialize firstprivate array using element-by-element
2315 // intialization.
2316 CGF.EmitOMPAggregateAssign(
2317 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002318 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00002319 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002320 // Clean up any temporaries needed by the initialization.
2321 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002322 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002323 return SrcElement;
2324 });
2325 (void)InitScope.Privatize();
2326 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00002327 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
2328 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002329 CGF.EmitAnyExprToMem(Init, DestElement,
2330 Init->getType().getQualifiers(),
2331 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002332 });
2333 }
2334 } else {
2335 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002336 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002337 return SharedRefLValue.getAddress();
2338 });
2339 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00002340 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002341 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2342 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002343 }
2344 } else {
2345 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2346 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002347 }
2348 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002349 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002350 }
2351 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002352 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002353 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002354 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2355 KmpTaskTWithPrivatesPtrQTy,
2356 KmpTaskTWithPrivatesQTy)
2357 : llvm::ConstantPointerNull::get(
2358 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2359 LValue Destructor = CGF.EmitLValueForField(
2360 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2361 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2362 DestructorFn, KmpRoutineEntryPtrTy),
2363 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002364
2365 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00002366 Address DependenciesArray = Address::invalid();
2367 unsigned NumDependencies = Dependences.size();
2368 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002369 // Dependence kind for RTL.
2370 enum RTLDependenceKindTy { DepIn = 1, DepOut = 2, DepInOut = 3 };
2371 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
2372 RecordDecl *KmpDependInfoRD;
2373 QualType FlagsTy = C.getIntTypeForBitwidth(
2374 C.toBits(C.getTypeSizeInChars(C.BoolTy)), /*Signed=*/false);
2375 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
2376 if (KmpDependInfoTy.isNull()) {
2377 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
2378 KmpDependInfoRD->startDefinition();
2379 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
2380 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
2381 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
2382 KmpDependInfoRD->completeDefinition();
2383 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
2384 } else {
2385 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
2386 }
John McCall7f416cc2015-09-08 08:05:57 +00002387 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002388 // Define type kmp_depend_info[<Dependences.size()>];
2389 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00002390 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002391 ArrayType::Normal, /*IndexTypeQuals=*/0);
2392 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00002393 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
2394 for (unsigned i = 0; i < NumDependencies; ++i) {
2395 const Expr *E = Dependences[i].second;
2396 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002397 llvm::Value *Size;
2398 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002399 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
2400 LValue UpAddrLVal =
2401 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
2402 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00002403 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002404 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00002405 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002406 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
2407 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
John McCall7f416cc2015-09-08 08:05:57 +00002408 } else {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002409 Size = getTypeSize(CGF, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002410 }
2411 auto Base = CGF.MakeAddrLValue(
2412 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002413 KmpDependInfoTy);
2414 // deps[i].base_addr = &<Dependences[i].second>;
2415 auto BaseAddrLVal = CGF.EmitLValueForField(
2416 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00002417 CGF.EmitStoreOfScalar(
2418 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
2419 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002420 // deps[i].len = sizeof(<Dependences[i].second>);
2421 auto LenLVal = CGF.EmitLValueForField(
2422 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
2423 CGF.EmitStoreOfScalar(Size, LenLVal);
2424 // deps[i].flags = <Dependences[i].first>;
2425 RTLDependenceKindTy DepKind;
2426 switch (Dependences[i].first) {
2427 case OMPC_DEPEND_in:
2428 DepKind = DepIn;
2429 break;
2430 case OMPC_DEPEND_out:
2431 DepKind = DepOut;
2432 break;
2433 case OMPC_DEPEND_inout:
2434 DepKind = DepInOut;
2435 break;
2436 case OMPC_DEPEND_unknown:
2437 llvm_unreachable("Unknown task dependence type");
2438 }
2439 auto FlagsLVal = CGF.EmitLValueForField(
2440 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
2441 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
2442 FlagsLVal);
2443 }
John McCall7f416cc2015-09-08 08:05:57 +00002444 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2445 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002446 CGF.VoidPtrTy);
2447 }
2448
Alexey Bataev62b63b12015-03-10 07:28:44 +00002449 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
2450 // libcall.
2451 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
2452 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002453 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2454 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2455 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
2456 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00002457 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002458 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002459 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
2460 llvm::Value *DepTaskArgs[7];
2461 if (NumDependencies) {
2462 DepTaskArgs[0] = UpLoc;
2463 DepTaskArgs[1] = ThreadID;
2464 DepTaskArgs[2] = NewTask;
2465 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
2466 DepTaskArgs[4] = DependenciesArray.getPointer();
2467 DepTaskArgs[5] = CGF.Builder.getInt32(0);
2468 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2469 }
2470 auto &&ThenCodeGen = [this, NumDependencies,
2471 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
2472 // TODO: add check for untied tasks.
2473 if (NumDependencies) {
2474 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
2475 DepTaskArgs);
2476 } else {
2477 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
2478 TaskArgs);
2479 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002480 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002481 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
2482 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00002483
2484 llvm::Value *DepWaitTaskArgs[6];
2485 if (NumDependencies) {
2486 DepWaitTaskArgs[0] = UpLoc;
2487 DepWaitTaskArgs[1] = ThreadID;
2488 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
2489 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
2490 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
2491 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2492 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002493 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00002494 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002495 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
2496 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2497 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
2498 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
2499 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00002500 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002501 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
2502 DepWaitTaskArgs);
2503 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
2504 // kmp_task_t *new_task);
2505 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
2506 TaskArgs);
2507 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
2508 // kmp_task_t *new_task);
2509 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
2510 NormalAndEHCleanup,
2511 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
2512 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002513
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002514 // Call proxy_task_entry(gtid, new_task);
2515 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
2516 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
2517 };
John McCall7f416cc2015-09-08 08:05:57 +00002518
Alexey Bataev1d677132015-04-22 13:57:31 +00002519 if (IfCond) {
2520 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
2521 } else {
2522 CodeGenFunction::RunCleanupsScope Scope(CGF);
2523 ThenCodeGen(CGF);
2524 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002525}
2526
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002527static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
2528 llvm::Type *ArgsType,
2529 ArrayRef<const Expr *> LHSExprs,
2530 ArrayRef<const Expr *> RHSExprs,
2531 ArrayRef<const Expr *> ReductionOps) {
2532 auto &C = CGM.getContext();
2533
2534 // void reduction_func(void *LHSArg, void *RHSArg);
2535 FunctionArgList Args;
2536 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2537 C.VoidPtrTy);
2538 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2539 C.VoidPtrTy);
2540 Args.push_back(&LHSArg);
2541 Args.push_back(&RHSArg);
2542 FunctionType::ExtInfo EI;
2543 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2544 C.VoidTy, Args, EI, /*isVariadic=*/false);
2545 auto *Fn = llvm::Function::Create(
2546 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2547 ".omp.reduction.reduction_func", &CGM.getModule());
2548 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
2549 CodeGenFunction CGF(CGM);
2550 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2551
2552 // Dst = (void*[n])(LHSArg);
2553 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002554 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2555 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2556 ArgsType), CGF.getPointerAlign());
2557 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2558 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2559 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002560
2561 // ...
2562 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
2563 // ...
2564 CodeGenFunction::OMPPrivateScope Scope(CGF);
2565 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002566 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
2567 Scope.addPrivate(RHSVar, [&]() -> Address {
2568 return emitAddrOfVarFromArray(CGF, RHS, I, RHSVar);
2569 });
2570 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
2571 Scope.addPrivate(LHSVar, [&]() -> Address {
2572 return emitAddrOfVarFromArray(CGF, LHS, I, LHSVar);
2573 });
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002574 }
2575 Scope.Privatize();
2576 for (auto *E : ReductionOps) {
2577 CGF.EmitIgnoredExpr(E);
2578 }
2579 Scope.ForceCleanup();
2580 CGF.FinishFunction();
2581 return Fn;
2582}
2583
2584void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
2585 ArrayRef<const Expr *> LHSExprs,
2586 ArrayRef<const Expr *> RHSExprs,
2587 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002588 bool WithNowait, bool SimpleReduction) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002589 // Next code should be emitted for reduction:
2590 //
2591 // static kmp_critical_name lock = { 0 };
2592 //
2593 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
2594 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
2595 // ...
2596 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
2597 // *(Type<n>-1*)rhs[<n>-1]);
2598 // }
2599 //
2600 // ...
2601 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
2602 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2603 // RedList, reduce_func, &<lock>)) {
2604 // case 1:
2605 // ...
2606 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2607 // ...
2608 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2609 // break;
2610 // case 2:
2611 // ...
2612 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2613 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00002614 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002615 // break;
2616 // default:;
2617 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002618 //
2619 // if SimpleReduction is true, only the next code is generated:
2620 // ...
2621 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2622 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002623
2624 auto &C = CGM.getContext();
2625
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002626 if (SimpleReduction) {
2627 CodeGenFunction::RunCleanupsScope Scope(CGF);
2628 for (auto *E : ReductionOps) {
2629 CGF.EmitIgnoredExpr(E);
2630 }
2631 return;
2632 }
2633
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002634 // 1. Build a list of reduction variables.
2635 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2636 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
2637 QualType ReductionArrayTy =
2638 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2639 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00002640 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002641 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2642 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002643 Address Elem =
2644 CGF.Builder.CreateConstArrayGEP(ReductionList, I, CGF.getPointerSize());
2645 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002646 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002647 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
2648 Elem);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002649 }
2650
2651 // 2. Emit reduce_func().
2652 auto *ReductionFn = emitReductionFunction(
2653 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
2654 RHSExprs, ReductionOps);
2655
2656 // 3. Create static kmp_critical_name lock = { 0 };
2657 auto *Lock = getCriticalRegionLock(".reduction");
2658
2659 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2660 // RedList, reduce_func, &<lock>);
2661 auto *IdentTLoc = emitUpdateLocation(
2662 CGF, Loc,
2663 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
2664 auto *ThreadId = getThreadID(CGF, Loc);
2665 auto *ReductionArrayTySize = llvm::ConstantInt::get(
2666 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002667 auto *RL =
2668 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
2669 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002670 llvm::Value *Args[] = {
2671 IdentTLoc, // ident_t *<loc>
2672 ThreadId, // i32 <gtid>
2673 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
2674 ReductionArrayTySize, // size_type sizeof(RedList)
2675 RL, // void *RedList
2676 ReductionFn, // void (*) (void *, void *) <reduce_func>
2677 Lock // kmp_critical_name *&<lock>
2678 };
2679 auto Res = CGF.EmitRuntimeCall(
2680 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
2681 : OMPRTL__kmpc_reduce),
2682 Args);
2683
2684 // 5. Build switch(res)
2685 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2686 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
2687
2688 // 6. Build case 1:
2689 // ...
2690 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2691 // ...
2692 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2693 // break;
2694 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2695 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2696 CGF.EmitBlock(Case1BB);
2697
2698 {
2699 CodeGenFunction::RunCleanupsScope Scope(CGF);
2700 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2701 llvm::Value *EndArgs[] = {
2702 IdentTLoc, // ident_t *<loc>
2703 ThreadId, // i32 <gtid>
2704 Lock // kmp_critical_name *&<lock>
2705 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002706 CGF.EHStack
2707 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2708 NormalAndEHCleanup,
2709 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
2710 : OMPRTL__kmpc_end_reduce),
2711 llvm::makeArrayRef(EndArgs));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002712 for (auto *E : ReductionOps) {
2713 CGF.EmitIgnoredExpr(E);
2714 }
2715 }
2716
2717 CGF.EmitBranch(DefaultBB);
2718
2719 // 7. Build case 2:
2720 // ...
2721 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2722 // ...
2723 // break;
2724 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
2725 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
2726 CGF.EmitBlock(Case2BB);
2727
2728 {
2729 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00002730 if (!WithNowait) {
2731 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
2732 llvm::Value *EndArgs[] = {
2733 IdentTLoc, // ident_t *<loc>
2734 ThreadId, // i32 <gtid>
2735 Lock // kmp_critical_name *&<lock>
2736 };
2737 CGF.EHStack
2738 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2739 NormalAndEHCleanup,
2740 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
2741 llvm::makeArrayRef(EndArgs));
2742 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002743 auto I = LHSExprs.begin();
2744 for (auto *E : ReductionOps) {
2745 const Expr *XExpr = nullptr;
2746 const Expr *EExpr = nullptr;
2747 const Expr *UpExpr = nullptr;
2748 BinaryOperatorKind BO = BO_Comma;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002749 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2750 if (BO->getOpcode() == BO_Assign) {
2751 XExpr = BO->getLHS();
2752 UpExpr = BO->getRHS();
2753 }
2754 }
Alexey Bataev69a47792015-05-07 03:54:03 +00002755 // Try to emit update expression as a simple atomic.
2756 auto *RHSExpr = UpExpr;
2757 if (RHSExpr) {
2758 // Analyze RHS part of the whole expression.
2759 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
2760 RHSExpr->IgnoreParenImpCasts())) {
2761 // If this is a conditional operator, analyze its condition for
2762 // min/max reduction operator.
2763 RHSExpr = ACO->getCond();
2764 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002765 if (auto *BORHS =
Alexey Bataev69a47792015-05-07 03:54:03 +00002766 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002767 EExpr = BORHS->getRHS();
2768 BO = BORHS->getOpcode();
2769 }
2770 }
2771 if (XExpr) {
2772 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2773 LValue X = CGF.EmitLValue(XExpr);
2774 RValue E;
2775 if (EExpr)
2776 E = CGF.EmitAnyExpr(EExpr);
2777 CGF.EmitOMPAtomicSimpleUpdateExpr(
2778 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
2779 [&CGF, UpExpr, VD](RValue XRValue) {
2780 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
2781 PrivateScope.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +00002782 VD, [&CGF, VD, XRValue]() -> Address {
2783 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002784 CGF.EmitStoreThroughLValue(
2785 XRValue,
John McCall7f416cc2015-09-08 08:05:57 +00002786 CGF.MakeAddrLValue(LHSTemp, VD->getType()));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002787 return LHSTemp;
2788 });
2789 (void)PrivateScope.Privatize();
2790 return CGF.EmitAnyExpr(UpExpr);
2791 });
2792 } else {
2793 // Emit as a critical region.
2794 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
2795 CGF.EmitIgnoredExpr(E);
2796 }, Loc);
2797 }
2798 ++I;
2799 }
2800 }
2801
2802 CGF.EmitBranch(DefaultBB);
2803 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2804}
2805
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002806void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
2807 SourceLocation Loc) {
2808 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2809 // global_tid);
2810 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2811 // Ignore return result until untied tasks are supported.
2812 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
2813}
2814
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002815void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002816 OpenMPDirectiveKind InnerKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002817 const RegionCodeGenTy &CodeGen) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002818 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002819 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002820}
2821
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002822namespace {
2823enum RTCancelKind {
2824 CancelNoreq = 0,
2825 CancelParallel = 1,
2826 CancelLoop = 2,
2827 CancelSections = 3,
2828 CancelTaskgroup = 4
2829};
2830}
2831
2832static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
2833 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00002834 if (CancelRegion == OMPD_parallel)
2835 CancelKind = CancelParallel;
2836 else if (CancelRegion == OMPD_for)
2837 CancelKind = CancelLoop;
2838 else if (CancelRegion == OMPD_sections)
2839 CancelKind = CancelSections;
2840 else {
2841 assert(CancelRegion == OMPD_taskgroup);
2842 CancelKind = CancelTaskgroup;
2843 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002844 return CancelKind;
2845}
2846
2847void CGOpenMPRuntime::emitCancellationPointCall(
2848 CodeGenFunction &CGF, SourceLocation Loc,
2849 OpenMPDirectiveKind CancelRegion) {
2850 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2851 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002852 if (auto *OMPRegionInfo =
2853 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2854 auto CancelDest =
2855 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2856 if (CancelDest.isValid()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002857 llvm::Value *Args[] = {
2858 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2859 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002860 // Ignore return result until untied tasks are supported.
2861 auto *Result = CGF.EmitRuntimeCall(
2862 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
2863 // if (__kmpc_cancellationpoint()) {
2864 // __kmpc_cancel_barrier();
2865 // exit from construct;
2866 // }
2867 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2868 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2869 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2870 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2871 CGF.EmitBlock(ExitBB);
2872 // __kmpc_cancel_barrier();
2873 emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
2874 // exit from construct;
2875 CGF.EmitBranchThroughCleanup(CancelDest);
2876 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2877 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002878 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002879}
2880
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002881void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
2882 OpenMPDirectiveKind CancelRegion) {
2883 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2884 // kmp_int32 cncl_kind);
2885 if (auto *OMPRegionInfo =
2886 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2887 auto CancelDest =
2888 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2889 if (CancelDest.isValid()) {
2890 llvm::Value *Args[] = {
2891 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2892 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
2893 // Ignore return result until untied tasks are supported.
2894 auto *Result =
2895 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
2896 // if (__kmpc_cancel()) {
2897 // __kmpc_cancel_barrier();
2898 // exit from construct;
2899 // }
2900 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2901 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2902 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2903 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2904 CGF.EmitBlock(ExitBB);
2905 // __kmpc_cancel_barrier();
2906 emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
2907 // exit from construct;
2908 CGF.EmitBranchThroughCleanup(CancelDest);
2909 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2910 }
2911 }
2912}
2913