blob: a9e7a9c55528cb22f0fe7410d1ed332d41139d75 [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 Wennborg7eb54642015-09-10 17:07:54 +000062 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 Wennborg7eb54642015-09-10 17:07:54 +0000159 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 Wennborg7eb54642015-09-10 17:07:54 +0000232} // anonymous 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 Wennborg7eb54642015-09-10 17:07:54 +00001289} // anonymous 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 Wennborg7eb54642015-09-10 17:07:54 +00001837} // anonymous 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
Alexey Bataevc71a4092015-09-11 10:29:41 +00001851static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1852 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001853 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);
Alexey Bataevc71a4092015-09-11 10:29:41 +00001859 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001860}
1861
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001862namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00001863struct PrivateHelpersTy {
1864 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
1865 const VarDecl *PrivateElemInit)
1866 : Original(Original), PrivateCopy(PrivateCopy),
1867 PrivateElemInit(PrivateElemInit) {}
1868 const VarDecl *Original;
1869 const VarDecl *PrivateCopy;
1870 const VarDecl *PrivateElemInit;
1871};
1872typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00001873} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001874
Alexey Bataev9e034042015-05-05 04:05:12 +00001875static RecordDecl *
1876createPrivatesRecordDecl(CodeGenModule &CGM,
1877 const ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001878 if (!Privates.empty()) {
1879 auto &C = CGM.getContext();
1880 // Build struct .kmp_privates_t. {
1881 // /* private vars */
1882 // };
1883 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
1884 RD->startDefinition();
1885 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00001886 auto *VD = Pair.second.Original;
1887 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001888 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00001889 auto *FD = addFieldToRecordDecl(C, RD, Type);
1890 if (VD->hasAttrs()) {
1891 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
1892 E(VD->getAttrs().end());
1893 I != E; ++I)
1894 FD->addAttr(*I);
1895 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001896 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001897 RD->completeDefinition();
1898 return RD;
1899 }
1900 return nullptr;
1901}
1902
Alexey Bataev9e034042015-05-05 04:05:12 +00001903static RecordDecl *
1904createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001905 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001906 auto &C = CGM.getContext();
1907 // Build struct kmp_task_t {
1908 // void * shareds;
1909 // kmp_routine_entry_t routine;
1910 // kmp_int32 part_id;
1911 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001912 // };
1913 auto *RD = C.buildImplicitRecord("kmp_task_t");
1914 RD->startDefinition();
1915 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1916 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1917 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1918 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001919 RD->completeDefinition();
1920 return RD;
1921}
1922
1923static RecordDecl *
1924createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
1925 const ArrayRef<PrivateDataTy> Privates) {
1926 auto &C = CGM.getContext();
1927 // Build struct kmp_task_t_with_privates {
1928 // kmp_task_t task_data;
1929 // .kmp_privates_t. privates;
1930 // };
1931 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
1932 RD->startDefinition();
1933 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001934 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
1935 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
1936 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001937 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001938 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001939}
1940
1941/// \brief Emit a proxy function which accepts kmp_task_t as the second
1942/// argument.
1943/// \code
1944/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001945/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
1946/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001947/// return 0;
1948/// }
1949/// \endcode
1950static llvm::Value *
1951emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001952 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
1953 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001954 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1955 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001956 auto &C = CGM.getContext();
1957 FunctionArgList Args;
1958 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1959 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001960 /*Id=*/nullptr,
1961 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001962 Args.push_back(&GtidArg);
1963 Args.push_back(&TaskTypeArg);
1964 FunctionType::ExtInfo Info;
1965 auto &TaskEntryFnInfo =
1966 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1967 /*isVariadic=*/false);
1968 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1969 auto *TaskEntry =
1970 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1971 ".omp_task_entry.", &CGM.getModule());
1972 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1973 CodeGenFunction CGF(CGM);
1974 CGF.disableDebugInfo();
1975 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1976
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001977 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
1978 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001979 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001980 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001981 LValue TDBase = emitLoadOfPointerLValue(
1982 CGF, CGF.GetAddrOfLocalVar(&TaskTypeArg), KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001983 auto *KmpTaskTWithPrivatesQTyRD =
1984 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001985 LValue Base =
1986 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001987 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
1988 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
1989 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
1990 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
1991
1992 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
1993 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001994 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001995 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001996 CGF.ConvertTypeForMem(SharedsPtrTy));
1997
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001998 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
1999 llvm::Value *PrivatesParam;
2000 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
2001 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
2002 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002003 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002004 } else {
2005 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2006 }
2007
2008 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
2009 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002010 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
2011 CGF.EmitStoreThroughLValue(
2012 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00002013 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002014 CGF.FinishFunction();
2015 return TaskEntry;
2016}
2017
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002018static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
2019 SourceLocation Loc,
2020 QualType KmpInt32Ty,
2021 QualType KmpTaskTWithPrivatesPtrQTy,
2022 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002023 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002024 FunctionArgList Args;
2025 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2026 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002027 /*Id=*/nullptr,
2028 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002029 Args.push_back(&GtidArg);
2030 Args.push_back(&TaskTypeArg);
2031 FunctionType::ExtInfo Info;
2032 auto &DestructorFnInfo =
2033 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2034 /*isVariadic=*/false);
2035 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
2036 auto *DestructorFn =
2037 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
2038 ".omp_task_destructor.", &CGM.getModule());
2039 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, DestructorFnInfo, DestructorFn);
2040 CodeGenFunction CGF(CGM);
2041 CGF.disableDebugInfo();
2042 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
2043 Args);
2044
Alexey Bataev2377fe92015-09-10 08:12:02 +00002045 LValue Base = emitLoadOfPointerLValue(
2046 CGF, CGF.GetAddrOfLocalVar(&TaskTypeArg), KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002047 auto *KmpTaskTWithPrivatesQTyRD =
2048 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
2049 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002050 Base = CGF.EmitLValueForField(Base, *FI);
2051 for (auto *Field :
2052 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
2053 if (auto DtorKind = Field->getType().isDestructedType()) {
2054 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
2055 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
2056 }
2057 }
2058 CGF.FinishFunction();
2059 return DestructorFn;
2060}
2061
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002062/// \brief Emit a privates mapping function for correct handling of private and
2063/// firstprivate variables.
2064/// \code
2065/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
2066/// **noalias priv1,..., <tyn> **noalias privn) {
2067/// *priv1 = &.privates.priv1;
2068/// ...;
2069/// *privn = &.privates.privn;
2070/// }
2071/// \endcode
2072static llvm::Value *
2073emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
2074 const ArrayRef<const Expr *> PrivateVars,
2075 const ArrayRef<const Expr *> FirstprivateVars,
2076 QualType PrivatesQTy,
2077 const ArrayRef<PrivateDataTy> Privates) {
2078 auto &C = CGM.getContext();
2079 FunctionArgList Args;
2080 ImplicitParamDecl TaskPrivatesArg(
2081 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2082 C.getPointerType(PrivatesQTy).withConst().withRestrict());
2083 Args.push_back(&TaskPrivatesArg);
2084 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
2085 unsigned Counter = 1;
2086 for (auto *E: PrivateVars) {
2087 Args.push_back(ImplicitParamDecl::Create(
2088 C, /*DC=*/nullptr, Loc,
2089 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2090 .withConst()
2091 .withRestrict()));
2092 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2093 PrivateVarsPos[VD] = Counter;
2094 ++Counter;
2095 }
2096 for (auto *E : FirstprivateVars) {
2097 Args.push_back(ImplicitParamDecl::Create(
2098 C, /*DC=*/nullptr, Loc,
2099 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2100 .withConst()
2101 .withRestrict()));
2102 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2103 PrivateVarsPos[VD] = Counter;
2104 ++Counter;
2105 }
2106 FunctionType::ExtInfo Info;
2107 auto &TaskPrivatesMapFnInfo =
2108 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2109 /*isVariadic=*/false);
2110 auto *TaskPrivatesMapTy =
2111 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2112 auto *TaskPrivatesMap = llvm::Function::Create(
2113 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2114 ".omp_task_privates_map.", &CGM.getModule());
2115 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskPrivatesMapFnInfo,
2116 TaskPrivatesMap);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00002117 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002118 CodeGenFunction CGF(CGM);
2119 CGF.disableDebugInfo();
2120 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2121 TaskPrivatesMapFnInfo, Args);
2122
2123 // *privi = &.privates.privi;
Alexey Bataev2377fe92015-09-10 08:12:02 +00002124 LValue Base = emitLoadOfPointerLValue(
2125 CGF, CGF.GetAddrOfLocalVar(&TaskPrivatesArg), TaskPrivatesArg.getType());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002126 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2127 Counter = 0;
2128 for (auto *Field : PrivatesQTyRD->fields()) {
2129 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2130 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00002131 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002132 auto RefLoadLVal =
2133 emitLoadOfPointerLValue(CGF, RefLVal.getAddress(), RefLVal.getType());
2134 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002135 ++Counter;
2136 }
2137 CGF.FinishFunction();
2138 return TaskPrivatesMap;
2139}
2140
Benjamin Kramer9b819032015-09-02 15:31:05 +00002141static llvm::Value *getTypeSize(CodeGenFunction &CGF, QualType Ty) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002142 auto &C = CGF.getContext();
2143 llvm::Value *Size;
2144 auto SizeInChars = C.getTypeSizeInChars(Ty);
2145 if (SizeInChars.isZero()) {
2146 // getTypeSizeInChars() returns 0 for a VLA.
2147 Size = nullptr;
2148 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
2149 llvm::Value *ArraySize;
2150 std::tie(ArraySize, Ty) = CGF.getVLASize(VAT);
2151 Size = Size ? CGF.Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
2152 }
2153 SizeInChars = C.getTypeSizeInChars(Ty);
2154 assert(!SizeInChars.isZero());
2155 Size = CGF.Builder.CreateNUWMul(
2156 Size, llvm::ConstantInt::get(CGF.SizeTy, SizeInChars.getQuantity()));
2157 } else
2158 Size = llvm::ConstantInt::get(CGF.SizeTy, SizeInChars.getQuantity());
2159 return Size;
2160}
2161
Alexey Bataev9e034042015-05-05 04:05:12 +00002162static int array_pod_sort_comparator(const PrivateDataTy *P1,
2163 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002164 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2165}
2166
2167void CGOpenMPRuntime::emitTaskCall(
2168 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
2169 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00002170 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002171 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
2172 ArrayRef<const Expr *> PrivateCopies,
2173 ArrayRef<const Expr *> FirstprivateVars,
2174 ArrayRef<const Expr *> FirstprivateCopies,
2175 ArrayRef<const Expr *> FirstprivateInits,
2176 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002177 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00002178 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002179 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00002180 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002181 for (auto *E : PrivateVars) {
2182 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2183 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00002184 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00002185 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2186 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002187 ++I;
2188 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002189 I = FirstprivateCopies.begin();
2190 auto IElemInitRef = FirstprivateInits.begin();
2191 for (auto *E : FirstprivateVars) {
2192 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2193 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00002194 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00002195 PrivateHelpersTy(
2196 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2197 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
2198 ++I, ++IElemInitRef;
2199 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002200 llvm::array_pod_sort(Privates.begin(), Privates.end(),
2201 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002202 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2203 // Build type kmp_routine_entry_t (if not built yet).
2204 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002205 // Build type kmp_task_t (if not built yet).
2206 if (KmpTaskTQTy.isNull()) {
2207 KmpTaskTQTy = C.getRecordType(
2208 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2209 }
2210 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002211 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002212 auto *KmpTaskTWithPrivatesQTyRD =
2213 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2214 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2215 QualType KmpTaskTWithPrivatesPtrQTy =
2216 C.getPointerType(KmpTaskTWithPrivatesQTy);
2217 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2218 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
2219 auto KmpTaskTWithPrivatesTySize =
2220 CGM.getSize(C.getTypeSizeInChars(KmpTaskTWithPrivatesQTy));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002221 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2222
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002223 // Emit initial values for private copies (if any).
2224 llvm::Value *TaskPrivatesMap = nullptr;
2225 auto *TaskPrivatesMapTy =
2226 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2227 3)
2228 ->getType();
2229 if (!Privates.empty()) {
2230 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2231 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2232 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2233 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2234 TaskPrivatesMap, TaskPrivatesMapTy);
2235 } else {
2236 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2237 cast<llvm::PointerType>(TaskPrivatesMapTy));
2238 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002239 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2240 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002241 auto *TaskEntry = emitProxyTaskFunction(
2242 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002243 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002244
2245 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2246 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2247 // kmp_routine_entry_t *task_entry);
2248 // Task flags. Format is taken from
2249 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2250 // description of kmp_tasking_flags struct.
2251 const unsigned TiedFlag = 0x1;
2252 const unsigned FinalFlag = 0x2;
2253 unsigned Flags = Tied ? TiedFlag : 0;
2254 auto *TaskFlags =
2255 Final.getPointer()
2256 ? CGF.Builder.CreateSelect(Final.getPointer(),
2257 CGF.Builder.getInt32(FinalFlag),
2258 CGF.Builder.getInt32(/*C=*/0))
2259 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2260 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
2261 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002262 llvm::Value *AllocArgs[] = {
2263 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), TaskFlags,
2264 KmpTaskTWithPrivatesTySize, CGM.getSize(SharedsSize),
2265 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskEntry,
2266 KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002267 auto *NewTask = CGF.EmitRuntimeCall(
2268 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002269 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2270 NewTask, KmpTaskTWithPrivatesPtrTy);
2271 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2272 KmpTaskTWithPrivatesQTy);
2273 LValue TDBase =
2274 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002275 // Fill the data in the resulting kmp_task_t record.
2276 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00002277 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002278 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002279 KmpTaskSharedsPtr =
2280 Address(CGF.EmitLoadOfScalar(
2281 CGF.EmitLValueForField(
2282 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
2283 KmpTaskTShareds)),
2284 Loc),
2285 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002286 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002287 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002288 // Emit initial values for private copies (if any).
2289 bool NeedsCleanup = false;
2290 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002291 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2292 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002293 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002294 LValue SharedsBase;
2295 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002296 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002297 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2298 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2299 SharedsTy);
2300 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002301 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2302 cast<CapturedStmt>(*D.getAssociatedStmt()));
2303 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002304 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002305 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002306 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002307 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002308 if (auto *Elem = Pair.second.PrivateElemInit) {
2309 auto *OriginalVD = Pair.second.Original;
2310 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2311 auto SharedRefLValue =
2312 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002313 SharedRefLValue = CGF.MakeAddrLValue(
2314 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
2315 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002316 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002317 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002318 // Initialize firstprivate array.
2319 if (!isa<CXXConstructExpr>(Init) ||
2320 CGF.isTrivialInitializer(Init)) {
2321 // Perform simple memcpy.
2322 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002323 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002324 } else {
2325 // Initialize firstprivate array using element-by-element
2326 // intialization.
2327 CGF.EmitOMPAggregateAssign(
2328 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002329 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00002330 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002331 // Clean up any temporaries needed by the initialization.
2332 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002333 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002334 return SrcElement;
2335 });
2336 (void)InitScope.Privatize();
2337 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00002338 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
2339 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002340 CGF.EmitAnyExprToMem(Init, DestElement,
2341 Init->getType().getQualifiers(),
2342 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002343 });
2344 }
2345 } else {
2346 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002347 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002348 return SharedRefLValue.getAddress();
2349 });
2350 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00002351 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002352 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2353 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002354 }
2355 } else {
2356 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2357 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002358 }
2359 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002360 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002361 }
2362 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002363 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002364 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002365 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2366 KmpTaskTWithPrivatesPtrQTy,
2367 KmpTaskTWithPrivatesQTy)
2368 : llvm::ConstantPointerNull::get(
2369 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2370 LValue Destructor = CGF.EmitLValueForField(
2371 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2372 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2373 DestructorFn, KmpRoutineEntryPtrTy),
2374 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002375
2376 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00002377 Address DependenciesArray = Address::invalid();
2378 unsigned NumDependencies = Dependences.size();
2379 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002380 // Dependence kind for RTL.
2381 enum RTLDependenceKindTy { DepIn = 1, DepOut = 2, DepInOut = 3 };
2382 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
2383 RecordDecl *KmpDependInfoRD;
2384 QualType FlagsTy = C.getIntTypeForBitwidth(
2385 C.toBits(C.getTypeSizeInChars(C.BoolTy)), /*Signed=*/false);
2386 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
2387 if (KmpDependInfoTy.isNull()) {
2388 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
2389 KmpDependInfoRD->startDefinition();
2390 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
2391 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
2392 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
2393 KmpDependInfoRD->completeDefinition();
2394 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
2395 } else {
2396 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
2397 }
John McCall7f416cc2015-09-08 08:05:57 +00002398 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002399 // Define type kmp_depend_info[<Dependences.size()>];
2400 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00002401 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002402 ArrayType::Normal, /*IndexTypeQuals=*/0);
2403 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00002404 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
2405 for (unsigned i = 0; i < NumDependencies; ++i) {
2406 const Expr *E = Dependences[i].second;
2407 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002408 llvm::Value *Size;
2409 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002410 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
2411 LValue UpAddrLVal =
2412 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
2413 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00002414 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002415 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00002416 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002417 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
2418 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
John McCall7f416cc2015-09-08 08:05:57 +00002419 } else {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002420 Size = getTypeSize(CGF, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002421 }
2422 auto Base = CGF.MakeAddrLValue(
2423 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002424 KmpDependInfoTy);
2425 // deps[i].base_addr = &<Dependences[i].second>;
2426 auto BaseAddrLVal = CGF.EmitLValueForField(
2427 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00002428 CGF.EmitStoreOfScalar(
2429 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
2430 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002431 // deps[i].len = sizeof(<Dependences[i].second>);
2432 auto LenLVal = CGF.EmitLValueForField(
2433 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
2434 CGF.EmitStoreOfScalar(Size, LenLVal);
2435 // deps[i].flags = <Dependences[i].first>;
2436 RTLDependenceKindTy DepKind;
2437 switch (Dependences[i].first) {
2438 case OMPC_DEPEND_in:
2439 DepKind = DepIn;
2440 break;
2441 case OMPC_DEPEND_out:
2442 DepKind = DepOut;
2443 break;
2444 case OMPC_DEPEND_inout:
2445 DepKind = DepInOut;
2446 break;
2447 case OMPC_DEPEND_unknown:
2448 llvm_unreachable("Unknown task dependence type");
2449 }
2450 auto FlagsLVal = CGF.EmitLValueForField(
2451 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
2452 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
2453 FlagsLVal);
2454 }
John McCall7f416cc2015-09-08 08:05:57 +00002455 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2456 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002457 CGF.VoidPtrTy);
2458 }
2459
Alexey Bataev62b63b12015-03-10 07:28:44 +00002460 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
2461 // libcall.
2462 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
2463 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002464 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2465 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2466 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
2467 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00002468 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002469 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002470 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
2471 llvm::Value *DepTaskArgs[7];
2472 if (NumDependencies) {
2473 DepTaskArgs[0] = UpLoc;
2474 DepTaskArgs[1] = ThreadID;
2475 DepTaskArgs[2] = NewTask;
2476 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
2477 DepTaskArgs[4] = DependenciesArray.getPointer();
2478 DepTaskArgs[5] = CGF.Builder.getInt32(0);
2479 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2480 }
2481 auto &&ThenCodeGen = [this, NumDependencies,
2482 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
2483 // TODO: add check for untied tasks.
2484 if (NumDependencies) {
2485 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
2486 DepTaskArgs);
2487 } else {
2488 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
2489 TaskArgs);
2490 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002491 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002492 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
2493 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00002494
2495 llvm::Value *DepWaitTaskArgs[6];
2496 if (NumDependencies) {
2497 DepWaitTaskArgs[0] = UpLoc;
2498 DepWaitTaskArgs[1] = ThreadID;
2499 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
2500 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
2501 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
2502 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2503 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002504 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00002505 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002506 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
2507 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2508 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
2509 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
2510 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00002511 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002512 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
2513 DepWaitTaskArgs);
2514 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
2515 // kmp_task_t *new_task);
2516 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
2517 TaskArgs);
2518 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
2519 // kmp_task_t *new_task);
2520 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
2521 NormalAndEHCleanup,
2522 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
2523 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002524
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002525 // Call proxy_task_entry(gtid, new_task);
2526 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
2527 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
2528 };
John McCall7f416cc2015-09-08 08:05:57 +00002529
Alexey Bataev1d677132015-04-22 13:57:31 +00002530 if (IfCond) {
2531 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
2532 } else {
2533 CodeGenFunction::RunCleanupsScope Scope(CGF);
2534 ThenCodeGen(CGF);
2535 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002536}
2537
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002538static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
2539 llvm::Type *ArgsType,
2540 ArrayRef<const Expr *> LHSExprs,
2541 ArrayRef<const Expr *> RHSExprs,
2542 ArrayRef<const Expr *> ReductionOps) {
2543 auto &C = CGM.getContext();
2544
2545 // void reduction_func(void *LHSArg, void *RHSArg);
2546 FunctionArgList Args;
2547 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2548 C.VoidPtrTy);
2549 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2550 C.VoidPtrTy);
2551 Args.push_back(&LHSArg);
2552 Args.push_back(&RHSArg);
2553 FunctionType::ExtInfo EI;
2554 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2555 C.VoidTy, Args, EI, /*isVariadic=*/false);
2556 auto *Fn = llvm::Function::Create(
2557 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2558 ".omp.reduction.reduction_func", &CGM.getModule());
2559 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
2560 CodeGenFunction CGF(CGM);
2561 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2562
2563 // Dst = (void*[n])(LHSArg);
2564 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002565 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2566 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2567 ArgsType), CGF.getPointerAlign());
2568 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2569 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2570 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002571
2572 // ...
2573 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
2574 // ...
2575 CodeGenFunction::OMPPrivateScope Scope(CGF);
2576 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002577 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
2578 Scope.addPrivate(RHSVar, [&]() -> Address {
2579 return emitAddrOfVarFromArray(CGF, RHS, I, RHSVar);
2580 });
2581 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
2582 Scope.addPrivate(LHSVar, [&]() -> Address {
2583 return emitAddrOfVarFromArray(CGF, LHS, I, LHSVar);
2584 });
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002585 }
2586 Scope.Privatize();
2587 for (auto *E : ReductionOps) {
2588 CGF.EmitIgnoredExpr(E);
2589 }
2590 Scope.ForceCleanup();
2591 CGF.FinishFunction();
2592 return Fn;
2593}
2594
2595void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
2596 ArrayRef<const Expr *> LHSExprs,
2597 ArrayRef<const Expr *> RHSExprs,
2598 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002599 bool WithNowait, bool SimpleReduction) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002600 // Next code should be emitted for reduction:
2601 //
2602 // static kmp_critical_name lock = { 0 };
2603 //
2604 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
2605 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
2606 // ...
2607 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
2608 // *(Type<n>-1*)rhs[<n>-1]);
2609 // }
2610 //
2611 // ...
2612 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
2613 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2614 // RedList, reduce_func, &<lock>)) {
2615 // case 1:
2616 // ...
2617 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2618 // ...
2619 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2620 // break;
2621 // case 2:
2622 // ...
2623 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2624 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00002625 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002626 // break;
2627 // default:;
2628 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002629 //
2630 // if SimpleReduction is true, only the next code is generated:
2631 // ...
2632 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2633 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002634
2635 auto &C = CGM.getContext();
2636
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002637 if (SimpleReduction) {
2638 CodeGenFunction::RunCleanupsScope Scope(CGF);
2639 for (auto *E : ReductionOps) {
2640 CGF.EmitIgnoredExpr(E);
2641 }
2642 return;
2643 }
2644
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002645 // 1. Build a list of reduction variables.
2646 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2647 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
2648 QualType ReductionArrayTy =
2649 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2650 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00002651 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002652 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2653 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002654 Address Elem =
2655 CGF.Builder.CreateConstArrayGEP(ReductionList, I, CGF.getPointerSize());
2656 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002657 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002658 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
2659 Elem);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002660 }
2661
2662 // 2. Emit reduce_func().
2663 auto *ReductionFn = emitReductionFunction(
2664 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
2665 RHSExprs, ReductionOps);
2666
2667 // 3. Create static kmp_critical_name lock = { 0 };
2668 auto *Lock = getCriticalRegionLock(".reduction");
2669
2670 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2671 // RedList, reduce_func, &<lock>);
2672 auto *IdentTLoc = emitUpdateLocation(
2673 CGF, Loc,
2674 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
2675 auto *ThreadId = getThreadID(CGF, Loc);
2676 auto *ReductionArrayTySize = llvm::ConstantInt::get(
2677 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002678 auto *RL =
2679 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
2680 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002681 llvm::Value *Args[] = {
2682 IdentTLoc, // ident_t *<loc>
2683 ThreadId, // i32 <gtid>
2684 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
2685 ReductionArrayTySize, // size_type sizeof(RedList)
2686 RL, // void *RedList
2687 ReductionFn, // void (*) (void *, void *) <reduce_func>
2688 Lock // kmp_critical_name *&<lock>
2689 };
2690 auto Res = CGF.EmitRuntimeCall(
2691 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
2692 : OMPRTL__kmpc_reduce),
2693 Args);
2694
2695 // 5. Build switch(res)
2696 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2697 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
2698
2699 // 6. Build case 1:
2700 // ...
2701 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2702 // ...
2703 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2704 // break;
2705 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2706 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2707 CGF.EmitBlock(Case1BB);
2708
2709 {
2710 CodeGenFunction::RunCleanupsScope Scope(CGF);
2711 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2712 llvm::Value *EndArgs[] = {
2713 IdentTLoc, // ident_t *<loc>
2714 ThreadId, // i32 <gtid>
2715 Lock // kmp_critical_name *&<lock>
2716 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002717 CGF.EHStack
2718 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2719 NormalAndEHCleanup,
2720 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
2721 : OMPRTL__kmpc_end_reduce),
2722 llvm::makeArrayRef(EndArgs));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002723 for (auto *E : ReductionOps) {
2724 CGF.EmitIgnoredExpr(E);
2725 }
2726 }
2727
2728 CGF.EmitBranch(DefaultBB);
2729
2730 // 7. Build case 2:
2731 // ...
2732 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2733 // ...
2734 // break;
2735 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
2736 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
2737 CGF.EmitBlock(Case2BB);
2738
2739 {
2740 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00002741 if (!WithNowait) {
2742 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
2743 llvm::Value *EndArgs[] = {
2744 IdentTLoc, // ident_t *<loc>
2745 ThreadId, // i32 <gtid>
2746 Lock // kmp_critical_name *&<lock>
2747 };
2748 CGF.EHStack
2749 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2750 NormalAndEHCleanup,
2751 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
2752 llvm::makeArrayRef(EndArgs));
2753 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002754 auto I = LHSExprs.begin();
2755 for (auto *E : ReductionOps) {
2756 const Expr *XExpr = nullptr;
2757 const Expr *EExpr = nullptr;
2758 const Expr *UpExpr = nullptr;
2759 BinaryOperatorKind BO = BO_Comma;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002760 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2761 if (BO->getOpcode() == BO_Assign) {
2762 XExpr = BO->getLHS();
2763 UpExpr = BO->getRHS();
2764 }
2765 }
Alexey Bataev69a47792015-05-07 03:54:03 +00002766 // Try to emit update expression as a simple atomic.
2767 auto *RHSExpr = UpExpr;
2768 if (RHSExpr) {
2769 // Analyze RHS part of the whole expression.
2770 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
2771 RHSExpr->IgnoreParenImpCasts())) {
2772 // If this is a conditional operator, analyze its condition for
2773 // min/max reduction operator.
2774 RHSExpr = ACO->getCond();
2775 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002776 if (auto *BORHS =
Alexey Bataev69a47792015-05-07 03:54:03 +00002777 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002778 EExpr = BORHS->getRHS();
2779 BO = BORHS->getOpcode();
2780 }
2781 }
2782 if (XExpr) {
2783 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2784 LValue X = CGF.EmitLValue(XExpr);
2785 RValue E;
2786 if (EExpr)
2787 E = CGF.EmitAnyExpr(EExpr);
2788 CGF.EmitOMPAtomicSimpleUpdateExpr(
2789 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
2790 [&CGF, UpExpr, VD](RValue XRValue) {
2791 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
2792 PrivateScope.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +00002793 VD, [&CGF, VD, XRValue]() -> Address {
2794 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002795 CGF.EmitStoreThroughLValue(
2796 XRValue,
John McCall7f416cc2015-09-08 08:05:57 +00002797 CGF.MakeAddrLValue(LHSTemp, VD->getType()));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002798 return LHSTemp;
2799 });
2800 (void)PrivateScope.Privatize();
2801 return CGF.EmitAnyExpr(UpExpr);
2802 });
2803 } else {
2804 // Emit as a critical region.
2805 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
2806 CGF.EmitIgnoredExpr(E);
2807 }, Loc);
2808 }
2809 ++I;
2810 }
2811 }
2812
2813 CGF.EmitBranch(DefaultBB);
2814 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2815}
2816
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002817void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
2818 SourceLocation Loc) {
2819 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2820 // global_tid);
2821 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2822 // Ignore return result until untied tasks are supported.
2823 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
2824}
2825
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002826void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002827 OpenMPDirectiveKind InnerKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002828 const RegionCodeGenTy &CodeGen) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002829 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002830 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002831}
2832
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002833namespace {
2834enum RTCancelKind {
2835 CancelNoreq = 0,
2836 CancelParallel = 1,
2837 CancelLoop = 2,
2838 CancelSections = 3,
2839 CancelTaskgroup = 4
2840};
2841}
2842
2843static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
2844 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00002845 if (CancelRegion == OMPD_parallel)
2846 CancelKind = CancelParallel;
2847 else if (CancelRegion == OMPD_for)
2848 CancelKind = CancelLoop;
2849 else if (CancelRegion == OMPD_sections)
2850 CancelKind = CancelSections;
2851 else {
2852 assert(CancelRegion == OMPD_taskgroup);
2853 CancelKind = CancelTaskgroup;
2854 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002855 return CancelKind;
2856}
2857
2858void CGOpenMPRuntime::emitCancellationPointCall(
2859 CodeGenFunction &CGF, SourceLocation Loc,
2860 OpenMPDirectiveKind CancelRegion) {
2861 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2862 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002863 if (auto *OMPRegionInfo =
2864 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2865 auto CancelDest =
2866 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2867 if (CancelDest.isValid()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002868 llvm::Value *Args[] = {
2869 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2870 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002871 // Ignore return result until untied tasks are supported.
2872 auto *Result = CGF.EmitRuntimeCall(
2873 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
2874 // if (__kmpc_cancellationpoint()) {
2875 // __kmpc_cancel_barrier();
2876 // exit from construct;
2877 // }
2878 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2879 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2880 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2881 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2882 CGF.EmitBlock(ExitBB);
2883 // __kmpc_cancel_barrier();
2884 emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
2885 // exit from construct;
2886 CGF.EmitBranchThroughCleanup(CancelDest);
2887 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2888 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002889 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002890}
2891
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002892void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
2893 OpenMPDirectiveKind CancelRegion) {
2894 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2895 // kmp_int32 cncl_kind);
2896 if (auto *OMPRegionInfo =
2897 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2898 auto CancelDest =
2899 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2900 if (CancelDest.isValid()) {
2901 llvm::Value *Args[] = {
2902 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2903 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
2904 // Ignore return result until untied tasks are supported.
2905 auto *Result =
2906 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
2907 // if (__kmpc_cancel()) {
2908 // __kmpc_cancel_barrier();
2909 // exit from construct;
2910 // }
2911 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2912 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2913 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2914 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2915 CGF.EmitBlock(ExitBB);
2916 // __kmpc_cancel_barrier();
2917 emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
2918 // exit from construct;
2919 CGF.EmitBranchThroughCleanup(CancelDest);
2920 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2921 }
2922 }
2923}