blob: 79900778fdf7bedcee7f5b41b9f42771f6c350fb [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
Alexey Bataev36bf0112015-03-10 05:15:26 +000016#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000017#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000020#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Value.h"
24#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000025#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000026
27using namespace clang;
28using namespace CodeGen;
29
Benjamin Kramerc52193f2014-10-10 13:57:57 +000030namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000031/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000032class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
33public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000034 /// \brief Kinds of OpenMP regions used in codegen.
35 enum CGOpenMPRegionKind {
36 /// \brief Region with outlined function for standalone 'parallel'
37 /// directive.
38 ParallelOutlinedRegion,
39 /// \brief Region with outlined function for standalone 'task' directive.
40 TaskOutlinedRegion,
41 /// \brief Region for constructs that do not require function outlining,
42 /// like 'for', 'sections', 'atomic' etc. directives.
43 InlinedRegion,
44 };
Alexey Bataev18095712014-10-10 12:19:54 +000045
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 CGOpenMPRegionInfo(const CapturedStmt &CS,
47 const CGOpenMPRegionKind RegionKind,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000048 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev81c7ea02015-07-03 09:56:58 +000050 CodeGen(CodeGen), Kind(Kind) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051
52 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind)
54 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
55 Kind(Kind) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000056
57 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000058 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000059 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000060
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000061 /// \brief Emit the captured statement body.
Hans Wennborge89c8c82015-09-10 00:37:18 +000062 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000063
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000065 /// \return LValue for thread id variable. This LValue always has type int32*.
66 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069
Alexey Bataev81c7ea02015-07-03 09:56:58 +000070 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
71
Alexey Bataev18095712014-10-10 12:19:54 +000072 static bool classof(const CGCapturedStmtInfo *Info) {
73 return Info->getKind() == CR_OpenMP;
74 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000076protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000077 CGOpenMPRegionKind RegionKind;
78 const RegionCodeGenTy &CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000079 OpenMPDirectiveKind Kind;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080};
Alexey Bataev18095712014-10-10 12:19:54 +000081
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000082/// \brief API for captured statement code generation in OpenMP constructs.
83class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
84public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000085 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000086 const RegionCodeGenTy &CodeGen,
87 OpenMPDirectiveKind Kind)
88 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000089 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
91 }
92 /// \brief Get a variable or parameter for storing global thread id
93 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +000094 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095
Alexey Bataev18095712014-10-10 12:19:54 +000096 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +000097 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +000098
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000099 static bool classof(const CGCapturedStmtInfo *Info) {
100 return CGOpenMPRegionInfo::classof(Info) &&
101 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
102 ParallelOutlinedRegion;
103 }
104
Alexey Bataev18095712014-10-10 12:19:54 +0000105private:
106 /// \brief A variable or parameter storing global thread id for OpenMP
107 /// constructs.
108 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109};
110
Alexey Bataev62b63b12015-03-10 07:28:44 +0000111/// \brief API for captured statement code generation in OpenMP constructs.
112class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
113public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000115 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000116 const RegionCodeGenTy &CodeGen,
117 OpenMPDirectiveKind Kind)
118 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000119 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000120 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
121 }
122 /// \brief Get a variable or parameter for storing global thread id
123 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000124 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000125
126 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000127 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000128
Alexey Bataev62b63b12015-03-10 07:28:44 +0000129 /// \brief Get the name of the capture helper.
130 StringRef getHelperName() const override { return ".omp_outlined."; }
131
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000132 static bool classof(const CGCapturedStmtInfo *Info) {
133 return CGOpenMPRegionInfo::classof(Info) &&
134 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
135 TaskOutlinedRegion;
136 }
137
Alexey Bataev62b63b12015-03-10 07:28:44 +0000138private:
139 /// \brief A variable or parameter storing global thread id for OpenMP
140 /// constructs.
141 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000142};
143
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000144/// \brief API for inlined captured statement code generation in OpenMP
145/// constructs.
146class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
147public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000148 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000149 const RegionCodeGenTy &CodeGen,
150 OpenMPDirectiveKind Kind)
151 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind), OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000152 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
153 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000154 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000155 if (OuterRegionInfo)
156 return OuterRegionInfo->getContextValue();
157 llvm_unreachable("No context value for inlined OpenMP region");
158 }
Hans Wennborge89c8c82015-09-10 00:37:18 +0000159 virtual void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000160 if (OuterRegionInfo) {
161 OuterRegionInfo->setContextValue(V);
162 return;
163 }
164 llvm_unreachable("No context value for inlined OpenMP region");
165 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000166 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000167 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000168 if (OuterRegionInfo)
169 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000170 // If there is no outer outlined region,no need to lookup in a list of
171 // captured variables, we can use the original one.
172 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000173 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000174 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000175 if (OuterRegionInfo)
176 return OuterRegionInfo->getThisFieldDecl();
177 return nullptr;
178 }
179 /// \brief Get a variable or parameter for storing global thread id
180 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000181 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000182 if (OuterRegionInfo)
183 return OuterRegionInfo->getThreadIDVariable();
184 return nullptr;
185 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000186
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000187 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000188 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000189 if (auto *OuterRegionInfo = getOldCSI())
190 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000191 llvm_unreachable("No helper name for inlined OpenMP construct");
192 }
193
194 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
195
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000196 static bool classof(const CGCapturedStmtInfo *Info) {
197 return CGOpenMPRegionInfo::classof(Info) &&
198 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
199 }
200
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000201private:
202 /// \brief CodeGen info about outer OpenMP region.
203 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
204 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000205};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000206
207/// \brief RAII for emitting code of OpenMP constructs.
208class InlinedOpenMPRegionRAII {
209 CodeGenFunction &CGF;
210
211public:
212 /// \brief Constructs region for combined constructs.
213 /// \param CodeGen Code generation sequence for combined directives. Includes
214 /// a list of functions used for code generation of implicitly inlined
215 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000216 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
217 OpenMPDirectiveKind Kind)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000218 : CGF(CGF) {
219 // Start emission for the construct.
220 CGF.CapturedStmtInfo =
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000221 new CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, CodeGen, Kind);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000222 }
223 ~InlinedOpenMPRegionRAII() {
224 // Restore original CapturedStmtInfo only if we're done with code emission.
225 auto *OldCSI =
226 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
227 delete CGF.CapturedStmtInfo;
228 CGF.CapturedStmtInfo = OldCSI;
229 }
230};
231
Hans Wennborge89c8c82015-09-10 00:37:18 +0000232} // namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000233
Alexey Bataev2377fe92015-09-10 08:12:02 +0000234static LValue emitLoadOfPointerLValue(CodeGenFunction &CGF, Address PtrAddr,
235 QualType Ty) {
236 AlignmentSource Source;
237 CharUnits Align = CGF.getNaturalPointeeTypeAlignment(Ty, &Source);
238 return CGF.MakeAddrLValue(Address(CGF.Builder.CreateLoad(PtrAddr), Align),
239 Ty->getPointeeType(), Source);
240}
241
Alexey Bataev18095712014-10-10 12:19:54 +0000242LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000243 return emitLoadOfPointerLValue(CGF,
244 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
245 getThreadIDVariable()->getType());
Alexey Bataev18095712014-10-10 12:19:54 +0000246}
247
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000248void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
249 // 1.2.2 OpenMP Language Terminology
250 // Structured block - An executable statement with a single entry at the
251 // top and a single exit at the bottom.
252 // The point of exit cannot be a branch out of the structured block.
253 // longjmp() and throw() must not violate the entry/exit criteria.
254 CGF.EHStack.pushTerminate();
255 {
256 CodeGenFunction::RunCleanupsScope Scope(CGF);
257 CodeGen(CGF);
258 }
259 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000260}
261
Alexey Bataev62b63b12015-03-10 07:28:44 +0000262LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
263 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000264 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
265 getThreadIDVariable()->getType(),
266 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267}
268
Alexey Bataev9959db52014-05-06 10:08:46 +0000269CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000270 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000271 IdentTy = llvm::StructType::create(
272 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
273 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000274 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000275 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000276 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
277 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000278 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000279 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000280}
281
Alexey Bataev91797552015-03-18 04:13:55 +0000282void CGOpenMPRuntime::clear() {
283 InternalVars.clear();
284}
285
John McCall7f416cc2015-09-08 08:05:57 +0000286// Layout information for ident_t.
287static CharUnits getIdentAlign(CodeGenModule &CGM) {
288 return CGM.getPointerAlign();
289}
290static CharUnits getIdentSize(CodeGenModule &CGM) {
291 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
292 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
293}
294static CharUnits getOffsetOfIdentField(CGOpenMPRuntime::IdentFieldIndex Field) {
295 // All the fields except the last are i32, so this works beautifully.
296 return unsigned(Field) * CharUnits::fromQuantity(4);
297}
298static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
299 CGOpenMPRuntime::IdentFieldIndex Field,
300 const llvm::Twine &Name = "") {
301 auto Offset = getOffsetOfIdentField(Field);
302 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
303}
304
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000305llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
306 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
307 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000308 assert(ThreadIDVar->getType()->isPointerType() &&
309 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000310 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
311 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000312 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind);
Alexey Bataevd157d472015-06-24 03:35:38 +0000313 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000314 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000315}
316
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000317llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
318 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
319 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000320 assert(!ThreadIDVar->getType()->isPointerType() &&
321 "thread id variable must be of type kmp_int32 for tasks");
322 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
323 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000324 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
325 InnermostKind);
Alexey Bataevd157d472015-06-24 03:35:38 +0000326 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000327 return CGF.GenerateCapturedStmtFunction(*CS);
328}
329
John McCall7f416cc2015-09-08 08:05:57 +0000330Address CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
331 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000332 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000333 if (!Entry) {
334 if (!DefaultOpenMPPSource) {
335 // Initialize default location for psource field of ident_t structure of
336 // all ident_t objects. Format is ";file;function;line;column;;".
337 // Taken from
338 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
339 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000340 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000341 DefaultOpenMPPSource =
342 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
343 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000344 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
345 CGM.getModule(), IdentTy, /*isConstant*/ true,
346 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000347 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000348 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000349
350 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000351 llvm::Constant *Values[] = {Zero,
352 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
353 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000354 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
355 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000356 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000357 }
John McCall7f416cc2015-09-08 08:05:57 +0000358 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000359}
360
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000361llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
362 SourceLocation Loc,
363 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000364 // If no debug info is generated - return global default location.
365 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
366 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000367 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000368
369 assert(CGF.CurFn && "No function in current CodeGenFunction.");
370
John McCall7f416cc2015-09-08 08:05:57 +0000371 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000372 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
373 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000374 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
375
Alexander Musmanc6388682014-12-15 07:07:06 +0000376 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
377 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000378 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000379 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000380 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
381 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000382 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000383 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000384 LocValue = AI;
385
386 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
387 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000388 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000389 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000390 }
391
392 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000393 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000394
Alexey Bataevf002aca2014-05-30 05:48:40 +0000395 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
396 if (OMPDebugLoc == nullptr) {
397 SmallString<128> Buffer2;
398 llvm::raw_svector_ostream OS2(Buffer2);
399 // Build debug location
400 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
401 OS2 << ";" << PLoc.getFilename() << ";";
402 if (const FunctionDecl *FD =
403 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
404 OS2 << FD->getQualifiedNameAsString();
405 }
406 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
407 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
408 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000409 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000410 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000411 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
412
John McCall7f416cc2015-09-08 08:05:57 +0000413 // Our callers always pass this to a runtime function, so for
414 // convenience, go ahead and return a naked pointer.
415 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000416}
417
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000418llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
419 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000420 assert(CGF.CurFn && "No function in current CodeGenFunction.");
421
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000422 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000423 // Check whether we've already cached a load of the thread id in this
424 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000425 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000426 if (I != OpenMPLocThreadIDMap.end()) {
427 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000428 if (ThreadID != nullptr)
429 return ThreadID;
430 }
431 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000432 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000433 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000434 // Check if this an outlined function with thread id passed as argument.
435 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000436 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
437 // If value loaded in entry block, cache it and use it everywhere in
438 // function.
439 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
440 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
441 Elem.second.ThreadID = ThreadID;
442 }
443 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000444 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000445 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000446
447 // This is not an outlined function region - need to call __kmpc_int32
448 // kmpc_global_thread_num(ident_t *loc).
449 // Generate thread id value and cache this value for use across the
450 // function.
451 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
452 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
453 ThreadID =
454 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
455 emitUpdateLocation(CGF, Loc));
456 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
457 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000458 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000459}
460
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000461void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000462 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000463 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
464 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000465}
466
467llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
468 return llvm::PointerType::getUnqual(IdentTy);
469}
470
471llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
472 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
473}
474
475llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000476CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000477 llvm::Constant *RTLFn = nullptr;
478 switch (Function) {
479 case OMPRTL__kmpc_fork_call: {
480 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
481 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000482 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
483 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000484 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000485 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000486 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
487 break;
488 }
489 case OMPRTL__kmpc_global_thread_num: {
490 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000491 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000492 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000493 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000494 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
495 break;
496 }
Alexey Bataev97720002014-11-11 04:05:39 +0000497 case OMPRTL__kmpc_threadprivate_cached: {
498 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
499 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
500 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
501 CGM.VoidPtrTy, CGM.SizeTy,
502 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
503 llvm::FunctionType *FnTy =
504 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
505 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
506 break;
507 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000508 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000509 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
510 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000511 llvm::Type *TypeParams[] = {
512 getIdentTyPointerTy(), CGM.Int32Ty,
513 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
514 llvm::FunctionType *FnTy =
515 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
516 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
517 break;
518 }
Alexey Bataev97720002014-11-11 04:05:39 +0000519 case OMPRTL__kmpc_threadprivate_register: {
520 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
521 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
522 // typedef void *(*kmpc_ctor)(void *);
523 auto KmpcCtorTy =
524 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
525 /*isVarArg*/ false)->getPointerTo();
526 // typedef void *(*kmpc_cctor)(void *, void *);
527 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
528 auto KmpcCopyCtorTy =
529 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
530 /*isVarArg*/ false)->getPointerTo();
531 // typedef void (*kmpc_dtor)(void *);
532 auto KmpcDtorTy =
533 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
534 ->getPointerTo();
535 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
536 KmpcCopyCtorTy, KmpcDtorTy};
537 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
538 /*isVarArg*/ false);
539 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
540 break;
541 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000542 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000543 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
544 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000545 llvm::Type *TypeParams[] = {
546 getIdentTyPointerTy(), CGM.Int32Ty,
547 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
548 llvm::FunctionType *FnTy =
549 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
550 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
551 break;
552 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000553 case OMPRTL__kmpc_cancel_barrier: {
554 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
555 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000556 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
557 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000558 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
559 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000560 break;
561 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000562 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000563 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000564 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
565 llvm::FunctionType *FnTy =
566 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
567 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
568 break;
569 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000570 case OMPRTL__kmpc_for_static_fini: {
571 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
572 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
573 llvm::FunctionType *FnTy =
574 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
575 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
576 break;
577 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000578 case OMPRTL__kmpc_push_num_threads: {
579 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
580 // kmp_int32 num_threads)
581 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
582 CGM.Int32Ty};
583 llvm::FunctionType *FnTy =
584 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
585 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
586 break;
587 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000588 case OMPRTL__kmpc_serialized_parallel: {
589 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
590 // global_tid);
591 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
592 llvm::FunctionType *FnTy =
593 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
594 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
595 break;
596 }
597 case OMPRTL__kmpc_end_serialized_parallel: {
598 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
599 // global_tid);
600 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
601 llvm::FunctionType *FnTy =
602 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
603 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
604 break;
605 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000606 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000607 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000608 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
609 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000610 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000611 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
612 break;
613 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000614 case OMPRTL__kmpc_master: {
615 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
616 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
617 llvm::FunctionType *FnTy =
618 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
619 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
620 break;
621 }
622 case OMPRTL__kmpc_end_master: {
623 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
624 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
625 llvm::FunctionType *FnTy =
626 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
627 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
628 break;
629 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000630 case OMPRTL__kmpc_omp_taskyield: {
631 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
632 // int end_part);
633 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
634 llvm::FunctionType *FnTy =
635 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
636 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
637 break;
638 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000639 case OMPRTL__kmpc_single: {
640 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
641 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
642 llvm::FunctionType *FnTy =
643 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
644 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
645 break;
646 }
647 case OMPRTL__kmpc_end_single: {
648 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
650 llvm::FunctionType *FnTy =
651 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
652 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
653 break;
654 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000655 case OMPRTL__kmpc_omp_task_alloc: {
656 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
657 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
658 // kmp_routine_entry_t *task_entry);
659 assert(KmpRoutineEntryPtrTy != nullptr &&
660 "Type kmp_routine_entry_t must be created.");
661 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
662 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
663 // Return void * and then cast to particular kmp_task_t type.
664 llvm::FunctionType *FnTy =
665 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
666 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
667 break;
668 }
669 case OMPRTL__kmpc_omp_task: {
670 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
671 // *new_task);
672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
673 CGM.VoidPtrTy};
674 llvm::FunctionType *FnTy =
675 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
676 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
677 break;
678 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000679 case OMPRTL__kmpc_copyprivate: {
680 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +0000681 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +0000682 // kmp_int32 didit);
683 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
684 auto *CpyFnTy =
685 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +0000686 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +0000687 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
688 CGM.Int32Ty};
689 llvm::FunctionType *FnTy =
690 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
691 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
692 break;
693 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000694 case OMPRTL__kmpc_reduce: {
695 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
696 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
697 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
698 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
699 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
700 /*isVarArg=*/false);
701 llvm::Type *TypeParams[] = {
702 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
703 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
704 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
705 llvm::FunctionType *FnTy =
706 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
707 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
708 break;
709 }
710 case OMPRTL__kmpc_reduce_nowait: {
711 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
712 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
713 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
714 // *lck);
715 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
716 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
717 /*isVarArg=*/false);
718 llvm::Type *TypeParams[] = {
719 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
720 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
721 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
722 llvm::FunctionType *FnTy =
723 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
724 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
725 break;
726 }
727 case OMPRTL__kmpc_end_reduce: {
728 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
729 // kmp_critical_name *lck);
730 llvm::Type *TypeParams[] = {
731 getIdentTyPointerTy(), CGM.Int32Ty,
732 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
733 llvm::FunctionType *FnTy =
734 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
735 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
736 break;
737 }
738 case OMPRTL__kmpc_end_reduce_nowait: {
739 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
740 // kmp_critical_name *lck);
741 llvm::Type *TypeParams[] = {
742 getIdentTyPointerTy(), CGM.Int32Ty,
743 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
744 llvm::FunctionType *FnTy =
745 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
746 RTLFn =
747 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
748 break;
749 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000750 case OMPRTL__kmpc_omp_task_begin_if0: {
751 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
752 // *new_task);
753 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
754 CGM.VoidPtrTy};
755 llvm::FunctionType *FnTy =
756 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
757 RTLFn =
758 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
759 break;
760 }
761 case OMPRTL__kmpc_omp_task_complete_if0: {
762 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
763 // *new_task);
764 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
765 CGM.VoidPtrTy};
766 llvm::FunctionType *FnTy =
767 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
768 RTLFn = CGM.CreateRuntimeFunction(FnTy,
769 /*Name=*/"__kmpc_omp_task_complete_if0");
770 break;
771 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000772 case OMPRTL__kmpc_ordered: {
773 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
775 llvm::FunctionType *FnTy =
776 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
777 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
778 break;
779 }
780 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000781 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
783 llvm::FunctionType *FnTy =
784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
785 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
786 break;
787 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +0000788 case OMPRTL__kmpc_omp_taskwait: {
789 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
790 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
791 llvm::FunctionType *FnTy =
792 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
793 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
794 break;
795 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000796 case OMPRTL__kmpc_taskgroup: {
797 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
798 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
799 llvm::FunctionType *FnTy =
800 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
801 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
802 break;
803 }
804 case OMPRTL__kmpc_end_taskgroup: {
805 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
806 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
807 llvm::FunctionType *FnTy =
808 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
809 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
810 break;
811 }
Alexey Bataev7f210c62015-06-18 13:40:03 +0000812 case OMPRTL__kmpc_push_proc_bind: {
813 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
814 // int proc_bind)
815 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
816 llvm::FunctionType *FnTy =
817 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
818 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
819 break;
820 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +0000821 case OMPRTL__kmpc_omp_task_with_deps: {
822 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
823 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
824 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
825 llvm::Type *TypeParams[] = {
826 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
827 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
828 llvm::FunctionType *FnTy =
829 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
830 RTLFn =
831 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
832 break;
833 }
834 case OMPRTL__kmpc_omp_wait_deps: {
835 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
836 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
837 // kmp_depend_info_t *noalias_dep_list);
838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
839 CGM.Int32Ty, CGM.VoidPtrTy,
840 CGM.Int32Ty, CGM.VoidPtrTy};
841 llvm::FunctionType *FnTy =
842 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
843 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
844 break;
845 }
Alexey Bataev0f34da12015-07-02 04:17:07 +0000846 case OMPRTL__kmpc_cancellationpoint: {
847 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
848 // global_tid, kmp_int32 cncl_kind)
849 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
850 llvm::FunctionType *FnTy =
851 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
852 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
853 break;
854 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000855 case OMPRTL__kmpc_cancel: {
856 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
857 // kmp_int32 cncl_kind)
858 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
859 llvm::FunctionType *FnTy =
860 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
861 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
862 break;
863 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000864 }
865 return RTLFn;
866}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000867
Alexander Musman21212e42015-03-13 10:38:23 +0000868llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
869 bool IVSigned) {
870 assert((IVSize == 32 || IVSize == 64) &&
871 "IV size is not compatible with the omp runtime");
872 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
873 : "__kmpc_for_static_init_4u")
874 : (IVSigned ? "__kmpc_for_static_init_8"
875 : "__kmpc_for_static_init_8u");
876 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
877 auto PtrTy = llvm::PointerType::getUnqual(ITy);
878 llvm::Type *TypeParams[] = {
879 getIdentTyPointerTy(), // loc
880 CGM.Int32Ty, // tid
881 CGM.Int32Ty, // schedtype
882 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
883 PtrTy, // p_lower
884 PtrTy, // p_upper
885 PtrTy, // p_stride
886 ITy, // incr
887 ITy // chunk
888 };
889 llvm::FunctionType *FnTy =
890 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
891 return CGM.CreateRuntimeFunction(FnTy, Name);
892}
893
Alexander Musman92bdaab2015-03-12 13:37:50 +0000894llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
895 bool IVSigned) {
896 assert((IVSize == 32 || IVSize == 64) &&
897 "IV size is not compatible with the omp runtime");
898 auto Name =
899 IVSize == 32
900 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
901 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
902 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
903 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
904 CGM.Int32Ty, // tid
905 CGM.Int32Ty, // schedtype
906 ITy, // lower
907 ITy, // upper
908 ITy, // stride
909 ITy // chunk
910 };
911 llvm::FunctionType *FnTy =
912 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
913 return CGM.CreateRuntimeFunction(FnTy, Name);
914}
915
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000916llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
917 bool IVSigned) {
918 assert((IVSize == 32 || IVSize == 64) &&
919 "IV size is not compatible with the omp runtime");
920 auto Name =
921 IVSize == 32
922 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
923 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
924 llvm::Type *TypeParams[] = {
925 getIdentTyPointerTy(), // loc
926 CGM.Int32Ty, // tid
927 };
928 llvm::FunctionType *FnTy =
929 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
930 return CGM.CreateRuntimeFunction(FnTy, Name);
931}
932
Alexander Musman92bdaab2015-03-12 13:37:50 +0000933llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
934 bool IVSigned) {
935 assert((IVSize == 32 || IVSize == 64) &&
936 "IV size is not compatible with the omp runtime");
937 auto Name =
938 IVSize == 32
939 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
940 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
941 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
942 auto PtrTy = llvm::PointerType::getUnqual(ITy);
943 llvm::Type *TypeParams[] = {
944 getIdentTyPointerTy(), // loc
945 CGM.Int32Ty, // tid
946 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
947 PtrTy, // p_lower
948 PtrTy, // p_upper
949 PtrTy // p_stride
950 };
951 llvm::FunctionType *FnTy =
952 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
953 return CGM.CreateRuntimeFunction(FnTy, Name);
954}
955
Alexey Bataev97720002014-11-11 04:05:39 +0000956llvm::Constant *
957CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +0000958 assert(!CGM.getLangOpts().OpenMPUseTLS ||
959 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +0000960 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000961 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000962 Twine(CGM.getMangledName(VD)) + ".cache.");
963}
964
John McCall7f416cc2015-09-08 08:05:57 +0000965Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
966 const VarDecl *VD,
967 Address VDAddr,
968 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +0000969 if (CGM.getLangOpts().OpenMPUseTLS &&
970 CGM.getContext().getTargetInfo().isTLSSupported())
971 return VDAddr;
972
John McCall7f416cc2015-09-08 08:05:57 +0000973 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000974 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +0000975 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
976 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +0000977 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
978 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +0000979 return Address(CGF.EmitRuntimeCall(
980 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
981 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +0000982}
983
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000984void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +0000985 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +0000986 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
987 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
988 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000989 auto OMPLoc = emitUpdateLocation(CGF, Loc);
990 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000991 OMPLoc);
992 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
993 // to register constructor/destructor for variable.
994 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +0000995 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
996 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +0000997 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000998 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000999 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001000}
1001
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001002llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001003 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001004 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001005 if (CGM.getLangOpts().OpenMPUseTLS &&
1006 CGM.getContext().getTargetInfo().isTLSSupported())
1007 return nullptr;
1008
Alexey Bataev97720002014-11-11 04:05:39 +00001009 VD = VD->getDefinition(CGM.getContext());
1010 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1011 ThreadPrivateWithDefinition.insert(VD);
1012 QualType ASTTy = VD->getType();
1013
1014 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1015 auto Init = VD->getAnyInitializer();
1016 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1017 // Generate function that re-emits the declaration's initializer into the
1018 // threadprivate copy of the variable VD
1019 CodeGenFunction CtorCGF(CGM);
1020 FunctionArgList Args;
1021 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1022 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1023 Args.push_back(&Dst);
1024
1025 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1026 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
1027 /*isVariadic=*/false);
1028 auto FTy = CGM.getTypes().GetFunctionType(FI);
1029 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1030 FTy, ".__kmpc_global_ctor_.", Loc);
1031 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1032 Args, SourceLocation());
1033 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001034 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001035 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001036 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1037 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1038 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001039 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1040 /*IsInitializer=*/true);
1041 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001042 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001043 CGM.getContext().VoidPtrTy, Dst.getLocation());
1044 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1045 CtorCGF.FinishFunction();
1046 Ctor = Fn;
1047 }
1048 if (VD->getType().isDestructedType() != QualType::DK_none) {
1049 // Generate function that emits destructor call for the threadprivate copy
1050 // of the variable VD
1051 CodeGenFunction DtorCGF(CGM);
1052 FunctionArgList Args;
1053 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1054 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1055 Args.push_back(&Dst);
1056
1057 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1058 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1059 /*isVariadic=*/false);
1060 auto FTy = CGM.getTypes().GetFunctionType(FI);
1061 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1062 FTy, ".__kmpc_global_dtor_.", Loc);
1063 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1064 SourceLocation());
1065 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1066 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001067 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1068 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001069 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1070 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1071 DtorCGF.FinishFunction();
1072 Dtor = Fn;
1073 }
1074 // Do not emit init function if it is not required.
1075 if (!Ctor && !Dtor)
1076 return nullptr;
1077
1078 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1079 auto CopyCtorTy =
1080 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1081 /*isVarArg=*/false)->getPointerTo();
1082 // Copying constructor for the threadprivate variable.
1083 // Must be NULL - reserved by runtime, but currently it requires that this
1084 // parameter is always NULL. Otherwise it fires assertion.
1085 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1086 if (Ctor == nullptr) {
1087 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1088 /*isVarArg=*/false)->getPointerTo();
1089 Ctor = llvm::Constant::getNullValue(CtorTy);
1090 }
1091 if (Dtor == nullptr) {
1092 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1093 /*isVarArg=*/false)->getPointerTo();
1094 Dtor = llvm::Constant::getNullValue(DtorTy);
1095 }
1096 if (!CGF) {
1097 auto InitFunctionTy =
1098 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1099 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1100 InitFunctionTy, ".__omp_threadprivate_init_.");
1101 CodeGenFunction InitCGF(CGM);
1102 FunctionArgList ArgList;
1103 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1104 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1105 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001106 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001107 InitCGF.FinishFunction();
1108 return InitFunction;
1109 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001110 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001111 }
1112 return nullptr;
1113}
1114
Alexey Bataev1d677132015-04-22 13:57:31 +00001115/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1116/// function. Here is the logic:
1117/// if (Cond) {
1118/// ThenGen();
1119/// } else {
1120/// ElseGen();
1121/// }
1122static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1123 const RegionCodeGenTy &ThenGen,
1124 const RegionCodeGenTy &ElseGen) {
1125 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1126
1127 // If the condition constant folds and can be elided, try to avoid emitting
1128 // the condition and the dead arm of the if/else.
1129 bool CondConstant;
1130 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1131 CodeGenFunction::RunCleanupsScope Scope(CGF);
1132 if (CondConstant) {
1133 ThenGen(CGF);
1134 } else {
1135 ElseGen(CGF);
1136 }
1137 return;
1138 }
1139
1140 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1141 // emit the conditional branch.
1142 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1143 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1144 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1145 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1146
1147 // Emit the 'then' code.
1148 CGF.EmitBlock(ThenBlock);
1149 {
1150 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1151 ThenGen(CGF);
1152 }
1153 CGF.EmitBranch(ContBlock);
1154 // Emit the 'else' code if present.
1155 {
1156 // There is no need to emit line number for unconditional branch.
1157 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1158 CGF.EmitBlock(ElseBlock);
1159 }
1160 {
1161 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1162 ElseGen(CGF);
1163 }
1164 {
1165 // There is no need to emit line number for unconditional branch.
1166 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1167 CGF.EmitBranch(ContBlock);
1168 }
1169 // Emit the continuation block for code after the if.
1170 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001171}
1172
Alexey Bataev1d677132015-04-22 13:57:31 +00001173void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1174 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001175 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001176 const Expr *IfCond) {
1177 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001178 auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1179 RTLoc](CodeGenFunction &CGF) {
1180 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1181 llvm::Value *Args[] = {
1182 RTLoc,
1183 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1184 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1185 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1186 RealArgs.append(std::begin(Args), std::end(Args));
1187 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1188
1189 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1190 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1191 };
1192 auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1193 Loc](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001194 auto ThreadID = getThreadID(CGF, Loc);
1195 // Build calls:
1196 // __kmpc_serialized_parallel(&Loc, GTid);
1197 llvm::Value *Args[] = {RTLoc, ThreadID};
1198 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1199 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001200
Alexey Bataev1d677132015-04-22 13:57:31 +00001201 // OutlinedFn(&GTid, &zero, CapturedStruct);
1202 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001203 Address ZeroAddr =
1204 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1205 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001206 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001207 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1208 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1209 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1210 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001211 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001212
Alexey Bataev1d677132015-04-22 13:57:31 +00001213 // __kmpc_end_serialized_parallel(&Loc, GTid);
1214 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1215 CGF.EmitRuntimeCall(
1216 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1217 };
1218 if (IfCond) {
1219 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1220 } else {
1221 CodeGenFunction::RunCleanupsScope Scope(CGF);
1222 ThenGen(CGF);
1223 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001224}
1225
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001226// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001227// thread-ID variable (it is passed in a first argument of the outlined function
1228// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1229// regular serial code region, get thread ID by calling kmp_int32
1230// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1231// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001232Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1233 SourceLocation Loc) {
Alexey Bataevd74d0602014-10-13 06:02:40 +00001234 if (auto OMPRegionInfo =
1235 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001236 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001237 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001238
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001239 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001240 auto Int32Ty =
1241 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1242 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1243 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001244 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001245
1246 return ThreadIDTemp;
1247}
1248
Alexey Bataev97720002014-11-11 04:05:39 +00001249llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001250CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001251 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001252 SmallString<256> Buffer;
1253 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001254 Out << Name;
1255 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001256 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1257 if (Elem.second) {
1258 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001259 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001260 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001261 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001262
David Blaikie13156b62014-11-19 03:06:06 +00001263 return Elem.second = new llvm::GlobalVariable(
1264 CGM.getModule(), Ty, /*IsConstant*/ false,
1265 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1266 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001267}
1268
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001269llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001270 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001271 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001272}
1273
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001274namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001275template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001276 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001277 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001278
1279public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001280 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1281 : Callee(Callee) {
1282 assert(CleanupArgs.size() == N);
1283 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1284 }
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001285 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1286 CGF.EmitRuntimeCall(Callee, Args);
1287 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001288};
Hans Wennborge89c8c82015-09-10 00:37:18 +00001289} // namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001290
1291void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1292 StringRef CriticalName,
1293 const RegionCodeGenTy &CriticalOpGen,
1294 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001295 // __kmpc_critical(ident_t *, gtid, Lock);
1296 // CriticalOpGen();
1297 // __kmpc_end_critical(ident_t *, gtid, Lock);
1298 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001299 {
1300 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001301 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1302 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001303 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001304 // Build a call to __kmpc_end_critical
Alexey Bataeva744ff52015-05-05 09:24:37 +00001305 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001306 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1307 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001308 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001309 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001310}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001311
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001312static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001313 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001314 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001315 llvm::Value *CallBool = CGF.EmitScalarConversion(
1316 IfCond,
1317 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001318 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001319
1320 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1321 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1322 // Generate the branch (If-stmt)
1323 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1324 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001325 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001326 // Emit the rest of bblocks/branches
1327 CGF.EmitBranch(ContBlock);
1328 CGF.EmitBlock(ContBlock, true);
1329}
1330
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001331void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001332 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001333 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001334 // if(__kmpc_master(ident_t *, gtid)) {
1335 // MasterOpGen();
1336 // __kmpc_end_master(ident_t *, gtid);
1337 // }
1338 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001339 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001340 auto *IsMaster =
1341 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001342 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1343 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001344 emitIfStmt(
1345 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1346 CodeGenFunction::RunCleanupsScope Scope(CGF);
1347 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1348 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1349 llvm::makeArrayRef(Args));
1350 MasterOpGen(CGF);
1351 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001352}
1353
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001354void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1355 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001356 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1357 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001358 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001359 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001360 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001361}
1362
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001363void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1364 const RegionCodeGenTy &TaskgroupOpGen,
1365 SourceLocation Loc) {
1366 // __kmpc_taskgroup(ident_t *, gtid);
1367 // TaskgroupOpGen();
1368 // __kmpc_end_taskgroup(ident_t *, gtid);
1369 // Prepare arguments and build a call to __kmpc_taskgroup
1370 {
1371 CodeGenFunction::RunCleanupsScope Scope(CGF);
1372 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1373 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1374 // Build a call to __kmpc_end_taskgroup
1375 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1376 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1377 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001378 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001379 }
1380}
1381
John McCall7f416cc2015-09-08 08:05:57 +00001382/// Given an array of pointers to variables, project the address of a
1383/// given variable.
1384static Address emitAddrOfVarFromArray(CodeGenFunction &CGF,
1385 Address Array, unsigned Index,
1386 const VarDecl *Var) {
1387 // Pull out the pointer to the variable.
1388 Address PtrAddr =
1389 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
1390 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1391
1392 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
1393 Addr = CGF.Builder.CreateElementBitCast(Addr,
1394 CGF.ConvertTypeForMem(Var->getType()));
1395 return Addr;
1396}
1397
Alexey Bataeva63048e2015-03-23 06:18:07 +00001398static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001399 CodeGenModule &CGM, llvm::Type *ArgsType,
1400 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1401 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001402 auto &C = CGM.getContext();
1403 // void copy_func(void *LHSArg, void *RHSArg);
1404 FunctionArgList Args;
1405 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1406 C.VoidPtrTy);
1407 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1408 C.VoidPtrTy);
1409 Args.push_back(&LHSArg);
1410 Args.push_back(&RHSArg);
1411 FunctionType::ExtInfo EI;
1412 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1413 C.VoidTy, Args, EI, /*isVariadic=*/false);
1414 auto *Fn = llvm::Function::Create(
1415 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1416 ".omp.copyprivate.copy_func", &CGM.getModule());
1417 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1418 CodeGenFunction CGF(CGM);
1419 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001420 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001421 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001422 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1423 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1424 ArgsType), CGF.getPointerAlign());
1425 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1426 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1427 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001428 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1429 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1430 // ...
1431 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001432 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001433 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1434 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1435
1436 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1437 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1438
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001439 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1440 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001441 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001442 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001443 CGF.FinishFunction();
1444 return Fn;
1445}
1446
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001447void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001448 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001449 SourceLocation Loc,
1450 ArrayRef<const Expr *> CopyprivateVars,
1451 ArrayRef<const Expr *> SrcExprs,
1452 ArrayRef<const Expr *> DstExprs,
1453 ArrayRef<const Expr *> AssignmentOps) {
1454 assert(CopyprivateVars.size() == SrcExprs.size() &&
1455 CopyprivateVars.size() == DstExprs.size() &&
1456 CopyprivateVars.size() == AssignmentOps.size());
1457 auto &C = CGM.getContext();
1458 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001459 // if(__kmpc_single(ident_t *, gtid)) {
1460 // SingleOpGen();
1461 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001462 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001463 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001464 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1465 // <copy_func>, did_it);
1466
John McCall7f416cc2015-09-08 08:05:57 +00001467 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001468 if (!CopyprivateVars.empty()) {
1469 // int32 did_it = 0;
1470 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1471 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00001472 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001473 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001474 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001475 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001476 auto *IsSingle =
1477 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001478 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1479 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001480 emitIfStmt(
1481 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
1482 CodeGenFunction::RunCleanupsScope Scope(CGF);
1483 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
1484 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1485 llvm::makeArrayRef(Args));
1486 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001487 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001488 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00001489 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001490 }
1491 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001492 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1493 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00001494 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001495 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1496 auto CopyprivateArrayTy =
1497 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1498 /*IndexTypeQuals=*/0);
1499 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00001500 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001501 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1502 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001503 Address Elem = CGF.Builder.CreateConstArrayGEP(
1504 CopyprivateList, I, CGF.getPointerSize());
1505 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00001506 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00001507 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
1508 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001509 }
1510 // Build function that copies private values from single region to all other
1511 // threads in the corresponding parallel region.
1512 auto *CpyFn = emitCopyprivateCopyFunction(
1513 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001514 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001515 auto *BufSize = llvm::ConstantInt::get(
1516 CGM.SizeTy, C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00001517 Address CL =
1518 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1519 CGF.VoidPtrTy);
1520 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001521 llvm::Value *Args[] = {
1522 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1523 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001524 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00001525 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001526 CpyFn, // void (*) (void *, void *) <copy_func>
1527 DidItVal // i32 did_it
1528 };
1529 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1530 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001531}
1532
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001533void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1534 const RegionCodeGenTy &OrderedOpGen,
1535 SourceLocation Loc) {
1536 // __kmpc_ordered(ident_t *, gtid);
1537 // OrderedOpGen();
1538 // __kmpc_end_ordered(ident_t *, gtid);
1539 // Prepare arguments and build a call to __kmpc_ordered
1540 {
1541 CodeGenFunction::RunCleanupsScope Scope(CGF);
1542 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1543 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1544 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001545 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001546 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1547 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001548 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001549 }
1550}
1551
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001552void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001553 OpenMPDirectiveKind Kind,
1554 bool CheckForCancel) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001555 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001556 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001557 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1558 if (Kind == OMPD_for) {
1559 Flags =
1560 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1561 } else if (Kind == OMPD_sections) {
1562 Flags = static_cast<OpenMPLocationFlags>(Flags |
1563 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1564 } else if (Kind == OMPD_single) {
1565 Flags =
1566 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1567 } else if (Kind == OMPD_barrier) {
1568 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1569 } else {
1570 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1571 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001572 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
1573 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001574 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1575 getThreadID(CGF, Loc)};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001576 if (auto *OMPRegionInfo =
1577 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1578 auto CancelDestination =
1579 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
1580 if (CancelDestination.isValid()) {
1581 auto *Result = CGF.EmitRuntimeCall(
1582 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
1583 if (CheckForCancel) {
1584 // if (__kmpc_cancel_barrier()) {
1585 // exit from construct;
1586 // }
1587 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
1588 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
1589 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
1590 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
1591 CGF.EmitBlock(ExitBB);
1592 // exit from construct;
1593 CGF.EmitBranchThroughCleanup(CancelDestination);
1594 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
1595 }
1596 return;
1597 }
1598 }
1599 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001600}
1601
Alexander Musmanc6388682014-12-15 07:07:06 +00001602/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1603/// the enum sched_type in kmp.h).
1604enum OpenMPSchedType {
1605 /// \brief Lower bound for default (unordered) versions.
1606 OMP_sch_lower = 32,
1607 OMP_sch_static_chunked = 33,
1608 OMP_sch_static = 34,
1609 OMP_sch_dynamic_chunked = 35,
1610 OMP_sch_guided_chunked = 36,
1611 OMP_sch_runtime = 37,
1612 OMP_sch_auto = 38,
1613 /// \brief Lower bound for 'ordered' versions.
1614 OMP_ord_lower = 64,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001615 OMP_ord_static_chunked = 65,
1616 OMP_ord_static = 66,
1617 OMP_ord_dynamic_chunked = 67,
1618 OMP_ord_guided_chunked = 68,
1619 OMP_ord_runtime = 69,
1620 OMP_ord_auto = 70,
1621 OMP_sch_default = OMP_sch_static,
Alexander Musmanc6388682014-12-15 07:07:06 +00001622};
1623
1624/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1625static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001626 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001627 switch (ScheduleKind) {
1628 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001629 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
1630 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00001631 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001632 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001633 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001634 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001635 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001636 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
1637 case OMPC_SCHEDULE_auto:
1638 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00001639 case OMPC_SCHEDULE_unknown:
1640 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001641 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00001642 }
1643 llvm_unreachable("Unexpected runtime schedule");
1644}
1645
1646bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1647 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001648 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00001649 return Schedule == OMP_sch_static;
1650}
1651
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001652bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001653 auto Schedule =
1654 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001655 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1656 return Schedule != OMP_sch_static;
1657}
1658
John McCall7f416cc2015-09-08 08:05:57 +00001659void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
1660 SourceLocation Loc,
1661 OpenMPScheduleClauseKind ScheduleKind,
1662 unsigned IVSize, bool IVSigned,
1663 bool Ordered, llvm::Value *UB,
1664 llvm::Value *Chunk) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001665 OpenMPSchedType Schedule =
1666 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00001667 assert(Ordered ||
1668 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
1669 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
1670 // Call __kmpc_dispatch_init(
1671 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1672 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1673 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001674
John McCall7f416cc2015-09-08 08:05:57 +00001675 // If the Chunk was not specified in the clause - use default value 1.
1676 if (Chunk == nullptr)
1677 Chunk = CGF.Builder.getIntN(IVSize, 1);
1678 llvm::Value *Args[] = {
1679 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1680 getThreadID(CGF, Loc),
1681 CGF.Builder.getInt32(Schedule), // Schedule type
1682 CGF.Builder.getIntN(IVSize, 0), // Lower
1683 UB, // Upper
1684 CGF.Builder.getIntN(IVSize, 1), // Stride
1685 Chunk // Chunk
1686 };
1687 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1688}
1689
1690void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
1691 SourceLocation Loc,
1692 OpenMPScheduleClauseKind ScheduleKind,
1693 unsigned IVSize, bool IVSigned,
1694 bool Ordered, Address IL, Address LB,
1695 Address UB, Address ST,
1696 llvm::Value *Chunk) {
1697 OpenMPSchedType Schedule =
1698 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
1699 assert(!Ordered);
1700 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
1701 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked);
1702
1703 // Call __kmpc_for_static_init(
1704 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1705 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1706 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1707 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1708 if (Chunk == nullptr) {
1709 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
1710 "expected static non-chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00001711 // If the Chunk was not specified in the clause - use default value 1.
Alexander Musman92bdaab2015-03-12 13:37:50 +00001712 Chunk = CGF.Builder.getIntN(IVSize, 1);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001713 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001714 assert((Schedule == OMP_sch_static_chunked ||
1715 Schedule == OMP_ord_static_chunked) &&
1716 "expected static chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00001717 }
John McCall7f416cc2015-09-08 08:05:57 +00001718 llvm::Value *Args[] = {
1719 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1720 getThreadID(CGF, Loc),
1721 CGF.Builder.getInt32(Schedule), // Schedule type
1722 IL.getPointer(), // &isLastIter
1723 LB.getPointer(), // &LB
1724 UB.getPointer(), // &UB
1725 ST.getPointer(), // &Stride
1726 CGF.Builder.getIntN(IVSize, 1), // Incr
1727 Chunk // Chunk
1728 };
1729 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001730}
1731
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001732void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1733 SourceLocation Loc) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001734 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001735 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1736 getThreadID(CGF, Loc)};
1737 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1738 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001739}
1740
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001741void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
1742 SourceLocation Loc,
1743 unsigned IVSize,
1744 bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001745 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1746 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1747 getThreadID(CGF, Loc)};
1748 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1749}
1750
Alexander Musman92bdaab2015-03-12 13:37:50 +00001751llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1752 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00001753 bool IVSigned, Address IL,
1754 Address LB, Address UB,
1755 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001756 // Call __kmpc_dispatch_next(
1757 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1758 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1759 // kmp_int[32|64] *p_stride);
1760 llvm::Value *Args[] = {
1761 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001762 IL.getPointer(), // &isLastIter
1763 LB.getPointer(), // &Lower
1764 UB.getPointer(), // &Upper
1765 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00001766 };
1767 llvm::Value *Call =
1768 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1769 return CGF.EmitScalarConversion(
1770 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001771 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001772}
1773
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001774void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1775 llvm::Value *NumThreads,
1776 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001777 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1778 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001779 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001780 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001781 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1782 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001783}
1784
Alexey Bataev7f210c62015-06-18 13:40:03 +00001785void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
1786 OpenMPProcBindClauseKind ProcBind,
1787 SourceLocation Loc) {
1788 // Constants for proc bind value accepted by the runtime.
1789 enum ProcBindTy {
1790 ProcBindFalse = 0,
1791 ProcBindTrue,
1792 ProcBindMaster,
1793 ProcBindClose,
1794 ProcBindSpread,
1795 ProcBindIntel,
1796 ProcBindDefault
1797 } RuntimeProcBind;
1798 switch (ProcBind) {
1799 case OMPC_PROC_BIND_master:
1800 RuntimeProcBind = ProcBindMaster;
1801 break;
1802 case OMPC_PROC_BIND_close:
1803 RuntimeProcBind = ProcBindClose;
1804 break;
1805 case OMPC_PROC_BIND_spread:
1806 RuntimeProcBind = ProcBindSpread;
1807 break;
1808 case OMPC_PROC_BIND_unknown:
1809 llvm_unreachable("Unsupported proc_bind value.");
1810 }
1811 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
1812 llvm::Value *Args[] = {
1813 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1814 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
1815 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
1816}
1817
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001818void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1819 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001820 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001821 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1822 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001823}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001824
Alexey Bataev62b63b12015-03-10 07:28:44 +00001825namespace {
1826/// \brief Indexes of fields for type kmp_task_t.
1827enum KmpTaskTFields {
1828 /// \brief List of shared variables.
1829 KmpTaskTShareds,
1830 /// \brief Task routine.
1831 KmpTaskTRoutine,
1832 /// \brief Partition id for the untied tasks.
1833 KmpTaskTPartId,
1834 /// \brief Function with call of destructors for private variables.
1835 KmpTaskTDestructors,
1836};
Hans Wennborge89c8c82015-09-10 00:37:18 +00001837} // namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00001838
1839void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1840 if (!KmpRoutineEntryPtrTy) {
1841 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1842 auto &C = CGM.getContext();
1843 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1844 FunctionProtoType::ExtProtoInfo EPI;
1845 KmpRoutineEntryPtrQTy = C.getPointerType(
1846 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1847 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1848 }
1849}
1850
1851static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1852 QualType FieldTy) {
1853 auto *Field = FieldDecl::Create(
1854 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1855 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1856 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1857 Field->setAccess(AS_public);
1858 DC->addDecl(Field);
1859}
1860
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001861namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00001862struct PrivateHelpersTy {
1863 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
1864 const VarDecl *PrivateElemInit)
1865 : Original(Original), PrivateCopy(PrivateCopy),
1866 PrivateElemInit(PrivateElemInit) {}
1867 const VarDecl *Original;
1868 const VarDecl *PrivateCopy;
1869 const VarDecl *PrivateElemInit;
1870};
1871typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborge89c8c82015-09-10 00:37:18 +00001872} // namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001873
Alexey Bataev9e034042015-05-05 04:05:12 +00001874static RecordDecl *
1875createPrivatesRecordDecl(CodeGenModule &CGM,
1876 const ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001877 if (!Privates.empty()) {
1878 auto &C = CGM.getContext();
1879 // Build struct .kmp_privates_t. {
1880 // /* private vars */
1881 // };
1882 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
1883 RD->startDefinition();
1884 for (auto &&Pair : Privates) {
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001885 auto Type = Pair.second.Original->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001886 Type = Type.getNonReferenceType();
1887 addFieldToRecordDecl(C, RD, Type);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001888 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001889 RD->completeDefinition();
1890 return RD;
1891 }
1892 return nullptr;
1893}
1894
Alexey Bataev9e034042015-05-05 04:05:12 +00001895static RecordDecl *
1896createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001897 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001898 auto &C = CGM.getContext();
1899 // Build struct kmp_task_t {
1900 // void * shareds;
1901 // kmp_routine_entry_t routine;
1902 // kmp_int32 part_id;
1903 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001904 // };
1905 auto *RD = C.buildImplicitRecord("kmp_task_t");
1906 RD->startDefinition();
1907 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1908 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1909 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1910 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001911 RD->completeDefinition();
1912 return RD;
1913}
1914
1915static RecordDecl *
1916createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
1917 const ArrayRef<PrivateDataTy> Privates) {
1918 auto &C = CGM.getContext();
1919 // Build struct kmp_task_t_with_privates {
1920 // kmp_task_t task_data;
1921 // .kmp_privates_t. privates;
1922 // };
1923 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
1924 RD->startDefinition();
1925 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001926 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
1927 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
1928 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001929 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001930 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001931}
1932
1933/// \brief Emit a proxy function which accepts kmp_task_t as the second
1934/// argument.
1935/// \code
1936/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001937/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
1938/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001939/// return 0;
1940/// }
1941/// \endcode
1942static llvm::Value *
1943emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001944 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
1945 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001946 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1947 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001948 auto &C = CGM.getContext();
1949 FunctionArgList Args;
1950 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1951 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001952 /*Id=*/nullptr,
1953 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001954 Args.push_back(&GtidArg);
1955 Args.push_back(&TaskTypeArg);
1956 FunctionType::ExtInfo Info;
1957 auto &TaskEntryFnInfo =
1958 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1959 /*isVariadic=*/false);
1960 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1961 auto *TaskEntry =
1962 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1963 ".omp_task_entry.", &CGM.getModule());
1964 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1965 CodeGenFunction CGF(CGM);
1966 CGF.disableDebugInfo();
1967 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1968
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001969 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
1970 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001971 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001972 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001973 LValue TDBase = emitLoadOfPointerLValue(
1974 CGF, CGF.GetAddrOfLocalVar(&TaskTypeArg), KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001975 auto *KmpTaskTWithPrivatesQTyRD =
1976 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001977 LValue Base =
1978 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001979 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
1980 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
1981 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
1982 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
1983
1984 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
1985 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001986 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001987 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001988 CGF.ConvertTypeForMem(SharedsPtrTy));
1989
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001990 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
1991 llvm::Value *PrivatesParam;
1992 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
1993 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
1994 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00001995 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001996 } else {
1997 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
1998 }
1999
2000 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
2001 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002002 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
2003 CGF.EmitStoreThroughLValue(
2004 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00002005 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002006 CGF.FinishFunction();
2007 return TaskEntry;
2008}
2009
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002010static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
2011 SourceLocation Loc,
2012 QualType KmpInt32Ty,
2013 QualType KmpTaskTWithPrivatesPtrQTy,
2014 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002015 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002016 FunctionArgList Args;
2017 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2018 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002019 /*Id=*/nullptr,
2020 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002021 Args.push_back(&GtidArg);
2022 Args.push_back(&TaskTypeArg);
2023 FunctionType::ExtInfo Info;
2024 auto &DestructorFnInfo =
2025 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2026 /*isVariadic=*/false);
2027 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
2028 auto *DestructorFn =
2029 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
2030 ".omp_task_destructor.", &CGM.getModule());
2031 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, DestructorFnInfo, DestructorFn);
2032 CodeGenFunction CGF(CGM);
2033 CGF.disableDebugInfo();
2034 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
2035 Args);
2036
Alexey Bataev2377fe92015-09-10 08:12:02 +00002037 LValue Base = emitLoadOfPointerLValue(
2038 CGF, CGF.GetAddrOfLocalVar(&TaskTypeArg), KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002039 auto *KmpTaskTWithPrivatesQTyRD =
2040 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
2041 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002042 Base = CGF.EmitLValueForField(Base, *FI);
2043 for (auto *Field :
2044 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
2045 if (auto DtorKind = Field->getType().isDestructedType()) {
2046 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
2047 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
2048 }
2049 }
2050 CGF.FinishFunction();
2051 return DestructorFn;
2052}
2053
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002054/// \brief Emit a privates mapping function for correct handling of private and
2055/// firstprivate variables.
2056/// \code
2057/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
2058/// **noalias priv1,..., <tyn> **noalias privn) {
2059/// *priv1 = &.privates.priv1;
2060/// ...;
2061/// *privn = &.privates.privn;
2062/// }
2063/// \endcode
2064static llvm::Value *
2065emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
2066 const ArrayRef<const Expr *> PrivateVars,
2067 const ArrayRef<const Expr *> FirstprivateVars,
2068 QualType PrivatesQTy,
2069 const ArrayRef<PrivateDataTy> Privates) {
2070 auto &C = CGM.getContext();
2071 FunctionArgList Args;
2072 ImplicitParamDecl TaskPrivatesArg(
2073 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2074 C.getPointerType(PrivatesQTy).withConst().withRestrict());
2075 Args.push_back(&TaskPrivatesArg);
2076 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
2077 unsigned Counter = 1;
2078 for (auto *E: PrivateVars) {
2079 Args.push_back(ImplicitParamDecl::Create(
2080 C, /*DC=*/nullptr, Loc,
2081 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2082 .withConst()
2083 .withRestrict()));
2084 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2085 PrivateVarsPos[VD] = Counter;
2086 ++Counter;
2087 }
2088 for (auto *E : FirstprivateVars) {
2089 Args.push_back(ImplicitParamDecl::Create(
2090 C, /*DC=*/nullptr, Loc,
2091 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2092 .withConst()
2093 .withRestrict()));
2094 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2095 PrivateVarsPos[VD] = Counter;
2096 ++Counter;
2097 }
2098 FunctionType::ExtInfo Info;
2099 auto &TaskPrivatesMapFnInfo =
2100 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2101 /*isVariadic=*/false);
2102 auto *TaskPrivatesMapTy =
2103 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2104 auto *TaskPrivatesMap = llvm::Function::Create(
2105 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2106 ".omp_task_privates_map.", &CGM.getModule());
2107 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskPrivatesMapFnInfo,
2108 TaskPrivatesMap);
2109 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
2110 CodeGenFunction CGF(CGM);
2111 CGF.disableDebugInfo();
2112 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2113 TaskPrivatesMapFnInfo, Args);
2114
2115 // *privi = &.privates.privi;
Alexey Bataev2377fe92015-09-10 08:12:02 +00002116 LValue Base = emitLoadOfPointerLValue(
2117 CGF, CGF.GetAddrOfLocalVar(&TaskPrivatesArg), TaskPrivatesArg.getType());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002118 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2119 Counter = 0;
2120 for (auto *Field : PrivatesQTyRD->fields()) {
2121 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2122 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00002123 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002124 auto RefLoadLVal =
2125 emitLoadOfPointerLValue(CGF, RefLVal.getAddress(), RefLVal.getType());
2126 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002127 ++Counter;
2128 }
2129 CGF.FinishFunction();
2130 return TaskPrivatesMap;
2131}
2132
Benjamin Kramer9b819032015-09-02 15:31:05 +00002133static llvm::Value *getTypeSize(CodeGenFunction &CGF, QualType Ty) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002134 auto &C = CGF.getContext();
2135 llvm::Value *Size;
2136 auto SizeInChars = C.getTypeSizeInChars(Ty);
2137 if (SizeInChars.isZero()) {
2138 // getTypeSizeInChars() returns 0 for a VLA.
2139 Size = nullptr;
2140 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
2141 llvm::Value *ArraySize;
2142 std::tie(ArraySize, Ty) = CGF.getVLASize(VAT);
2143 Size = Size ? CGF.Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
2144 }
2145 SizeInChars = C.getTypeSizeInChars(Ty);
2146 assert(!SizeInChars.isZero());
2147 Size = CGF.Builder.CreateNUWMul(
2148 Size, llvm::ConstantInt::get(CGF.SizeTy, SizeInChars.getQuantity()));
2149 } else
2150 Size = llvm::ConstantInt::get(CGF.SizeTy, SizeInChars.getQuantity());
2151 return Size;
2152}
2153
Alexey Bataev9e034042015-05-05 04:05:12 +00002154static int array_pod_sort_comparator(const PrivateDataTy *P1,
2155 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002156 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2157}
2158
2159void CGOpenMPRuntime::emitTaskCall(
2160 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
2161 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00002162 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002163 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
2164 ArrayRef<const Expr *> PrivateCopies,
2165 ArrayRef<const Expr *> FirstprivateVars,
2166 ArrayRef<const Expr *> FirstprivateCopies,
2167 ArrayRef<const Expr *> FirstprivateInits,
2168 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002169 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00002170 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002171 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00002172 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002173 for (auto *E : PrivateVars) {
2174 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2175 Privates.push_back(std::make_pair(
2176 C.getTypeAlignInChars(VD->getType()),
Alexey Bataev9e034042015-05-05 04:05:12 +00002177 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2178 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002179 ++I;
2180 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002181 I = FirstprivateCopies.begin();
2182 auto IElemInitRef = FirstprivateInits.begin();
2183 for (auto *E : FirstprivateVars) {
2184 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2185 Privates.push_back(std::make_pair(
2186 C.getTypeAlignInChars(VD->getType()),
2187 PrivateHelpersTy(
2188 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2189 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
2190 ++I, ++IElemInitRef;
2191 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002192 llvm::array_pod_sort(Privates.begin(), Privates.end(),
2193 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002194 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2195 // Build type kmp_routine_entry_t (if not built yet).
2196 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002197 // Build type kmp_task_t (if not built yet).
2198 if (KmpTaskTQTy.isNull()) {
2199 KmpTaskTQTy = C.getRecordType(
2200 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2201 }
2202 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002203 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002204 auto *KmpTaskTWithPrivatesQTyRD =
2205 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2206 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2207 QualType KmpTaskTWithPrivatesPtrQTy =
2208 C.getPointerType(KmpTaskTWithPrivatesQTy);
2209 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2210 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
2211 auto KmpTaskTWithPrivatesTySize =
2212 CGM.getSize(C.getTypeSizeInChars(KmpTaskTWithPrivatesQTy));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002213 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2214
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002215 // Emit initial values for private copies (if any).
2216 llvm::Value *TaskPrivatesMap = nullptr;
2217 auto *TaskPrivatesMapTy =
2218 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2219 3)
2220 ->getType();
2221 if (!Privates.empty()) {
2222 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2223 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2224 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2225 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2226 TaskPrivatesMap, TaskPrivatesMapTy);
2227 } else {
2228 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2229 cast<llvm::PointerType>(TaskPrivatesMapTy));
2230 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002231 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2232 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002233 auto *TaskEntry = emitProxyTaskFunction(
2234 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002235 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002236
2237 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2238 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2239 // kmp_routine_entry_t *task_entry);
2240 // Task flags. Format is taken from
2241 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2242 // description of kmp_tasking_flags struct.
2243 const unsigned TiedFlag = 0x1;
2244 const unsigned FinalFlag = 0x2;
2245 unsigned Flags = Tied ? TiedFlag : 0;
2246 auto *TaskFlags =
2247 Final.getPointer()
2248 ? CGF.Builder.CreateSelect(Final.getPointer(),
2249 CGF.Builder.getInt32(FinalFlag),
2250 CGF.Builder.getInt32(/*C=*/0))
2251 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2252 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
2253 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002254 llvm::Value *AllocArgs[] = {
2255 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), TaskFlags,
2256 KmpTaskTWithPrivatesTySize, CGM.getSize(SharedsSize),
2257 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskEntry,
2258 KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002259 auto *NewTask = CGF.EmitRuntimeCall(
2260 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002261 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2262 NewTask, KmpTaskTWithPrivatesPtrTy);
2263 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2264 KmpTaskTWithPrivatesQTy);
2265 LValue TDBase =
2266 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002267 // Fill the data in the resulting kmp_task_t record.
2268 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00002269 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002270 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002271 KmpTaskSharedsPtr =
2272 Address(CGF.EmitLoadOfScalar(
2273 CGF.EmitLValueForField(
2274 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
2275 KmpTaskTShareds)),
2276 Loc),
2277 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002278 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002279 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002280 // Emit initial values for private copies (if any).
2281 bool NeedsCleanup = false;
2282 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002283 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2284 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002285 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002286 LValue SharedsBase;
2287 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002288 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002289 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2290 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2291 SharedsTy);
2292 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002293 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2294 cast<CapturedStmt>(*D.getAssociatedStmt()));
2295 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002296 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002297 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002298 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002299 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002300 if (auto *Elem = Pair.second.PrivateElemInit) {
2301 auto *OriginalVD = Pair.second.Original;
2302 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2303 auto SharedRefLValue =
2304 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002305 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002306 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002307 // Initialize firstprivate array.
2308 if (!isa<CXXConstructExpr>(Init) ||
2309 CGF.isTrivialInitializer(Init)) {
2310 // Perform simple memcpy.
2311 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002312 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002313 } else {
2314 // Initialize firstprivate array using element-by-element
2315 // intialization.
2316 CGF.EmitOMPAggregateAssign(
2317 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002318 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00002319 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002320 // Clean up any temporaries needed by the initialization.
2321 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002322 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002323 return SrcElement;
2324 });
2325 (void)InitScope.Privatize();
2326 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00002327 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
2328 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002329 CGF.EmitAnyExprToMem(Init, DestElement,
2330 Init->getType().getQualifiers(),
2331 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002332 });
2333 }
2334 } else {
2335 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002336 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002337 return SharedRefLValue.getAddress();
2338 });
2339 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00002340 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002341 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2342 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002343 }
2344 } else {
2345 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2346 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002347 }
2348 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002349 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002350 }
2351 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002352 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002353 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002354 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2355 KmpTaskTWithPrivatesPtrQTy,
2356 KmpTaskTWithPrivatesQTy)
2357 : llvm::ConstantPointerNull::get(
2358 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2359 LValue Destructor = CGF.EmitLValueForField(
2360 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2361 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2362 DestructorFn, KmpRoutineEntryPtrTy),
2363 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002364
2365 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00002366 Address DependenciesArray = Address::invalid();
2367 unsigned NumDependencies = Dependences.size();
2368 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002369 // Dependence kind for RTL.
2370 enum RTLDependenceKindTy { DepIn = 1, DepOut = 2, DepInOut = 3 };
2371 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
2372 RecordDecl *KmpDependInfoRD;
2373 QualType FlagsTy = C.getIntTypeForBitwidth(
2374 C.toBits(C.getTypeSizeInChars(C.BoolTy)), /*Signed=*/false);
2375 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
2376 if (KmpDependInfoTy.isNull()) {
2377 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
2378 KmpDependInfoRD->startDefinition();
2379 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
2380 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
2381 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
2382 KmpDependInfoRD->completeDefinition();
2383 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
2384 } else {
2385 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
2386 }
John McCall7f416cc2015-09-08 08:05:57 +00002387 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002388 // Define type kmp_depend_info[<Dependences.size()>];
2389 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00002390 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002391 ArrayType::Normal, /*IndexTypeQuals=*/0);
2392 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00002393 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
2394 for (unsigned i = 0; i < NumDependencies; ++i) {
2395 const Expr *E = Dependences[i].second;
2396 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002397 llvm::Value *Size;
2398 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002399 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
2400 LValue UpAddrLVal =
2401 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
2402 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00002403 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002404 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00002405 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002406 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
2407 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
John McCall7f416cc2015-09-08 08:05:57 +00002408 } else {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002409 Size = getTypeSize(CGF, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002410 }
2411 auto Base = CGF.MakeAddrLValue(
2412 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002413 KmpDependInfoTy);
2414 // deps[i].base_addr = &<Dependences[i].second>;
2415 auto BaseAddrLVal = CGF.EmitLValueForField(
2416 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00002417 CGF.EmitStoreOfScalar(
2418 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
2419 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002420 // deps[i].len = sizeof(<Dependences[i].second>);
2421 auto LenLVal = CGF.EmitLValueForField(
2422 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
2423 CGF.EmitStoreOfScalar(Size, LenLVal);
2424 // deps[i].flags = <Dependences[i].first>;
2425 RTLDependenceKindTy DepKind;
2426 switch (Dependences[i].first) {
2427 case OMPC_DEPEND_in:
2428 DepKind = DepIn;
2429 break;
2430 case OMPC_DEPEND_out:
2431 DepKind = DepOut;
2432 break;
2433 case OMPC_DEPEND_inout:
2434 DepKind = DepInOut;
2435 break;
2436 case OMPC_DEPEND_unknown:
2437 llvm_unreachable("Unknown task dependence type");
2438 }
2439 auto FlagsLVal = CGF.EmitLValueForField(
2440 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
2441 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
2442 FlagsLVal);
2443 }
John McCall7f416cc2015-09-08 08:05:57 +00002444 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2445 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002446 CGF.VoidPtrTy);
2447 }
2448
Alexey Bataev62b63b12015-03-10 07:28:44 +00002449 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
2450 // libcall.
2451 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
2452 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002453 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2454 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2455 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
2456 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00002457 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002458 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002459 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
2460 llvm::Value *DepTaskArgs[7];
2461 if (NumDependencies) {
2462 DepTaskArgs[0] = UpLoc;
2463 DepTaskArgs[1] = ThreadID;
2464 DepTaskArgs[2] = NewTask;
2465 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
2466 DepTaskArgs[4] = DependenciesArray.getPointer();
2467 DepTaskArgs[5] = CGF.Builder.getInt32(0);
2468 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2469 }
2470 auto &&ThenCodeGen = [this, NumDependencies,
2471 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
2472 // TODO: add check for untied tasks.
2473 if (NumDependencies) {
2474 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
2475 DepTaskArgs);
2476 } else {
2477 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
2478 TaskArgs);
2479 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002480 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002481 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
2482 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00002483
2484 llvm::Value *DepWaitTaskArgs[6];
2485 if (NumDependencies) {
2486 DepWaitTaskArgs[0] = UpLoc;
2487 DepWaitTaskArgs[1] = ThreadID;
2488 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
2489 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
2490 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
2491 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2492 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002493 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00002494 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002495 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
2496 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2497 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
2498 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
2499 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00002500 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002501 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
2502 DepWaitTaskArgs);
2503 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
2504 // kmp_task_t *new_task);
2505 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
2506 TaskArgs);
2507 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
2508 // kmp_task_t *new_task);
2509 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
2510 NormalAndEHCleanup,
2511 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
2512 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002513
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002514 // Call proxy_task_entry(gtid, new_task);
2515 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
2516 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
2517 };
John McCall7f416cc2015-09-08 08:05:57 +00002518
Alexey Bataev1d677132015-04-22 13:57:31 +00002519 if (IfCond) {
2520 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
2521 } else {
2522 CodeGenFunction::RunCleanupsScope Scope(CGF);
2523 ThenCodeGen(CGF);
2524 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002525}
2526
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002527static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
2528 llvm::Type *ArgsType,
2529 ArrayRef<const Expr *> LHSExprs,
2530 ArrayRef<const Expr *> RHSExprs,
2531 ArrayRef<const Expr *> ReductionOps) {
2532 auto &C = CGM.getContext();
2533
2534 // void reduction_func(void *LHSArg, void *RHSArg);
2535 FunctionArgList Args;
2536 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2537 C.VoidPtrTy);
2538 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2539 C.VoidPtrTy);
2540 Args.push_back(&LHSArg);
2541 Args.push_back(&RHSArg);
2542 FunctionType::ExtInfo EI;
2543 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2544 C.VoidTy, Args, EI, /*isVariadic=*/false);
2545 auto *Fn = llvm::Function::Create(
2546 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2547 ".omp.reduction.reduction_func", &CGM.getModule());
2548 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
2549 CodeGenFunction CGF(CGM);
2550 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2551
2552 // Dst = (void*[n])(LHSArg);
2553 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002554 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2555 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2556 ArgsType), CGF.getPointerAlign());
2557 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2558 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2559 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002560
2561 // ...
2562 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
2563 // ...
2564 CodeGenFunction::OMPPrivateScope Scope(CGF);
2565 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002566 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
2567 Scope.addPrivate(RHSVar, [&]() -> Address {
2568 return emitAddrOfVarFromArray(CGF, RHS, I, RHSVar);
2569 });
2570 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
2571 Scope.addPrivate(LHSVar, [&]() -> Address {
2572 return emitAddrOfVarFromArray(CGF, LHS, I, LHSVar);
2573 });
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002574 }
2575 Scope.Privatize();
2576 for (auto *E : ReductionOps) {
2577 CGF.EmitIgnoredExpr(E);
2578 }
2579 Scope.ForceCleanup();
2580 CGF.FinishFunction();
2581 return Fn;
2582}
2583
2584void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
2585 ArrayRef<const Expr *> LHSExprs,
2586 ArrayRef<const Expr *> RHSExprs,
2587 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002588 bool WithNowait, bool SimpleReduction) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002589 // Next code should be emitted for reduction:
2590 //
2591 // static kmp_critical_name lock = { 0 };
2592 //
2593 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
2594 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
2595 // ...
2596 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
2597 // *(Type<n>-1*)rhs[<n>-1]);
2598 // }
2599 //
2600 // ...
2601 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
2602 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2603 // RedList, reduce_func, &<lock>)) {
2604 // case 1:
2605 // ...
2606 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2607 // ...
2608 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2609 // break;
2610 // case 2:
2611 // ...
2612 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2613 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00002614 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002615 // break;
2616 // default:;
2617 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002618 //
2619 // if SimpleReduction is true, only the next code is generated:
2620 // ...
2621 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2622 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002623
2624 auto &C = CGM.getContext();
2625
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002626 if (SimpleReduction) {
2627 CodeGenFunction::RunCleanupsScope Scope(CGF);
2628 for (auto *E : ReductionOps) {
2629 CGF.EmitIgnoredExpr(E);
2630 }
2631 return;
2632 }
2633
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002634 // 1. Build a list of reduction variables.
2635 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2636 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
2637 QualType ReductionArrayTy =
2638 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2639 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00002640 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002641 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2642 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002643 Address Elem =
2644 CGF.Builder.CreateConstArrayGEP(ReductionList, I, CGF.getPointerSize());
2645 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002646 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002647 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
2648 Elem);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002649 }
2650
2651 // 2. Emit reduce_func().
2652 auto *ReductionFn = emitReductionFunction(
2653 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
2654 RHSExprs, ReductionOps);
2655
2656 // 3. Create static kmp_critical_name lock = { 0 };
2657 auto *Lock = getCriticalRegionLock(".reduction");
2658
2659 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2660 // RedList, reduce_func, &<lock>);
2661 auto *IdentTLoc = emitUpdateLocation(
2662 CGF, Loc,
2663 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
2664 auto *ThreadId = getThreadID(CGF, Loc);
2665 auto *ReductionArrayTySize = llvm::ConstantInt::get(
2666 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002667 auto *RL =
2668 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
2669 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002670 llvm::Value *Args[] = {
2671 IdentTLoc, // ident_t *<loc>
2672 ThreadId, // i32 <gtid>
2673 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
2674 ReductionArrayTySize, // size_type sizeof(RedList)
2675 RL, // void *RedList
2676 ReductionFn, // void (*) (void *, void *) <reduce_func>
2677 Lock // kmp_critical_name *&<lock>
2678 };
2679 auto Res = CGF.EmitRuntimeCall(
2680 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
2681 : OMPRTL__kmpc_reduce),
2682 Args);
2683
2684 // 5. Build switch(res)
2685 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2686 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
2687
2688 // 6. Build case 1:
2689 // ...
2690 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2691 // ...
2692 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2693 // break;
2694 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2695 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2696 CGF.EmitBlock(Case1BB);
2697
2698 {
2699 CodeGenFunction::RunCleanupsScope Scope(CGF);
2700 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2701 llvm::Value *EndArgs[] = {
2702 IdentTLoc, // ident_t *<loc>
2703 ThreadId, // i32 <gtid>
2704 Lock // kmp_critical_name *&<lock>
2705 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002706 CGF.EHStack
2707 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2708 NormalAndEHCleanup,
2709 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
2710 : OMPRTL__kmpc_end_reduce),
2711 llvm::makeArrayRef(EndArgs));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002712 for (auto *E : ReductionOps) {
2713 CGF.EmitIgnoredExpr(E);
2714 }
2715 }
2716
2717 CGF.EmitBranch(DefaultBB);
2718
2719 // 7. Build case 2:
2720 // ...
2721 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2722 // ...
2723 // break;
2724 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
2725 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
2726 CGF.EmitBlock(Case2BB);
2727
2728 {
2729 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00002730 if (!WithNowait) {
2731 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
2732 llvm::Value *EndArgs[] = {
2733 IdentTLoc, // ident_t *<loc>
2734 ThreadId, // i32 <gtid>
2735 Lock // kmp_critical_name *&<lock>
2736 };
2737 CGF.EHStack
2738 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2739 NormalAndEHCleanup,
2740 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
2741 llvm::makeArrayRef(EndArgs));
2742 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002743 auto I = LHSExprs.begin();
2744 for (auto *E : ReductionOps) {
2745 const Expr *XExpr = nullptr;
2746 const Expr *EExpr = nullptr;
2747 const Expr *UpExpr = nullptr;
2748 BinaryOperatorKind BO = BO_Comma;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002749 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2750 if (BO->getOpcode() == BO_Assign) {
2751 XExpr = BO->getLHS();
2752 UpExpr = BO->getRHS();
2753 }
2754 }
Alexey Bataev69a47792015-05-07 03:54:03 +00002755 // Try to emit update expression as a simple atomic.
2756 auto *RHSExpr = UpExpr;
2757 if (RHSExpr) {
2758 // Analyze RHS part of the whole expression.
2759 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
2760 RHSExpr->IgnoreParenImpCasts())) {
2761 // If this is a conditional operator, analyze its condition for
2762 // min/max reduction operator.
2763 RHSExpr = ACO->getCond();
2764 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002765 if (auto *BORHS =
Alexey Bataev69a47792015-05-07 03:54:03 +00002766 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002767 EExpr = BORHS->getRHS();
2768 BO = BORHS->getOpcode();
2769 }
2770 }
2771 if (XExpr) {
2772 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2773 LValue X = CGF.EmitLValue(XExpr);
2774 RValue E;
2775 if (EExpr)
2776 E = CGF.EmitAnyExpr(EExpr);
2777 CGF.EmitOMPAtomicSimpleUpdateExpr(
2778 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
2779 [&CGF, UpExpr, VD](RValue XRValue) {
2780 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
2781 PrivateScope.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +00002782 VD, [&CGF, VD, XRValue]() -> Address {
2783 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002784 CGF.EmitStoreThroughLValue(
2785 XRValue,
John McCall7f416cc2015-09-08 08:05:57 +00002786 CGF.MakeAddrLValue(LHSTemp, VD->getType()));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002787 return LHSTemp;
2788 });
2789 (void)PrivateScope.Privatize();
2790 return CGF.EmitAnyExpr(UpExpr);
2791 });
2792 } else {
2793 // Emit as a critical region.
2794 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
2795 CGF.EmitIgnoredExpr(E);
2796 }, Loc);
2797 }
2798 ++I;
2799 }
2800 }
2801
2802 CGF.EmitBranch(DefaultBB);
2803 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2804}
2805
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002806void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
2807 SourceLocation Loc) {
2808 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2809 // global_tid);
2810 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2811 // Ignore return result until untied tasks are supported.
2812 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
2813}
2814
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002815void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002816 OpenMPDirectiveKind InnerKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002817 const RegionCodeGenTy &CodeGen) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002818 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002819 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002820}
2821
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002822namespace {
2823enum RTCancelKind {
2824 CancelNoreq = 0,
2825 CancelParallel = 1,
2826 CancelLoop = 2,
2827 CancelSections = 3,
2828 CancelTaskgroup = 4
2829};
2830}
2831
2832static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
2833 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00002834 if (CancelRegion == OMPD_parallel)
2835 CancelKind = CancelParallel;
2836 else if (CancelRegion == OMPD_for)
2837 CancelKind = CancelLoop;
2838 else if (CancelRegion == OMPD_sections)
2839 CancelKind = CancelSections;
2840 else {
2841 assert(CancelRegion == OMPD_taskgroup);
2842 CancelKind = CancelTaskgroup;
2843 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002844 return CancelKind;
2845}
2846
2847void CGOpenMPRuntime::emitCancellationPointCall(
2848 CodeGenFunction &CGF, SourceLocation Loc,
2849 OpenMPDirectiveKind CancelRegion) {
2850 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2851 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002852 if (auto *OMPRegionInfo =
2853 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2854 auto CancelDest =
2855 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2856 if (CancelDest.isValid()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002857 llvm::Value *Args[] = {
2858 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2859 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002860 // Ignore return result until untied tasks are supported.
2861 auto *Result = CGF.EmitRuntimeCall(
2862 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
2863 // if (__kmpc_cancellationpoint()) {
2864 // __kmpc_cancel_barrier();
2865 // exit from construct;
2866 // }
2867 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2868 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2869 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2870 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2871 CGF.EmitBlock(ExitBB);
2872 // __kmpc_cancel_barrier();
2873 emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
2874 // exit from construct;
2875 CGF.EmitBranchThroughCleanup(CancelDest);
2876 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2877 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002878 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002879}
2880
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002881void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
2882 OpenMPDirectiveKind CancelRegion) {
2883 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2884 // kmp_int32 cncl_kind);
2885 if (auto *OMPRegionInfo =
2886 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2887 auto CancelDest =
2888 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2889 if (CancelDest.isValid()) {
2890 llvm::Value *Args[] = {
2891 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2892 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
2893 // Ignore return result until untied tasks are supported.
2894 auto *Result =
2895 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
2896 // if (__kmpc_cancel()) {
2897 // __kmpc_cancel_barrier();
2898 // exit from construct;
2899 // }
2900 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2901 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2902 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2903 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2904 CGF.EmitBlock(ExitBB);
2905 // __kmpc_cancel_barrier();
2906 emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
2907 // exit from construct;
2908 CGF.EmitBranchThroughCleanup(CancelDest);
2909 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2910 }
2911 }
2912}
Hans Wennborge89c8c82015-09-10 00:37:18 +00002913