blob: 5fe81c2443ca4ef178cbc91e0b8afb8b305a6d55 [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,
48 const RegionCodeGenTy &CodeGen)
49 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
50 CodeGen(CodeGen) {}
51
52 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
53 const RegionCodeGenTy &CodeGen)
54 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind),
55 CodeGen(CodeGen) {}
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 Bataev18095712014-10-10 12:19:54 +000070 static bool classof(const CGCapturedStmtInfo *Info) {
71 return Info->getKind() == CR_OpenMP;
72 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000073
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000074protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075 CGOpenMPRegionKind RegionKind;
76 const RegionCodeGenTy &CodeGen;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000077};
Alexey Bataev18095712014-10-10 12:19:54 +000078
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079/// \brief API for captured statement code generation in OpenMP constructs.
80class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
81public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000082 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
83 const RegionCodeGenTy &CodeGen)
84 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen),
85 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000086 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
87 }
88 /// \brief Get a variable or parameter for storing global thread id
89 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +000090 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091
Alexey Bataev18095712014-10-10 12:19:54 +000092 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +000093 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +000094
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095 static bool classof(const CGCapturedStmtInfo *Info) {
96 return CGOpenMPRegionInfo::classof(Info) &&
97 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
98 ParallelOutlinedRegion;
99 }
100
Alexey Bataev18095712014-10-10 12:19:54 +0000101private:
102 /// \brief A variable or parameter storing global thread id for OpenMP
103 /// constructs.
104 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000105};
106
Alexey Bataev62b63b12015-03-10 07:28:44 +0000107/// \brief API for captured statement code generation in OpenMP constructs.
108class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
109public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000110 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000111 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000112 const RegionCodeGenTy &CodeGen)
113 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen),
114 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000115 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
116 }
117 /// \brief Get a variable or parameter for storing global thread id
118 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000119 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000120
121 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000122 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000123
Alexey Bataev62b63b12015-03-10 07:28:44 +0000124 /// \brief Get the name of the capture helper.
125 StringRef getHelperName() const override { return ".omp_outlined."; }
126
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000127 static bool classof(const CGCapturedStmtInfo *Info) {
128 return CGOpenMPRegionInfo::classof(Info) &&
129 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
130 TaskOutlinedRegion;
131 }
132
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133private:
134 /// \brief A variable or parameter storing global thread id for OpenMP
135 /// constructs.
136 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000137};
138
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000139/// \brief API for inlined captured statement code generation in OpenMP
140/// constructs.
141class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
142public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000143 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
144 const RegionCodeGenTy &CodeGen)
145 : CGOpenMPRegionInfo(InlinedRegion, CodeGen), OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000146 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
147 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000148 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000149 if (OuterRegionInfo)
150 return OuterRegionInfo->getContextValue();
151 llvm_unreachable("No context value for inlined OpenMP region");
152 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000153 virtual void setContextValue(llvm::Value *V) override {
154 if (OuterRegionInfo) {
155 OuterRegionInfo->setContextValue(V);
156 return;
157 }
158 llvm_unreachable("No context value for inlined OpenMP region");
159 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000160 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000161 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000162 if (OuterRegionInfo)
163 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000164 // If there is no outer outlined region,no need to lookup in a list of
165 // captured variables, we can use the original one.
166 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000167 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000168 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000169 if (OuterRegionInfo)
170 return OuterRegionInfo->getThisFieldDecl();
171 return nullptr;
172 }
173 /// \brief Get a variable or parameter for storing global thread id
174 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000175 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000176 if (OuterRegionInfo)
177 return OuterRegionInfo->getThreadIDVariable();
178 return nullptr;
179 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000180
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000181 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000182 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000183 if (auto *OuterRegionInfo = getOldCSI())
184 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000185 llvm_unreachable("No helper name for inlined OpenMP construct");
186 }
187
188 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
189
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000190 static bool classof(const CGCapturedStmtInfo *Info) {
191 return CGOpenMPRegionInfo::classof(Info) &&
192 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
193 }
194
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000195private:
196 /// \brief CodeGen info about outer OpenMP region.
197 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
198 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000199};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000200
201/// \brief RAII for emitting code of OpenMP constructs.
202class InlinedOpenMPRegionRAII {
203 CodeGenFunction &CGF;
204
205public:
206 /// \brief Constructs region for combined constructs.
207 /// \param CodeGen Code generation sequence for combined directives. Includes
208 /// a list of functions used for code generation of implicitly inlined
209 /// regions.
210 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen)
211 : CGF(CGF) {
212 // Start emission for the construct.
213 CGF.CapturedStmtInfo =
214 new CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, CodeGen);
215 }
216 ~InlinedOpenMPRegionRAII() {
217 // Restore original CapturedStmtInfo only if we're done with code emission.
218 auto *OldCSI =
219 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
220 delete CGF.CapturedStmtInfo;
221 CGF.CapturedStmtInfo = OldCSI;
222 }
223};
224
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000225} // namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000226
227LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
228 return CGF.MakeNaturalAlignAddrLValue(
Alexey Bataev62b63b12015-03-10 07:28:44 +0000229 CGF.Builder.CreateAlignedLoad(
230 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
231 CGF.PointerAlignInBytes),
232 getThreadIDVariable()
233 ->getType()
234 ->castAs<PointerType>()
235 ->getPointeeType());
Alexey Bataev18095712014-10-10 12:19:54 +0000236}
237
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
239 // 1.2.2 OpenMP Language Terminology
240 // Structured block - An executable statement with a single entry at the
241 // top and a single exit at the bottom.
242 // The point of exit cannot be a branch out of the structured block.
243 // longjmp() and throw() must not violate the entry/exit criteria.
244 CGF.EHStack.pushTerminate();
245 {
246 CodeGenFunction::RunCleanupsScope Scope(CGF);
247 CodeGen(CGF);
248 }
249 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000250}
251
Alexey Bataev62b63b12015-03-10 07:28:44 +0000252LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
253 CodeGenFunction &CGF) {
254 return CGF.MakeNaturalAlignAddrLValue(
255 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
256 getThreadIDVariable()->getType());
257}
258
Alexey Bataev9959db52014-05-06 10:08:46 +0000259CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000260 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000261 IdentTy = llvm::StructType::create(
262 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
263 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000264 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000265 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000266 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
267 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000268 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000269 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000270}
271
Alexey Bataev91797552015-03-18 04:13:55 +0000272void CGOpenMPRuntime::clear() {
273 InternalVars.clear();
274}
275
Alexey Bataev9959db52014-05-06 10:08:46 +0000276llvm::Value *
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277CGOpenMPRuntime::emitParallelOutlinedFunction(const OMPExecutableDirective &D,
278 const VarDecl *ThreadIDVar,
279 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000280 assert(ThreadIDVar->getType()->isPointerType() &&
281 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000282 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
283 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000284 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataevd157d472015-06-24 03:35:38 +0000285 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev18095712014-10-10 12:19:54 +0000286 return CGF.GenerateCapturedStmtFunction(*CS);
287}
288
289llvm::Value *
Alexey Bataev62b63b12015-03-10 07:28:44 +0000290CGOpenMPRuntime::emitTaskOutlinedFunction(const OMPExecutableDirective &D,
291 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000292 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000293 assert(!ThreadIDVar->getType()->isPointerType() &&
294 "thread id variable must be of type kmp_int32 for tasks");
295 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
296 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000297 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataevd157d472015-06-24 03:35:38 +0000298 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000299 return CGF.GenerateCapturedStmtFunction(*CS);
300}
301
302llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000303CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000304 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000305 if (!Entry) {
306 if (!DefaultOpenMPPSource) {
307 // Initialize default location for psource field of ident_t structure of
308 // all ident_t objects. Format is ";file;function;line;column;;".
309 // Taken from
310 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
311 DefaultOpenMPPSource =
312 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
313 DefaultOpenMPPSource =
314 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
315 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000316 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
317 CGM.getModule(), IdentTy, /*isConstant*/ true,
318 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000319 DefaultOpenMPLocation->setUnnamedAddr(true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000320
321 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000322 llvm::Constant *Values[] = {Zero,
323 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
324 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000325 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
326 DefaultOpenMPLocation->setInitializer(Init);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000327 OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000328 return DefaultOpenMPLocation;
329 }
330 return Entry;
331}
332
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000333llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
334 SourceLocation Loc,
335 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000336 // If no debug info is generated - return global default location.
337 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
338 Loc.isInvalid())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000339 return getOrCreateDefaultLocation(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000340
341 assert(CGF.CurFn && "No function in current CodeGenFunction.");
342
Alexey Bataev9959db52014-05-06 10:08:46 +0000343 llvm::Value *LocValue = nullptr;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000344 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
345 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataev18095712014-10-10 12:19:54 +0000346 LocValue = I->second.DebugLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +0000347 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
348 // GetOpenMPThreadID was called before this routine.
349 if (LocValue == nullptr) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000350 // Generate "ident_t .kmpc_loc.addr;"
351 llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
Alexey Bataev9959db52014-05-06 10:08:46 +0000352 AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
Alexey Bataev18095712014-10-10 12:19:54 +0000353 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
354 Elem.second.DebugLoc = AI;
Alexey Bataev9959db52014-05-06 10:08:46 +0000355 LocValue = AI;
356
357 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
358 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000359 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataev9959db52014-05-06 10:08:46 +0000360 llvm::ConstantExpr::getSizeOf(IdentTy),
361 CGM.PointerAlignInBytes);
362 }
363
364 // char **psource = &.kmpc_loc_<flags>.addr.psource;
David Blaikie1ed728c2015-04-05 22:45:47 +0000365 auto *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(IdentTy, LocValue, 0,
366 IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000367
Alexey Bataevf002aca2014-05-30 05:48:40 +0000368 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
369 if (OMPDebugLoc == nullptr) {
370 SmallString<128> Buffer2;
371 llvm::raw_svector_ostream OS2(Buffer2);
372 // Build debug location
373 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
374 OS2 << ";" << PLoc.getFilename() << ";";
375 if (const FunctionDecl *FD =
376 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
377 OS2 << FD->getQualifiedNameAsString();
378 }
379 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
380 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
381 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000382 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000383 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000384 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
385
Alexey Bataev9959db52014-05-06 10:08:46 +0000386 return LocValue;
387}
388
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000389llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
390 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000391 assert(CGF.CurFn && "No function in current CodeGenFunction.");
392
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000393 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000394 // Check whether we've already cached a load of the thread id in this
395 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000396 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000397 if (I != OpenMPLocThreadIDMap.end()) {
398 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000399 if (ThreadID != nullptr)
400 return ThreadID;
401 }
402 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000403 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000404 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000405 // Check if this an outlined function with thread id passed as argument.
406 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000407 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
408 // If value loaded in entry block, cache it and use it everywhere in
409 // function.
410 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
411 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
412 Elem.second.ThreadID = ThreadID;
413 }
414 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000415 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000416 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000417
418 // This is not an outlined function region - need to call __kmpc_int32
419 // kmpc_global_thread_num(ident_t *loc).
420 // Generate thread id value and cache this value for use across the
421 // function.
422 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
423 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
424 ThreadID =
425 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
426 emitUpdateLocation(CGF, Loc));
427 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
428 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000429 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000430}
431
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000432void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000433 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000434 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
435 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000436}
437
438llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
439 return llvm::PointerType::getUnqual(IdentTy);
440}
441
442llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
443 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
444}
445
446llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000447CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000448 llvm::Constant *RTLFn = nullptr;
449 switch (Function) {
450 case OMPRTL__kmpc_fork_call: {
451 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
452 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000453 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
454 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000455 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000456 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000457 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
458 break;
459 }
460 case OMPRTL__kmpc_global_thread_num: {
461 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000462 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000463 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
466 break;
467 }
Alexey Bataev97720002014-11-11 04:05:39 +0000468 case OMPRTL__kmpc_threadprivate_cached: {
469 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
470 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
472 CGM.VoidPtrTy, CGM.SizeTy,
473 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
474 llvm::FunctionType *FnTy =
475 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
476 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
477 break;
478 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000479 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000480 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
481 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000482 llvm::Type *TypeParams[] = {
483 getIdentTyPointerTy(), CGM.Int32Ty,
484 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
485 llvm::FunctionType *FnTy =
486 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
487 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
488 break;
489 }
Alexey Bataev97720002014-11-11 04:05:39 +0000490 case OMPRTL__kmpc_threadprivate_register: {
491 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
492 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
493 // typedef void *(*kmpc_ctor)(void *);
494 auto KmpcCtorTy =
495 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
496 /*isVarArg*/ false)->getPointerTo();
497 // typedef void *(*kmpc_cctor)(void *, void *);
498 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
499 auto KmpcCopyCtorTy =
500 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
501 /*isVarArg*/ false)->getPointerTo();
502 // typedef void (*kmpc_dtor)(void *);
503 auto KmpcDtorTy =
504 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
505 ->getPointerTo();
506 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
507 KmpcCopyCtorTy, KmpcDtorTy};
508 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
509 /*isVarArg*/ false);
510 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
511 break;
512 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000513 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000514 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
515 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000516 llvm::Type *TypeParams[] = {
517 getIdentTyPointerTy(), CGM.Int32Ty,
518 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
519 llvm::FunctionType *FnTy =
520 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
521 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
522 break;
523 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000524 case OMPRTL__kmpc_cancel_barrier: {
525 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
526 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000527 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
528 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000529 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
530 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000531 break;
532 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000533 case OMPRTL__kmpc_for_static_fini: {
534 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
535 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
536 llvm::FunctionType *FnTy =
537 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
538 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
539 break;
540 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000541 case OMPRTL__kmpc_push_num_threads: {
542 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
543 // kmp_int32 num_threads)
544 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
545 CGM.Int32Ty};
546 llvm::FunctionType *FnTy =
547 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
548 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
549 break;
550 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000551 case OMPRTL__kmpc_serialized_parallel: {
552 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
553 // global_tid);
554 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
555 llvm::FunctionType *FnTy =
556 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
557 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
558 break;
559 }
560 case OMPRTL__kmpc_end_serialized_parallel: {
561 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
562 // global_tid);
563 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
564 llvm::FunctionType *FnTy =
565 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
566 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
567 break;
568 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000569 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000570 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000571 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
572 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000573 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
575 break;
576 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000577 case OMPRTL__kmpc_master: {
578 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
580 llvm::FunctionType *FnTy =
581 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
582 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
583 break;
584 }
585 case OMPRTL__kmpc_end_master: {
586 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 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, /*Name=*/"__kmpc_end_master");
591 break;
592 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000593 case OMPRTL__kmpc_omp_taskyield: {
594 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
595 // int end_part);
596 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
597 llvm::FunctionType *FnTy =
598 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
599 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
600 break;
601 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000602 case OMPRTL__kmpc_single: {
603 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
604 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
605 llvm::FunctionType *FnTy =
606 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
607 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
608 break;
609 }
610 case OMPRTL__kmpc_end_single: {
611 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
612 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
613 llvm::FunctionType *FnTy =
614 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
615 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
616 break;
617 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000618 case OMPRTL__kmpc_omp_task_alloc: {
619 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
620 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
621 // kmp_routine_entry_t *task_entry);
622 assert(KmpRoutineEntryPtrTy != nullptr &&
623 "Type kmp_routine_entry_t must be created.");
624 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
625 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
626 // Return void * and then cast to particular kmp_task_t type.
627 llvm::FunctionType *FnTy =
628 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
629 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
630 break;
631 }
632 case OMPRTL__kmpc_omp_task: {
633 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
634 // *new_task);
635 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
636 CGM.VoidPtrTy};
637 llvm::FunctionType *FnTy =
638 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
639 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
640 break;
641 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000642 case OMPRTL__kmpc_copyprivate: {
643 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +0000644 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +0000645 // kmp_int32 didit);
646 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
647 auto *CpyFnTy =
648 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +0000649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +0000650 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
651 CGM.Int32Ty};
652 llvm::FunctionType *FnTy =
653 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
654 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
655 break;
656 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000657 case OMPRTL__kmpc_reduce: {
658 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
659 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
660 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
661 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
662 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
663 /*isVarArg=*/false);
664 llvm::Type *TypeParams[] = {
665 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
666 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
667 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
668 llvm::FunctionType *FnTy =
669 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
670 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
671 break;
672 }
673 case OMPRTL__kmpc_reduce_nowait: {
674 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
675 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
676 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
677 // *lck);
678 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
679 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
680 /*isVarArg=*/false);
681 llvm::Type *TypeParams[] = {
682 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
683 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
684 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
685 llvm::FunctionType *FnTy =
686 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
687 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
688 break;
689 }
690 case OMPRTL__kmpc_end_reduce: {
691 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
692 // kmp_critical_name *lck);
693 llvm::Type *TypeParams[] = {
694 getIdentTyPointerTy(), CGM.Int32Ty,
695 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
696 llvm::FunctionType *FnTy =
697 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
698 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
699 break;
700 }
701 case OMPRTL__kmpc_end_reduce_nowait: {
702 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
703 // kmp_critical_name *lck);
704 llvm::Type *TypeParams[] = {
705 getIdentTyPointerTy(), CGM.Int32Ty,
706 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
707 llvm::FunctionType *FnTy =
708 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
709 RTLFn =
710 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
711 break;
712 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000713 case OMPRTL__kmpc_omp_task_begin_if0: {
714 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
715 // *new_task);
716 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
717 CGM.VoidPtrTy};
718 llvm::FunctionType *FnTy =
719 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
720 RTLFn =
721 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
722 break;
723 }
724 case OMPRTL__kmpc_omp_task_complete_if0: {
725 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
726 // *new_task);
727 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
728 CGM.VoidPtrTy};
729 llvm::FunctionType *FnTy =
730 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
731 RTLFn = CGM.CreateRuntimeFunction(FnTy,
732 /*Name=*/"__kmpc_omp_task_complete_if0");
733 break;
734 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000735 case OMPRTL__kmpc_ordered: {
736 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
737 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
738 llvm::FunctionType *FnTy =
739 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
740 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
741 break;
742 }
743 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000744 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000745 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
746 llvm::FunctionType *FnTy =
747 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
748 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
749 break;
750 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +0000751 case OMPRTL__kmpc_omp_taskwait: {
752 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
753 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
754 llvm::FunctionType *FnTy =
755 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
756 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
757 break;
758 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000759 case OMPRTL__kmpc_taskgroup: {
760 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
761 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
762 llvm::FunctionType *FnTy =
763 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
764 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
765 break;
766 }
767 case OMPRTL__kmpc_end_taskgroup: {
768 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
769 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
770 llvm::FunctionType *FnTy =
771 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
772 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
773 break;
774 }
Alexey Bataev7f210c62015-06-18 13:40:03 +0000775 case OMPRTL__kmpc_push_proc_bind: {
776 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
777 // int proc_bind)
778 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
779 llvm::FunctionType *FnTy =
780 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
781 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
782 break;
783 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +0000784 case OMPRTL__kmpc_omp_task_with_deps: {
785 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
786 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
787 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
788 llvm::Type *TypeParams[] = {
789 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
790 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
791 llvm::FunctionType *FnTy =
792 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
793 RTLFn =
794 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
795 break;
796 }
797 case OMPRTL__kmpc_omp_wait_deps: {
798 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
799 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
800 // kmp_depend_info_t *noalias_dep_list);
801 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
802 CGM.Int32Ty, CGM.VoidPtrTy,
803 CGM.Int32Ty, CGM.VoidPtrTy};
804 llvm::FunctionType *FnTy =
805 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
806 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
807 break;
808 }
Alexey Bataev0f34da12015-07-02 04:17:07 +0000809 case OMPRTL__kmpc_cancellationpoint: {
810 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
811 // global_tid, kmp_int32 cncl_kind)
812 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
813 llvm::FunctionType *FnTy =
814 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
815 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
816 break;
817 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000818 }
819 return RTLFn;
820}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000821
Alexander Musman21212e42015-03-13 10:38:23 +0000822llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
823 bool IVSigned) {
824 assert((IVSize == 32 || IVSize == 64) &&
825 "IV size is not compatible with the omp runtime");
826 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
827 : "__kmpc_for_static_init_4u")
828 : (IVSigned ? "__kmpc_for_static_init_8"
829 : "__kmpc_for_static_init_8u");
830 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
831 auto PtrTy = llvm::PointerType::getUnqual(ITy);
832 llvm::Type *TypeParams[] = {
833 getIdentTyPointerTy(), // loc
834 CGM.Int32Ty, // tid
835 CGM.Int32Ty, // schedtype
836 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
837 PtrTy, // p_lower
838 PtrTy, // p_upper
839 PtrTy, // p_stride
840 ITy, // incr
841 ITy // chunk
842 };
843 llvm::FunctionType *FnTy =
844 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
845 return CGM.CreateRuntimeFunction(FnTy, Name);
846}
847
Alexander Musman92bdaab2015-03-12 13:37:50 +0000848llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
849 bool IVSigned) {
850 assert((IVSize == 32 || IVSize == 64) &&
851 "IV size is not compatible with the omp runtime");
852 auto Name =
853 IVSize == 32
854 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
855 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
856 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
857 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
858 CGM.Int32Ty, // tid
859 CGM.Int32Ty, // schedtype
860 ITy, // lower
861 ITy, // upper
862 ITy, // stride
863 ITy // chunk
864 };
865 llvm::FunctionType *FnTy =
866 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
867 return CGM.CreateRuntimeFunction(FnTy, Name);
868}
869
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000870llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
871 bool IVSigned) {
872 assert((IVSize == 32 || IVSize == 64) &&
873 "IV size is not compatible with the omp runtime");
874 auto Name =
875 IVSize == 32
876 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
877 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
878 llvm::Type *TypeParams[] = {
879 getIdentTyPointerTy(), // loc
880 CGM.Int32Ty, // tid
881 };
882 llvm::FunctionType *FnTy =
883 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
884 return CGM.CreateRuntimeFunction(FnTy, Name);
885}
886
Alexander Musman92bdaab2015-03-12 13:37:50 +0000887llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
888 bool IVSigned) {
889 assert((IVSize == 32 || IVSize == 64) &&
890 "IV size is not compatible with the omp runtime");
891 auto Name =
892 IVSize == 32
893 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
894 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
895 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
896 auto PtrTy = llvm::PointerType::getUnqual(ITy);
897 llvm::Type *TypeParams[] = {
898 getIdentTyPointerTy(), // loc
899 CGM.Int32Ty, // tid
900 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
901 PtrTy, // p_lower
902 PtrTy, // p_upper
903 PtrTy // p_stride
904 };
905 llvm::FunctionType *FnTy =
906 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
907 return CGM.CreateRuntimeFunction(FnTy, Name);
908}
909
Alexey Bataev97720002014-11-11 04:05:39 +0000910llvm::Constant *
911CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
912 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000913 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000914 Twine(CGM.getMangledName(VD)) + ".cache.");
915}
916
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000917llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
918 const VarDecl *VD,
919 llvm::Value *VDAddr,
920 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000921 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000922 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000923 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
924 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
925 getOrCreateThreadPrivateCache(VD)};
926 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000927 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000928}
929
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000930void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000931 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
932 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
933 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
934 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000935 auto OMPLoc = emitUpdateLocation(CGF, Loc);
936 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000937 OMPLoc);
938 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
939 // to register constructor/destructor for variable.
940 llvm::Value *Args[] = {OMPLoc,
941 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
942 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000943 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000944 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000945}
946
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000947llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000948 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
949 bool PerformInit, CodeGenFunction *CGF) {
950 VD = VD->getDefinition(CGM.getContext());
951 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
952 ThreadPrivateWithDefinition.insert(VD);
953 QualType ASTTy = VD->getType();
954
955 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
956 auto Init = VD->getAnyInitializer();
957 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
958 // Generate function that re-emits the declaration's initializer into the
959 // threadprivate copy of the variable VD
960 CodeGenFunction CtorCGF(CGM);
961 FunctionArgList Args;
962 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
963 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
964 Args.push_back(&Dst);
965
966 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
967 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
968 /*isVariadic=*/false);
969 auto FTy = CGM.getTypes().GetFunctionType(FI);
970 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
971 FTy, ".__kmpc_global_ctor_.", Loc);
972 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
973 Args, SourceLocation());
974 auto ArgVal = CtorCGF.EmitLoadOfScalar(
975 CtorCGF.GetAddrOfLocalVar(&Dst),
976 /*Volatile=*/false, CGM.PointerAlignInBytes,
977 CGM.getContext().VoidPtrTy, Dst.getLocation());
978 auto Arg = CtorCGF.Builder.CreatePointerCast(
979 ArgVal,
980 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
981 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
982 /*IsInitializer=*/true);
983 ArgVal = CtorCGF.EmitLoadOfScalar(
984 CtorCGF.GetAddrOfLocalVar(&Dst),
985 /*Volatile=*/false, CGM.PointerAlignInBytes,
986 CGM.getContext().VoidPtrTy, Dst.getLocation());
987 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
988 CtorCGF.FinishFunction();
989 Ctor = Fn;
990 }
991 if (VD->getType().isDestructedType() != QualType::DK_none) {
992 // Generate function that emits destructor call for the threadprivate copy
993 // of the variable VD
994 CodeGenFunction DtorCGF(CGM);
995 FunctionArgList Args;
996 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
997 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
998 Args.push_back(&Dst);
999
1000 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1001 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1002 /*isVariadic=*/false);
1003 auto FTy = CGM.getTypes().GetFunctionType(FI);
1004 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1005 FTy, ".__kmpc_global_dtor_.", Loc);
1006 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1007 SourceLocation());
1008 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1009 DtorCGF.GetAddrOfLocalVar(&Dst),
1010 /*Volatile=*/false, CGM.PointerAlignInBytes,
1011 CGM.getContext().VoidPtrTy, Dst.getLocation());
1012 DtorCGF.emitDestroy(ArgVal, ASTTy,
1013 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1014 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1015 DtorCGF.FinishFunction();
1016 Dtor = Fn;
1017 }
1018 // Do not emit init function if it is not required.
1019 if (!Ctor && !Dtor)
1020 return nullptr;
1021
1022 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1023 auto CopyCtorTy =
1024 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1025 /*isVarArg=*/false)->getPointerTo();
1026 // Copying constructor for the threadprivate variable.
1027 // Must be NULL - reserved by runtime, but currently it requires that this
1028 // parameter is always NULL. Otherwise it fires assertion.
1029 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1030 if (Ctor == nullptr) {
1031 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1032 /*isVarArg=*/false)->getPointerTo();
1033 Ctor = llvm::Constant::getNullValue(CtorTy);
1034 }
1035 if (Dtor == nullptr) {
1036 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1037 /*isVarArg=*/false)->getPointerTo();
1038 Dtor = llvm::Constant::getNullValue(DtorTy);
1039 }
1040 if (!CGF) {
1041 auto InitFunctionTy =
1042 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1043 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1044 InitFunctionTy, ".__omp_threadprivate_init_.");
1045 CodeGenFunction InitCGF(CGM);
1046 FunctionArgList ArgList;
1047 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1048 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1049 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001050 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001051 InitCGF.FinishFunction();
1052 return InitFunction;
1053 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001054 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001055 }
1056 return nullptr;
1057}
1058
Alexey Bataev1d677132015-04-22 13:57:31 +00001059/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1060/// function. Here is the logic:
1061/// if (Cond) {
1062/// ThenGen();
1063/// } else {
1064/// ElseGen();
1065/// }
1066static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1067 const RegionCodeGenTy &ThenGen,
1068 const RegionCodeGenTy &ElseGen) {
1069 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1070
1071 // If the condition constant folds and can be elided, try to avoid emitting
1072 // the condition and the dead arm of the if/else.
1073 bool CondConstant;
1074 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1075 CodeGenFunction::RunCleanupsScope Scope(CGF);
1076 if (CondConstant) {
1077 ThenGen(CGF);
1078 } else {
1079 ElseGen(CGF);
1080 }
1081 return;
1082 }
1083
1084 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1085 // emit the conditional branch.
1086 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1087 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1088 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1089 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1090
1091 // Emit the 'then' code.
1092 CGF.EmitBlock(ThenBlock);
1093 {
1094 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1095 ThenGen(CGF);
1096 }
1097 CGF.EmitBranch(ContBlock);
1098 // Emit the 'else' code if present.
1099 {
1100 // There is no need to emit line number for unconditional branch.
1101 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1102 CGF.EmitBlock(ElseBlock);
1103 }
1104 {
1105 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1106 ElseGen(CGF);
1107 }
1108 {
1109 // There is no need to emit line number for unconditional branch.
1110 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1111 CGF.EmitBranch(ContBlock);
1112 }
1113 // Emit the continuation block for code after the if.
1114 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001115}
1116
Alexey Bataev1d677132015-04-22 13:57:31 +00001117void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1118 llvm::Value *OutlinedFn,
1119 llvm::Value *CapturedStruct,
1120 const Expr *IfCond) {
1121 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1122 auto &&ThenGen =
1123 [this, OutlinedFn, CapturedStruct, RTLoc](CodeGenFunction &CGF) {
1124 // Build call __kmpc_fork_call(loc, 1, microtask,
1125 // captured_struct/*context*/)
1126 llvm::Value *Args[] = {
1127 RTLoc,
1128 CGF.Builder.getInt32(
1129 1), // Number of arguments after 'microtask' argument
1130 // (there is only one additional argument - 'context')
1131 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
1132 CGF.EmitCastToVoidPtr(CapturedStruct)};
1133 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1134 CGF.EmitRuntimeCall(RTLFn, Args);
1135 };
1136 auto &&ElseGen = [this, OutlinedFn, CapturedStruct, RTLoc, Loc](
1137 CodeGenFunction &CGF) {
1138 auto ThreadID = getThreadID(CGF, Loc);
1139 // Build calls:
1140 // __kmpc_serialized_parallel(&Loc, GTid);
1141 llvm::Value *Args[] = {RTLoc, ThreadID};
1142 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1143 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001144
Alexey Bataev1d677132015-04-22 13:57:31 +00001145 // OutlinedFn(&GTid, &zero, CapturedStruct);
1146 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1147 auto Int32Ty = CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32,
1148 /*Signed*/ true);
1149 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
1150 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1151 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
1152 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001153
Alexey Bataev1d677132015-04-22 13:57:31 +00001154 // __kmpc_end_serialized_parallel(&Loc, GTid);
1155 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1156 CGF.EmitRuntimeCall(
1157 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1158 };
1159 if (IfCond) {
1160 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1161 } else {
1162 CodeGenFunction::RunCleanupsScope Scope(CGF);
1163 ThenGen(CGF);
1164 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001165}
1166
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001167// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001168// thread-ID variable (it is passed in a first argument of the outlined function
1169// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1170// regular serial code region, get thread ID by calling kmp_int32
1171// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1172// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001173llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +00001174 SourceLocation Loc) {
1175 if (auto OMPRegionInfo =
1176 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001177 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001178 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001179
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001180 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001181 auto Int32Ty =
1182 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1183 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1184 CGF.EmitStoreOfScalar(ThreadID,
1185 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
1186
1187 return ThreadIDTemp;
1188}
1189
Alexey Bataev97720002014-11-11 04:05:39 +00001190llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001191CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001192 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001193 SmallString<256> Buffer;
1194 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001195 Out << Name;
1196 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001197 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1198 if (Elem.second) {
1199 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001200 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001201 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001202 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001203
David Blaikie13156b62014-11-19 03:06:06 +00001204 return Elem.second = new llvm::GlobalVariable(
1205 CGM.getModule(), Ty, /*IsConstant*/ false,
1206 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1207 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001208}
1209
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001210llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001211 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001212 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001213}
1214
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001215namespace {
Alexey Bataeva744ff52015-05-05 09:24:37 +00001216template <size_t N> class CallEndCleanup : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001217 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001218 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001219
1220public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001221 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1222 : Callee(Callee) {
1223 assert(CleanupArgs.size() == N);
1224 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1225 }
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001226 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1227 CGF.EmitRuntimeCall(Callee, Args);
1228 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001229};
1230} // namespace
1231
1232void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1233 StringRef CriticalName,
1234 const RegionCodeGenTy &CriticalOpGen,
1235 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001236 // __kmpc_critical(ident_t *, gtid, Lock);
1237 // CriticalOpGen();
1238 // __kmpc_end_critical(ident_t *, gtid, Lock);
1239 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001240 {
1241 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001242 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1243 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001244 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001245 // Build a call to __kmpc_end_critical
Alexey Bataeva744ff52015-05-05 09:24:37 +00001246 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001247 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1248 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001249 emitInlinedDirective(CGF, CriticalOpGen);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001250 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001251}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001252
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001253static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001254 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001255 llvm::Value *CallBool = CGF.EmitScalarConversion(
1256 IfCond,
1257 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1258 CGF.getContext().BoolTy);
1259
1260 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1261 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1262 // Generate the branch (If-stmt)
1263 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1264 CGF.EmitBlock(ThenBlock);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001265 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001266 // Emit the rest of bblocks/branches
1267 CGF.EmitBranch(ContBlock);
1268 CGF.EmitBlock(ContBlock, true);
1269}
1270
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001271void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001272 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001273 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001274 // if(__kmpc_master(ident_t *, gtid)) {
1275 // MasterOpGen();
1276 // __kmpc_end_master(ident_t *, gtid);
1277 // }
1278 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001279 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001280 auto *IsMaster =
1281 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001282 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1283 MasterCallEndCleanup;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001284 emitIfStmt(CGF, IsMaster, [&](CodeGenFunction &CGF) -> void {
1285 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001286 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001287 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1288 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001289 MasterOpGen(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001290 });
1291}
1292
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001293void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1294 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001295 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1296 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001297 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001298 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001299 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001300}
1301
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001302void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1303 const RegionCodeGenTy &TaskgroupOpGen,
1304 SourceLocation Loc) {
1305 // __kmpc_taskgroup(ident_t *, gtid);
1306 // TaskgroupOpGen();
1307 // __kmpc_end_taskgroup(ident_t *, gtid);
1308 // Prepare arguments and build a call to __kmpc_taskgroup
1309 {
1310 CodeGenFunction::RunCleanupsScope Scope(CGF);
1311 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1312 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1313 // Build a call to __kmpc_end_taskgroup
1314 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1315 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1316 llvm::makeArrayRef(Args));
1317 emitInlinedDirective(CGF, TaskgroupOpGen);
1318 }
1319}
1320
Alexey Bataeva63048e2015-03-23 06:18:07 +00001321static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001322 CodeGenModule &CGM, llvm::Type *ArgsType,
1323 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1324 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001325 auto &C = CGM.getContext();
1326 // void copy_func(void *LHSArg, void *RHSArg);
1327 FunctionArgList Args;
1328 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1329 C.VoidPtrTy);
1330 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1331 C.VoidPtrTy);
1332 Args.push_back(&LHSArg);
1333 Args.push_back(&RHSArg);
1334 FunctionType::ExtInfo EI;
1335 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1336 C.VoidTy, Args, EI, /*isVariadic=*/false);
1337 auto *Fn = llvm::Function::Create(
1338 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1339 ".omp.copyprivate.copy_func", &CGM.getModule());
1340 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1341 CodeGenFunction CGF(CGM);
1342 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001343 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001344 // Src = (void*[n])(RHSArg);
1345 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1346 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1347 CGF.PointerAlignInBytes),
1348 ArgsType);
1349 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1350 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1351 CGF.PointerAlignInBytes),
1352 ArgsType);
1353 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1354 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1355 // ...
1356 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001357 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataev420d45b2015-04-14 05:11:24 +00001358 auto *DestAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1359 CGF.Builder.CreateAlignedLoad(
1360 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1361 CGM.PointerAlignInBytes),
1362 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1363 auto *SrcAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1364 CGF.Builder.CreateAlignedLoad(
1365 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1366 CGM.PointerAlignInBytes),
1367 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001368 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1369 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001370 CGF.EmitOMPCopy(CGF, Type, DestAddr, SrcAddr,
Alexey Bataev420d45b2015-04-14 05:11:24 +00001371 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()),
1372 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1373 AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001374 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001375 CGF.FinishFunction();
1376 return Fn;
1377}
1378
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001379void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001380 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001381 SourceLocation Loc,
1382 ArrayRef<const Expr *> CopyprivateVars,
1383 ArrayRef<const Expr *> SrcExprs,
1384 ArrayRef<const Expr *> DstExprs,
1385 ArrayRef<const Expr *> AssignmentOps) {
1386 assert(CopyprivateVars.size() == SrcExprs.size() &&
1387 CopyprivateVars.size() == DstExprs.size() &&
1388 CopyprivateVars.size() == AssignmentOps.size());
1389 auto &C = CGM.getContext();
1390 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001391 // if(__kmpc_single(ident_t *, gtid)) {
1392 // SingleOpGen();
1393 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001394 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001395 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001396 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1397 // <copy_func>, did_it);
1398
1399 llvm::AllocaInst *DidIt = nullptr;
1400 if (!CopyprivateVars.empty()) {
1401 // int32 did_it = 0;
1402 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1403 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
Alexey Bataev66beaa92015-04-30 03:47:32 +00001404 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(0), DidIt,
1405 DidIt->getAlignment());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001406 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001407 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001408 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001409 auto *IsSingle =
1410 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001411 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1412 SingleCallEndCleanup;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001413 emitIfStmt(CGF, IsSingle, [&](CodeGenFunction &CGF) -> void {
1414 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001415 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001416 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1417 llvm::makeArrayRef(Args));
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001418 SingleOpGen(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001419 if (DidIt) {
1420 // did_it = 1;
1421 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1422 DidIt->getAlignment());
1423 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001424 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001425 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1426 // <copy_func>, did_it);
1427 if (DidIt) {
1428 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1429 auto CopyprivateArrayTy =
1430 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1431 /*IndexTypeQuals=*/0);
1432 // Create a list of all private variables for copyprivate.
1433 auto *CopyprivateList =
1434 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1435 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001436 auto *Elem = CGF.Builder.CreateStructGEP(
1437 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001438 CGF.Builder.CreateAlignedStore(
1439 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1440 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1441 Elem, CGM.PointerAlignInBytes);
1442 }
1443 // Build function that copies private values from single region to all other
1444 // threads in the corresponding parallel region.
1445 auto *CpyFn = emitCopyprivateCopyFunction(
1446 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001447 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001448 auto *BufSize = llvm::ConstantInt::get(
1449 CGM.SizeTy, C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001450 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1451 CGF.VoidPtrTy);
1452 auto *DidItVal =
1453 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1454 llvm::Value *Args[] = {
1455 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1456 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001457 BufSize, // size_t <buf_size>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001458 CL, // void *<copyprivate list>
1459 CpyFn, // void (*) (void *, void *) <copy_func>
1460 DidItVal // i32 did_it
1461 };
1462 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1463 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001464}
1465
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001466void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1467 const RegionCodeGenTy &OrderedOpGen,
1468 SourceLocation Loc) {
1469 // __kmpc_ordered(ident_t *, gtid);
1470 // OrderedOpGen();
1471 // __kmpc_end_ordered(ident_t *, gtid);
1472 // Prepare arguments and build a call to __kmpc_ordered
1473 {
1474 CodeGenFunction::RunCleanupsScope Scope(CGF);
1475 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1476 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1477 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001478 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001479 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1480 llvm::makeArrayRef(Args));
1481 emitInlinedDirective(CGF, OrderedOpGen);
1482 }
1483}
1484
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001485void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001486 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001487 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001488 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1489 if (Kind == OMPD_for) {
1490 Flags =
1491 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1492 } else if (Kind == OMPD_sections) {
1493 Flags = static_cast<OpenMPLocationFlags>(Flags |
1494 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1495 } else if (Kind == OMPD_single) {
1496 Flags =
1497 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1498 } else if (Kind == OMPD_barrier) {
1499 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1500 } else {
1501 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1502 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001503 // Build call __kmpc_cancel_barrier(loc, thread_id);
1504 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1505 // one provides the same functionality and adds initial support for
1506 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1507 // is provided default by the runtime library so it safe to make such
1508 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001509 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1510 getThreadID(CGF, Loc)};
1511 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001512}
1513
Alexander Musmanc6388682014-12-15 07:07:06 +00001514/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1515/// the enum sched_type in kmp.h).
1516enum OpenMPSchedType {
1517 /// \brief Lower bound for default (unordered) versions.
1518 OMP_sch_lower = 32,
1519 OMP_sch_static_chunked = 33,
1520 OMP_sch_static = 34,
1521 OMP_sch_dynamic_chunked = 35,
1522 OMP_sch_guided_chunked = 36,
1523 OMP_sch_runtime = 37,
1524 OMP_sch_auto = 38,
1525 /// \brief Lower bound for 'ordered' versions.
1526 OMP_ord_lower = 64,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001527 OMP_ord_static_chunked = 65,
1528 OMP_ord_static = 66,
1529 OMP_ord_dynamic_chunked = 67,
1530 OMP_ord_guided_chunked = 68,
1531 OMP_ord_runtime = 69,
1532 OMP_ord_auto = 70,
1533 OMP_sch_default = OMP_sch_static,
Alexander Musmanc6388682014-12-15 07:07:06 +00001534};
1535
1536/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1537static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001538 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001539 switch (ScheduleKind) {
1540 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001541 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
1542 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00001543 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001544 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001545 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001546 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001547 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001548 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
1549 case OMPC_SCHEDULE_auto:
1550 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00001551 case OMPC_SCHEDULE_unknown:
1552 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001553 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00001554 }
1555 llvm_unreachable("Unexpected runtime schedule");
1556}
1557
1558bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1559 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001560 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00001561 return Schedule == OMP_sch_static;
1562}
1563
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001564bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001565 auto Schedule =
1566 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001567 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1568 return Schedule != OMP_sch_static;
1569}
1570
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001571void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1572 OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001573 unsigned IVSize, bool IVSigned, bool Ordered,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001574 llvm::Value *IL, llvm::Value *LB,
1575 llvm::Value *UB, llvm::Value *ST,
1576 llvm::Value *Chunk) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001577 OpenMPSchedType Schedule =
1578 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
1579 if (Ordered ||
1580 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
1581 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked)) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001582 // Call __kmpc_dispatch_init(
1583 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1584 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1585 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001586
Alexander Musman92bdaab2015-03-12 13:37:50 +00001587 // If the Chunk was not specified in the clause - use default value 1.
1588 if (Chunk == nullptr)
1589 Chunk = CGF.Builder.getIntN(IVSize, 1);
1590 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1591 getThreadID(CGF, Loc),
1592 CGF.Builder.getInt32(Schedule), // Schedule type
1593 CGF.Builder.getIntN(IVSize, 0), // Lower
1594 UB, // Upper
1595 CGF.Builder.getIntN(IVSize, 1), // Stride
1596 Chunk // Chunk
1597 };
1598 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1599 } else {
1600 // Call __kmpc_for_static_init(
1601 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1602 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1603 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1604 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1605 if (Chunk == nullptr) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001606 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
Alexander Musman92bdaab2015-03-12 13:37:50 +00001607 "expected static non-chunked schedule");
1608 // If the Chunk was not specified in the clause - use default value 1.
1609 Chunk = CGF.Builder.getIntN(IVSize, 1);
1610 } else
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001611 assert((Schedule == OMP_sch_static_chunked ||
1612 Schedule == OMP_ord_static_chunked) &&
Alexander Musman92bdaab2015-03-12 13:37:50 +00001613 "expected static chunked schedule");
1614 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1615 getThreadID(CGF, Loc),
1616 CGF.Builder.getInt32(Schedule), // Schedule type
1617 IL, // &isLastIter
1618 LB, // &LB
1619 UB, // &UB
1620 ST, // &Stride
1621 CGF.Builder.getIntN(IVSize, 1), // Incr
1622 Chunk // Chunk
1623 };
Alexander Musman21212e42015-03-13 10:38:23 +00001624 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001625 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001626}
1627
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001628void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1629 SourceLocation Loc) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001630 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001631 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1632 getThreadID(CGF, Loc)};
1633 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1634 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001635}
1636
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001637void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
1638 SourceLocation Loc,
1639 unsigned IVSize,
1640 bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001641 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1642 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1643 getThreadID(CGF, Loc)};
1644 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1645}
1646
Alexander Musman92bdaab2015-03-12 13:37:50 +00001647llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1648 SourceLocation Loc, unsigned IVSize,
1649 bool IVSigned, llvm::Value *IL,
1650 llvm::Value *LB, llvm::Value *UB,
1651 llvm::Value *ST) {
1652 // Call __kmpc_dispatch_next(
1653 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1654 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1655 // kmp_int[32|64] *p_stride);
1656 llvm::Value *Args[] = {
1657 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1658 IL, // &isLastIter
1659 LB, // &Lower
1660 UB, // &Upper
1661 ST // &Stride
1662 };
1663 llvm::Value *Call =
1664 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1665 return CGF.EmitScalarConversion(
1666 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1667 CGF.getContext().BoolTy);
1668}
1669
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001670void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1671 llvm::Value *NumThreads,
1672 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001673 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1674 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001675 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001676 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001677 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1678 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001679}
1680
Alexey Bataev7f210c62015-06-18 13:40:03 +00001681void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
1682 OpenMPProcBindClauseKind ProcBind,
1683 SourceLocation Loc) {
1684 // Constants for proc bind value accepted by the runtime.
1685 enum ProcBindTy {
1686 ProcBindFalse = 0,
1687 ProcBindTrue,
1688 ProcBindMaster,
1689 ProcBindClose,
1690 ProcBindSpread,
1691 ProcBindIntel,
1692 ProcBindDefault
1693 } RuntimeProcBind;
1694 switch (ProcBind) {
1695 case OMPC_PROC_BIND_master:
1696 RuntimeProcBind = ProcBindMaster;
1697 break;
1698 case OMPC_PROC_BIND_close:
1699 RuntimeProcBind = ProcBindClose;
1700 break;
1701 case OMPC_PROC_BIND_spread:
1702 RuntimeProcBind = ProcBindSpread;
1703 break;
1704 case OMPC_PROC_BIND_unknown:
1705 llvm_unreachable("Unsupported proc_bind value.");
1706 }
1707 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
1708 llvm::Value *Args[] = {
1709 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1710 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
1711 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
1712}
1713
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001714void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1715 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001716 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001717 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1718 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001719}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001720
Alexey Bataev62b63b12015-03-10 07:28:44 +00001721namespace {
1722/// \brief Indexes of fields for type kmp_task_t.
1723enum KmpTaskTFields {
1724 /// \brief List of shared variables.
1725 KmpTaskTShareds,
1726 /// \brief Task routine.
1727 KmpTaskTRoutine,
1728 /// \brief Partition id for the untied tasks.
1729 KmpTaskTPartId,
1730 /// \brief Function with call of destructors for private variables.
1731 KmpTaskTDestructors,
1732};
1733} // namespace
1734
1735void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1736 if (!KmpRoutineEntryPtrTy) {
1737 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1738 auto &C = CGM.getContext();
1739 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1740 FunctionProtoType::ExtProtoInfo EPI;
1741 KmpRoutineEntryPtrQTy = C.getPointerType(
1742 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1743 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1744 }
1745}
1746
1747static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1748 QualType FieldTy) {
1749 auto *Field = FieldDecl::Create(
1750 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1751 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1752 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1753 Field->setAccess(AS_public);
1754 DC->addDecl(Field);
1755}
1756
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001757namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00001758struct PrivateHelpersTy {
1759 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
1760 const VarDecl *PrivateElemInit)
1761 : Original(Original), PrivateCopy(PrivateCopy),
1762 PrivateElemInit(PrivateElemInit) {}
1763 const VarDecl *Original;
1764 const VarDecl *PrivateCopy;
1765 const VarDecl *PrivateElemInit;
1766};
1767typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001768} // namespace
1769
Alexey Bataev9e034042015-05-05 04:05:12 +00001770static RecordDecl *
1771createPrivatesRecordDecl(CodeGenModule &CGM,
1772 const ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001773 if (!Privates.empty()) {
1774 auto &C = CGM.getContext();
1775 // Build struct .kmp_privates_t. {
1776 // /* private vars */
1777 // };
1778 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
1779 RD->startDefinition();
1780 for (auto &&Pair : Privates) {
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001781 auto Type = Pair.second.Original->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001782 Type = Type.getNonReferenceType();
1783 addFieldToRecordDecl(C, RD, Type);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001784 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001785 RD->completeDefinition();
1786 return RD;
1787 }
1788 return nullptr;
1789}
1790
Alexey Bataev9e034042015-05-05 04:05:12 +00001791static RecordDecl *
1792createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001793 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001794 auto &C = CGM.getContext();
1795 // Build struct kmp_task_t {
1796 // void * shareds;
1797 // kmp_routine_entry_t routine;
1798 // kmp_int32 part_id;
1799 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001800 // };
1801 auto *RD = C.buildImplicitRecord("kmp_task_t");
1802 RD->startDefinition();
1803 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1804 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1805 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1806 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001807 RD->completeDefinition();
1808 return RD;
1809}
1810
1811static RecordDecl *
1812createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
1813 const ArrayRef<PrivateDataTy> Privates) {
1814 auto &C = CGM.getContext();
1815 // Build struct kmp_task_t_with_privates {
1816 // kmp_task_t task_data;
1817 // .kmp_privates_t. privates;
1818 // };
1819 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
1820 RD->startDefinition();
1821 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001822 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
1823 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
1824 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001825 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001826 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001827}
1828
1829/// \brief Emit a proxy function which accepts kmp_task_t as the second
1830/// argument.
1831/// \code
1832/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001833/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
1834/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001835/// return 0;
1836/// }
1837/// \endcode
1838static llvm::Value *
1839emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001840 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
1841 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001842 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1843 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001844 auto &C = CGM.getContext();
1845 FunctionArgList Args;
1846 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1847 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001848 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001849 Args.push_back(&GtidArg);
1850 Args.push_back(&TaskTypeArg);
1851 FunctionType::ExtInfo Info;
1852 auto &TaskEntryFnInfo =
1853 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1854 /*isVariadic=*/false);
1855 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1856 auto *TaskEntry =
1857 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1858 ".omp_task_entry.", &CGM.getModule());
1859 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1860 CodeGenFunction CGF(CGM);
1861 CGF.disableDebugInfo();
1862 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1863
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001864 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
1865 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001866 auto *GtidParam = CGF.EmitLoadOfScalar(
1867 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1868 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001869 auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
1870 CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001871 LValue TDBase =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001872 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1873 auto *KmpTaskTWithPrivatesQTyRD =
1874 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001875 LValue Base =
1876 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001877 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
1878 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
1879 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
1880 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
1881
1882 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
1883 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001884 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001885 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001886 CGF.ConvertTypeForMem(SharedsPtrTy));
1887
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001888 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
1889 llvm::Value *PrivatesParam;
1890 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
1891 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
1892 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1893 PrivatesLVal.getAddress(), CGF.VoidPtrTy);
1894 } else {
1895 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
1896 }
1897
1898 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
1899 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00001900 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1901 CGF.EmitStoreThroughLValue(
1902 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1903 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1904 CGF.FinishFunction();
1905 return TaskEntry;
1906}
1907
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001908static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
1909 SourceLocation Loc,
1910 QualType KmpInt32Ty,
1911 QualType KmpTaskTWithPrivatesPtrQTy,
1912 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001913 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001914 FunctionArgList Args;
1915 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1916 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001917 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001918 Args.push_back(&GtidArg);
1919 Args.push_back(&TaskTypeArg);
1920 FunctionType::ExtInfo Info;
1921 auto &DestructorFnInfo =
1922 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1923 /*isVariadic=*/false);
1924 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
1925 auto *DestructorFn =
1926 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
1927 ".omp_task_destructor.", &CGM.getModule());
1928 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, DestructorFnInfo, DestructorFn);
1929 CodeGenFunction CGF(CGM);
1930 CGF.disableDebugInfo();
1931 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
1932 Args);
1933
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001934 auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
1935 CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
1936 LValue Base =
1937 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1938 auto *KmpTaskTWithPrivatesQTyRD =
1939 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
1940 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001941 Base = CGF.EmitLValueForField(Base, *FI);
1942 for (auto *Field :
1943 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
1944 if (auto DtorKind = Field->getType().isDestructedType()) {
1945 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
1946 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
1947 }
1948 }
1949 CGF.FinishFunction();
1950 return DestructorFn;
1951}
1952
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001953/// \brief Emit a privates mapping function for correct handling of private and
1954/// firstprivate variables.
1955/// \code
1956/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
1957/// **noalias priv1,..., <tyn> **noalias privn) {
1958/// *priv1 = &.privates.priv1;
1959/// ...;
1960/// *privn = &.privates.privn;
1961/// }
1962/// \endcode
1963static llvm::Value *
1964emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
1965 const ArrayRef<const Expr *> PrivateVars,
1966 const ArrayRef<const Expr *> FirstprivateVars,
1967 QualType PrivatesQTy,
1968 const ArrayRef<PrivateDataTy> Privates) {
1969 auto &C = CGM.getContext();
1970 FunctionArgList Args;
1971 ImplicitParamDecl TaskPrivatesArg(
1972 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1973 C.getPointerType(PrivatesQTy).withConst().withRestrict());
1974 Args.push_back(&TaskPrivatesArg);
1975 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
1976 unsigned Counter = 1;
1977 for (auto *E: PrivateVars) {
1978 Args.push_back(ImplicitParamDecl::Create(
1979 C, /*DC=*/nullptr, Loc,
1980 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
1981 .withConst()
1982 .withRestrict()));
1983 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1984 PrivateVarsPos[VD] = Counter;
1985 ++Counter;
1986 }
1987 for (auto *E : FirstprivateVars) {
1988 Args.push_back(ImplicitParamDecl::Create(
1989 C, /*DC=*/nullptr, Loc,
1990 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
1991 .withConst()
1992 .withRestrict()));
1993 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1994 PrivateVarsPos[VD] = Counter;
1995 ++Counter;
1996 }
1997 FunctionType::ExtInfo Info;
1998 auto &TaskPrivatesMapFnInfo =
1999 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2000 /*isVariadic=*/false);
2001 auto *TaskPrivatesMapTy =
2002 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2003 auto *TaskPrivatesMap = llvm::Function::Create(
2004 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2005 ".omp_task_privates_map.", &CGM.getModule());
2006 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskPrivatesMapFnInfo,
2007 TaskPrivatesMap);
2008 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
2009 CodeGenFunction CGF(CGM);
2010 CGF.disableDebugInfo();
2011 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2012 TaskPrivatesMapFnInfo, Args);
2013
2014 // *privi = &.privates.privi;
2015 auto *TaskPrivatesArgAddr = CGF.Builder.CreateAlignedLoad(
2016 CGF.GetAddrOfLocalVar(&TaskPrivatesArg), CGM.PointerAlignInBytes);
2017 LValue Base =
2018 CGF.MakeNaturalAlignAddrLValue(TaskPrivatesArgAddr, PrivatesQTy);
2019 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2020 Counter = 0;
2021 for (auto *Field : PrivatesQTyRD->fields()) {
2022 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2023 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
2024 auto RefLVal = CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(VD),
2025 VD->getType());
2026 auto RefLoadRVal = CGF.EmitLoadOfLValue(RefLVal, Loc);
2027 CGF.EmitStoreOfScalar(
2028 FieldLVal.getAddress(),
2029 CGF.MakeNaturalAlignAddrLValue(RefLoadRVal.getScalarVal(),
2030 RefLVal.getType()->getPointeeType()));
2031 ++Counter;
2032 }
2033 CGF.FinishFunction();
2034 return TaskPrivatesMap;
2035}
2036
Alexey Bataev9e034042015-05-05 04:05:12 +00002037static int array_pod_sort_comparator(const PrivateDataTy *P1,
2038 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002039 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2040}
2041
2042void CGOpenMPRuntime::emitTaskCall(
2043 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
2044 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
2045 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002046 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
2047 ArrayRef<const Expr *> PrivateCopies,
2048 ArrayRef<const Expr *> FirstprivateVars,
2049 ArrayRef<const Expr *> FirstprivateCopies,
2050 ArrayRef<const Expr *> FirstprivateInits,
2051 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002052 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00002053 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002054 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00002055 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002056 for (auto *E : PrivateVars) {
2057 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2058 Privates.push_back(std::make_pair(
2059 C.getTypeAlignInChars(VD->getType()),
Alexey Bataev9e034042015-05-05 04:05:12 +00002060 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2061 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002062 ++I;
2063 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002064 I = FirstprivateCopies.begin();
2065 auto IElemInitRef = FirstprivateInits.begin();
2066 for (auto *E : FirstprivateVars) {
2067 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2068 Privates.push_back(std::make_pair(
2069 C.getTypeAlignInChars(VD->getType()),
2070 PrivateHelpersTy(
2071 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2072 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
2073 ++I, ++IElemInitRef;
2074 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002075 llvm::array_pod_sort(Privates.begin(), Privates.end(),
2076 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002077 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2078 // Build type kmp_routine_entry_t (if not built yet).
2079 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002080 // Build type kmp_task_t (if not built yet).
2081 if (KmpTaskTQTy.isNull()) {
2082 KmpTaskTQTy = C.getRecordType(
2083 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2084 }
2085 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002086 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002087 auto *KmpTaskTWithPrivatesQTyRD =
2088 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2089 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2090 QualType KmpTaskTWithPrivatesPtrQTy =
2091 C.getPointerType(KmpTaskTWithPrivatesQTy);
2092 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2093 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
2094 auto KmpTaskTWithPrivatesTySize =
2095 CGM.getSize(C.getTypeSizeInChars(KmpTaskTWithPrivatesQTy));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002096 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2097
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002098 // Emit initial values for private copies (if any).
2099 llvm::Value *TaskPrivatesMap = nullptr;
2100 auto *TaskPrivatesMapTy =
2101 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2102 3)
2103 ->getType();
2104 if (!Privates.empty()) {
2105 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2106 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2107 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2108 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2109 TaskPrivatesMap, TaskPrivatesMapTy);
2110 } else {
2111 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2112 cast<llvm::PointerType>(TaskPrivatesMapTy));
2113 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002114 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2115 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002116 auto *TaskEntry = emitProxyTaskFunction(
2117 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002118 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002119
2120 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2121 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2122 // kmp_routine_entry_t *task_entry);
2123 // Task flags. Format is taken from
2124 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2125 // description of kmp_tasking_flags struct.
2126 const unsigned TiedFlag = 0x1;
2127 const unsigned FinalFlag = 0x2;
2128 unsigned Flags = Tied ? TiedFlag : 0;
2129 auto *TaskFlags =
2130 Final.getPointer()
2131 ? CGF.Builder.CreateSelect(Final.getPointer(),
2132 CGF.Builder.getInt32(FinalFlag),
2133 CGF.Builder.getInt32(/*C=*/0))
2134 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2135 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
2136 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002137 llvm::Value *AllocArgs[] = {
2138 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), TaskFlags,
2139 KmpTaskTWithPrivatesTySize, CGM.getSize(SharedsSize),
2140 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskEntry,
2141 KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002142 auto *NewTask = CGF.EmitRuntimeCall(
2143 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002144 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2145 NewTask, KmpTaskTWithPrivatesPtrTy);
2146 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2147 KmpTaskTWithPrivatesQTy);
2148 LValue TDBase =
2149 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002150 // Fill the data in the resulting kmp_task_t record.
2151 // Copy shareds if there are any.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002152 llvm::Value *KmpTaskSharedsPtr = nullptr;
2153 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
2154 KmpTaskSharedsPtr = CGF.EmitLoadOfScalar(
2155 CGF.EmitLValueForField(
2156 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)),
2157 Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002158 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002159 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002160 // Emit initial values for private copies (if any).
2161 bool NeedsCleanup = false;
2162 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002163 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2164 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002165 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002166 LValue SharedsBase;
2167 if (!FirstprivateVars.empty()) {
2168 SharedsBase = CGF.MakeNaturalAlignAddrLValue(
2169 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2170 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2171 SharedsTy);
2172 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002173 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2174 cast<CapturedStmt>(*D.getAssociatedStmt()));
2175 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002176 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002177 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002178 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002179 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002180 if (auto *Elem = Pair.second.PrivateElemInit) {
2181 auto *OriginalVD = Pair.second.Original;
2182 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2183 auto SharedRefLValue =
2184 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002185 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002186 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002187 // Initialize firstprivate array.
2188 if (!isa<CXXConstructExpr>(Init) ||
2189 CGF.isTrivialInitializer(Init)) {
2190 // Perform simple memcpy.
2191 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002192 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002193 } else {
2194 // Initialize firstprivate array using element-by-element
2195 // intialization.
2196 CGF.EmitOMPAggregateAssign(
2197 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002198 Type, [&CGF, Elem, Init, &CapturesInfo](
2199 llvm::Value *DestElement, llvm::Value *SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002200 // Clean up any temporaries needed by the initialization.
2201 CodeGenFunction::OMPPrivateScope InitScope(CGF);
2202 InitScope.addPrivate(Elem, [SrcElement]() -> llvm::Value *{
2203 return SrcElement;
2204 });
2205 (void)InitScope.Privatize();
2206 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00002207 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
2208 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002209 CGF.EmitAnyExprToMem(Init, DestElement,
2210 Init->getType().getQualifiers(),
2211 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002212 });
2213 }
2214 } else {
2215 CodeGenFunction::OMPPrivateScope InitScope(CGF);
2216 InitScope.addPrivate(Elem, [SharedRefLValue]() -> llvm::Value *{
2217 return SharedRefLValue.getAddress();
2218 });
2219 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00002220 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002221 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2222 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002223 }
2224 } else {
2225 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2226 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002227 }
2228 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002229 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002230 }
2231 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002232 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002233 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002234 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2235 KmpTaskTWithPrivatesPtrQTy,
2236 KmpTaskTWithPrivatesQTy)
2237 : llvm::ConstantPointerNull::get(
2238 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2239 LValue Destructor = CGF.EmitLValueForField(
2240 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2241 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2242 DestructorFn, KmpRoutineEntryPtrTy),
2243 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002244
2245 // Process list of dependences.
2246 llvm::Value *DependInfo = nullptr;
2247 unsigned DependencesNumber = Dependences.size();
2248 if (!Dependences.empty()) {
2249 // Dependence kind for RTL.
2250 enum RTLDependenceKindTy { DepIn = 1, DepOut = 2, DepInOut = 3 };
2251 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
2252 RecordDecl *KmpDependInfoRD;
2253 QualType FlagsTy = C.getIntTypeForBitwidth(
2254 C.toBits(C.getTypeSizeInChars(C.BoolTy)), /*Signed=*/false);
2255 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
2256 if (KmpDependInfoTy.isNull()) {
2257 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
2258 KmpDependInfoRD->startDefinition();
2259 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
2260 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
2261 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
2262 KmpDependInfoRD->completeDefinition();
2263 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
2264 } else {
2265 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
2266 }
2267 // Define type kmp_depend_info[<Dependences.size()>];
2268 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
2269 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, Dependences.size()),
2270 ArrayType::Normal, /*IndexTypeQuals=*/0);
2271 // kmp_depend_info[<Dependences.size()>] deps;
2272 DependInfo = CGF.CreateMemTemp(KmpDependInfoArrayTy);
2273 for (unsigned i = 0; i < DependencesNumber; ++i) {
2274 auto Addr = CGF.EmitLValue(Dependences[i].second);
2275 auto *Size = llvm::ConstantInt::get(
2276 CGF.SizeTy,
2277 C.getTypeSizeInChars(Dependences[i].second->getType()).getQuantity());
2278 auto Base = CGF.MakeNaturalAlignAddrLValue(
2279 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, DependInfo, i),
2280 KmpDependInfoTy);
2281 // deps[i].base_addr = &<Dependences[i].second>;
2282 auto BaseAddrLVal = CGF.EmitLValueForField(
2283 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
2284 CGF.EmitStoreOfScalar(
2285 CGF.Builder.CreatePtrToInt(Addr.getAddress(), CGF.IntPtrTy),
2286 BaseAddrLVal);
2287 // deps[i].len = sizeof(<Dependences[i].second>);
2288 auto LenLVal = CGF.EmitLValueForField(
2289 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
2290 CGF.EmitStoreOfScalar(Size, LenLVal);
2291 // deps[i].flags = <Dependences[i].first>;
2292 RTLDependenceKindTy DepKind;
2293 switch (Dependences[i].first) {
2294 case OMPC_DEPEND_in:
2295 DepKind = DepIn;
2296 break;
2297 case OMPC_DEPEND_out:
2298 DepKind = DepOut;
2299 break;
2300 case OMPC_DEPEND_inout:
2301 DepKind = DepInOut;
2302 break;
2303 case OMPC_DEPEND_unknown:
2304 llvm_unreachable("Unknown task dependence type");
2305 }
2306 auto FlagsLVal = CGF.EmitLValueForField(
2307 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
2308 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
2309 FlagsLVal);
2310 }
2311 DependInfo = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2312 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, DependInfo, 0),
2313 CGF.VoidPtrTy);
2314 }
2315
Alexey Bataev62b63b12015-03-10 07:28:44 +00002316 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
2317 // libcall.
2318 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
2319 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002320 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2321 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2322 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
2323 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00002324 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002325 auto *UpLoc = emitUpdateLocation(CGF, Loc);
2326 llvm::Value *TaskArgs[] = {UpLoc, ThreadID, NewTask};
2327 llvm::Value *DepTaskArgs[] = {
2328 UpLoc,
2329 ThreadID,
2330 NewTask,
2331 DependInfo ? CGF.Builder.getInt32(DependencesNumber) : nullptr,
2332 DependInfo,
2333 DependInfo ? CGF.Builder.getInt32(0) : nullptr,
2334 DependInfo ? llvm::ConstantPointerNull::get(CGF.VoidPtrTy) : nullptr};
2335 auto &&ThenCodeGen = [this, DependInfo, &TaskArgs,
2336 &DepTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002337 // TODO: add check for untied tasks.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002338 CGF.EmitRuntimeCall(
2339 createRuntimeFunction(DependInfo ? OMPRTL__kmpc_omp_task_with_deps
2340 : OMPRTL__kmpc_omp_task),
2341 DependInfo ? makeArrayRef(DepTaskArgs) : makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002342 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002343 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
2344 IfCallEndCleanup;
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002345 llvm::Value *DepWaitTaskArgs[] = {
2346 UpLoc,
2347 ThreadID,
2348 DependInfo ? CGF.Builder.getInt32(DependencesNumber) : nullptr,
2349 DependInfo,
2350 DependInfo ? CGF.Builder.getInt32(0) : nullptr,
2351 DependInfo ? llvm::ConstantPointerNull::get(CGF.VoidPtrTy) : nullptr};
2352 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
2353 DependInfo, &DepWaitTaskArgs](CodeGenFunction &CGF) {
2354 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
2355 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2356 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
2357 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
2358 // is specified.
2359 if (DependInfo)
2360 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
2361 DepWaitTaskArgs);
2362 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
2363 // kmp_task_t *new_task);
2364 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
2365 TaskArgs);
2366 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
2367 // kmp_task_t *new_task);
2368 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
2369 NormalAndEHCleanup,
2370 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
2371 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002372
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002373 // Call proxy_task_entry(gtid, new_task);
2374 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
2375 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
2376 };
Alexey Bataev1d677132015-04-22 13:57:31 +00002377 if (IfCond) {
2378 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
2379 } else {
2380 CodeGenFunction::RunCleanupsScope Scope(CGF);
2381 ThenCodeGen(CGF);
2382 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002383}
2384
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002385static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
2386 llvm::Type *ArgsType,
2387 ArrayRef<const Expr *> LHSExprs,
2388 ArrayRef<const Expr *> RHSExprs,
2389 ArrayRef<const Expr *> ReductionOps) {
2390 auto &C = CGM.getContext();
2391
2392 // void reduction_func(void *LHSArg, void *RHSArg);
2393 FunctionArgList Args;
2394 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2395 C.VoidPtrTy);
2396 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2397 C.VoidPtrTy);
2398 Args.push_back(&LHSArg);
2399 Args.push_back(&RHSArg);
2400 FunctionType::ExtInfo EI;
2401 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2402 C.VoidTy, Args, EI, /*isVariadic=*/false);
2403 auto *Fn = llvm::Function::Create(
2404 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2405 ".omp.reduction.reduction_func", &CGM.getModule());
2406 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
2407 CodeGenFunction CGF(CGM);
2408 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2409
2410 // Dst = (void*[n])(LHSArg);
2411 // Src = (void*[n])(RHSArg);
2412 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2413 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
2414 CGF.PointerAlignInBytes),
2415 ArgsType);
2416 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2417 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
2418 CGF.PointerAlignInBytes),
2419 ArgsType);
2420
2421 // ...
2422 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
2423 // ...
2424 CodeGenFunction::OMPPrivateScope Scope(CGF);
2425 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
2426 Scope.addPrivate(
2427 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()),
2428 [&]() -> llvm::Value *{
2429 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2430 CGF.Builder.CreateAlignedLoad(
2431 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, RHS, I),
2432 CGM.PointerAlignInBytes),
2433 CGF.ConvertTypeForMem(C.getPointerType(RHSExprs[I]->getType())));
2434 });
2435 Scope.addPrivate(
2436 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()),
2437 [&]() -> llvm::Value *{
2438 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2439 CGF.Builder.CreateAlignedLoad(
2440 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, LHS, I),
2441 CGM.PointerAlignInBytes),
2442 CGF.ConvertTypeForMem(C.getPointerType(LHSExprs[I]->getType())));
2443 });
2444 }
2445 Scope.Privatize();
2446 for (auto *E : ReductionOps) {
2447 CGF.EmitIgnoredExpr(E);
2448 }
2449 Scope.ForceCleanup();
2450 CGF.FinishFunction();
2451 return Fn;
2452}
2453
2454void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
2455 ArrayRef<const Expr *> LHSExprs,
2456 ArrayRef<const Expr *> RHSExprs,
2457 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002458 bool WithNowait, bool SimpleReduction) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002459 // Next code should be emitted for reduction:
2460 //
2461 // static kmp_critical_name lock = { 0 };
2462 //
2463 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
2464 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
2465 // ...
2466 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
2467 // *(Type<n>-1*)rhs[<n>-1]);
2468 // }
2469 //
2470 // ...
2471 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
2472 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2473 // RedList, reduce_func, &<lock>)) {
2474 // case 1:
2475 // ...
2476 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2477 // ...
2478 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2479 // break;
2480 // case 2:
2481 // ...
2482 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2483 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00002484 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002485 // break;
2486 // default:;
2487 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002488 //
2489 // if SimpleReduction is true, only the next code is generated:
2490 // ...
2491 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2492 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002493
2494 auto &C = CGM.getContext();
2495
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002496 if (SimpleReduction) {
2497 CodeGenFunction::RunCleanupsScope Scope(CGF);
2498 for (auto *E : ReductionOps) {
2499 CGF.EmitIgnoredExpr(E);
2500 }
2501 return;
2502 }
2503
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002504 // 1. Build a list of reduction variables.
2505 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2506 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
2507 QualType ReductionArrayTy =
2508 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2509 /*IndexTypeQuals=*/0);
2510 auto *ReductionList =
2511 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2512 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
2513 auto *Elem = CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, ReductionList, I);
2514 CGF.Builder.CreateAlignedStore(
2515 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2516 CGF.EmitLValue(RHSExprs[I]).getAddress(), CGF.VoidPtrTy),
2517 Elem, CGM.PointerAlignInBytes);
2518 }
2519
2520 // 2. Emit reduce_func().
2521 auto *ReductionFn = emitReductionFunction(
2522 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
2523 RHSExprs, ReductionOps);
2524
2525 // 3. Create static kmp_critical_name lock = { 0 };
2526 auto *Lock = getCriticalRegionLock(".reduction");
2527
2528 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2529 // RedList, reduce_func, &<lock>);
2530 auto *IdentTLoc = emitUpdateLocation(
2531 CGF, Loc,
2532 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
2533 auto *ThreadId = getThreadID(CGF, Loc);
2534 auto *ReductionArrayTySize = llvm::ConstantInt::get(
2535 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
2536 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList,
2537 CGF.VoidPtrTy);
2538 llvm::Value *Args[] = {
2539 IdentTLoc, // ident_t *<loc>
2540 ThreadId, // i32 <gtid>
2541 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
2542 ReductionArrayTySize, // size_type sizeof(RedList)
2543 RL, // void *RedList
2544 ReductionFn, // void (*) (void *, void *) <reduce_func>
2545 Lock // kmp_critical_name *&<lock>
2546 };
2547 auto Res = CGF.EmitRuntimeCall(
2548 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
2549 : OMPRTL__kmpc_reduce),
2550 Args);
2551
2552 // 5. Build switch(res)
2553 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2554 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
2555
2556 // 6. Build case 1:
2557 // ...
2558 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2559 // ...
2560 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2561 // break;
2562 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2563 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2564 CGF.EmitBlock(Case1BB);
2565
2566 {
2567 CodeGenFunction::RunCleanupsScope Scope(CGF);
2568 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2569 llvm::Value *EndArgs[] = {
2570 IdentTLoc, // ident_t *<loc>
2571 ThreadId, // i32 <gtid>
2572 Lock // kmp_critical_name *&<lock>
2573 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002574 CGF.EHStack
2575 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2576 NormalAndEHCleanup,
2577 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
2578 : OMPRTL__kmpc_end_reduce),
2579 llvm::makeArrayRef(EndArgs));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002580 for (auto *E : ReductionOps) {
2581 CGF.EmitIgnoredExpr(E);
2582 }
2583 }
2584
2585 CGF.EmitBranch(DefaultBB);
2586
2587 // 7. Build case 2:
2588 // ...
2589 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2590 // ...
2591 // break;
2592 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
2593 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
2594 CGF.EmitBlock(Case2BB);
2595
2596 {
2597 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00002598 if (!WithNowait) {
2599 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
2600 llvm::Value *EndArgs[] = {
2601 IdentTLoc, // ident_t *<loc>
2602 ThreadId, // i32 <gtid>
2603 Lock // kmp_critical_name *&<lock>
2604 };
2605 CGF.EHStack
2606 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2607 NormalAndEHCleanup,
2608 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
2609 llvm::makeArrayRef(EndArgs));
2610 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002611 auto I = LHSExprs.begin();
2612 for (auto *E : ReductionOps) {
2613 const Expr *XExpr = nullptr;
2614 const Expr *EExpr = nullptr;
2615 const Expr *UpExpr = nullptr;
2616 BinaryOperatorKind BO = BO_Comma;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002617 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2618 if (BO->getOpcode() == BO_Assign) {
2619 XExpr = BO->getLHS();
2620 UpExpr = BO->getRHS();
2621 }
2622 }
Alexey Bataev69a47792015-05-07 03:54:03 +00002623 // Try to emit update expression as a simple atomic.
2624 auto *RHSExpr = UpExpr;
2625 if (RHSExpr) {
2626 // Analyze RHS part of the whole expression.
2627 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
2628 RHSExpr->IgnoreParenImpCasts())) {
2629 // If this is a conditional operator, analyze its condition for
2630 // min/max reduction operator.
2631 RHSExpr = ACO->getCond();
2632 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002633 if (auto *BORHS =
Alexey Bataev69a47792015-05-07 03:54:03 +00002634 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002635 EExpr = BORHS->getRHS();
2636 BO = BORHS->getOpcode();
2637 }
2638 }
2639 if (XExpr) {
2640 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2641 LValue X = CGF.EmitLValue(XExpr);
2642 RValue E;
2643 if (EExpr)
2644 E = CGF.EmitAnyExpr(EExpr);
2645 CGF.EmitOMPAtomicSimpleUpdateExpr(
2646 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
2647 [&CGF, UpExpr, VD](RValue XRValue) {
2648 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
2649 PrivateScope.addPrivate(
2650 VD, [&CGF, VD, XRValue]() -> llvm::Value *{
2651 auto *LHSTemp = CGF.CreateMemTemp(VD->getType());
2652 CGF.EmitStoreThroughLValue(
2653 XRValue,
2654 CGF.MakeNaturalAlignAddrLValue(LHSTemp, VD->getType()));
2655 return LHSTemp;
2656 });
2657 (void)PrivateScope.Privatize();
2658 return CGF.EmitAnyExpr(UpExpr);
2659 });
2660 } else {
2661 // Emit as a critical region.
2662 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
2663 CGF.EmitIgnoredExpr(E);
2664 }, Loc);
2665 }
2666 ++I;
2667 }
2668 }
2669
2670 CGF.EmitBranch(DefaultBB);
2671 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2672}
2673
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002674void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
2675 SourceLocation Loc) {
2676 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2677 // global_tid);
2678 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2679 // Ignore return result until untied tasks are supported.
2680 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
2681}
2682
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002683void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
2684 const RegionCodeGenTy &CodeGen) {
2685 InlinedOpenMPRegionRAII Region(CGF, CodeGen);
2686 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002687}
2688
Alexey Bataev0f34da12015-07-02 04:17:07 +00002689void CGOpenMPRuntime::emitCancellationPointCall(
2690 CodeGenFunction &CGF, SourceLocation Loc,
2691 OpenMPDirectiveKind CancelRegion) {
2692 // Build call kmp_int32 OMPRTL__kmpc_cancellationpoint(ident_t *loc, kmp_int32
2693 // global_tid, kmp_int32 cncl_kind);
2694 enum {
2695 CancelNoreq = 0,
2696 CancelParallel = 1,
2697 CancelLoop = 2,
2698 CancelSections = 3,
2699 CancelTaskgroup = 4
2700 } CancelKind = CancelNoreq;
2701 if (CancelRegion == OMPD_parallel)
2702 CancelKind = CancelParallel;
2703 else if (CancelRegion == OMPD_for)
2704 CancelKind = CancelLoop;
2705 else if (CancelRegion == OMPD_sections)
2706 CancelKind = CancelSections;
2707 else {
2708 assert(CancelRegion == OMPD_taskgroup);
2709 CancelKind = CancelTaskgroup;
2710 }
2711 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2712 CGF.Builder.getInt32(CancelKind)};
2713 // Ignore return result until untied tasks are supported.
2714 auto *Result = CGF.EmitRuntimeCall(
2715 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
2716 // if (__kmpc_cancellationpoint())
2717 // exit from construct;
2718 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2719 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2720 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2721 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2722 CGF.EmitBlock(ExitBB);
2723 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_taskgroup) {
2724 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
2725 } else {
2726 assert(CancelRegion == OMPD_for || CancelRegion == OMPD_sections);
2727 BreakStmt PseudoBrStmt(Loc);
2728 CGF.EmitBreakStmt(PseudoBrStmt);
2729 }
2730 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2731}
2732