blob: f7caee1bbc4f50a260451d7e8a02994cc161f493 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
Alexey Bataev36bf0112015-03-10 05:15:26 +000016#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000017#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000020#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Value.h"
24#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000025#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000026
27using namespace clang;
28using namespace CodeGen;
29
Benjamin Kramerc52193f2014-10-10 13:57:57 +000030namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000031/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000032class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
33public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000034 /// \brief Kinds of OpenMP regions used in codegen.
35 enum CGOpenMPRegionKind {
36 /// \brief Region with outlined function for standalone 'parallel'
37 /// directive.
38 ParallelOutlinedRegion,
39 /// \brief Region with outlined function for standalone 'task' directive.
40 TaskOutlinedRegion,
41 /// \brief Region for constructs that do not require function outlining,
42 /// like 'for', 'sections', 'atomic' etc. directives.
43 InlinedRegion,
44 };
Alexey Bataev18095712014-10-10 12:19:54 +000045
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 CGOpenMPRegionInfo(const CapturedStmt &CS,
47 const CGOpenMPRegionKind RegionKind,
48 const RegionCodeGenTy &CodeGen)
49 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
50 CodeGen(CodeGen) {}
51
52 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
53 const RegionCodeGenTy &CodeGen)
54 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind),
55 CodeGen(CodeGen) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000056
57 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000058 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000059 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000060
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000061 /// \brief Emit the captured statement body.
62 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
63
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000065 /// \return LValue for thread id variable. This LValue always has type int32*.
66 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069
Alexey Bataev18095712014-10-10 12:19:54 +000070 static bool classof(const CGCapturedStmtInfo *Info) {
71 return Info->getKind() == CR_OpenMP;
72 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000073
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000074protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075 CGOpenMPRegionKind RegionKind;
76 const RegionCodeGenTy &CodeGen;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000077};
Alexey Bataev18095712014-10-10 12:19:54 +000078
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079/// \brief API for captured statement code generation in OpenMP constructs.
80class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
81public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000082 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
83 const RegionCodeGenTy &CodeGen)
84 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen),
85 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000086 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
87 }
88 /// \brief Get a variable or parameter for storing global thread id
89 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +000090 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091
Alexey Bataev18095712014-10-10 12:19:54 +000092 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +000093 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +000094
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095 static bool classof(const CGCapturedStmtInfo *Info) {
96 return CGOpenMPRegionInfo::classof(Info) &&
97 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
98 ParallelOutlinedRegion;
99 }
100
Alexey Bataev18095712014-10-10 12:19:54 +0000101private:
102 /// \brief A variable or parameter storing global thread id for OpenMP
103 /// constructs.
104 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000105};
106
Alexey Bataev62b63b12015-03-10 07:28:44 +0000107/// \brief API for captured statement code generation in OpenMP constructs.
108class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
109public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000110 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000111 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000112 const RegionCodeGenTy &CodeGen)
113 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen),
114 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000115 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
116 }
117 /// \brief Get a variable or parameter for storing global thread id
118 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000119 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000120
121 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000122 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000123
Alexey Bataev62b63b12015-03-10 07:28:44 +0000124 /// \brief Get the name of the capture helper.
125 StringRef getHelperName() const override { return ".omp_outlined."; }
126
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000127 static bool classof(const CGCapturedStmtInfo *Info) {
128 return CGOpenMPRegionInfo::classof(Info) &&
129 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
130 TaskOutlinedRegion;
131 }
132
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133private:
134 /// \brief A variable or parameter storing global thread id for OpenMP
135 /// constructs.
136 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000137};
138
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000139/// \brief API for inlined captured statement code generation in OpenMP
140/// constructs.
141class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
142public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000143 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
144 const RegionCodeGenTy &CodeGen)
145 : CGOpenMPRegionInfo(InlinedRegion, CodeGen), OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000146 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
147 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000148 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000149 if (OuterRegionInfo)
150 return OuterRegionInfo->getContextValue();
151 llvm_unreachable("No context value for inlined OpenMP region");
152 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000153 virtual void setContextValue(llvm::Value *V) override {
154 if (OuterRegionInfo) {
155 OuterRegionInfo->setContextValue(V);
156 return;
157 }
158 llvm_unreachable("No context value for inlined OpenMP region");
159 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000160 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000161 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000162 if (OuterRegionInfo)
163 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000164 // If there is no outer outlined region,no need to lookup in a list of
165 // captured variables, we can use the original one.
166 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000167 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000168 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000169 if (OuterRegionInfo)
170 return OuterRegionInfo->getThisFieldDecl();
171 return nullptr;
172 }
173 /// \brief Get a variable or parameter for storing global thread id
174 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000175 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000176 if (OuterRegionInfo)
177 return OuterRegionInfo->getThreadIDVariable();
178 return nullptr;
179 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000180
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000181 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000182 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000183 if (auto *OuterRegionInfo = getOldCSI())
184 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000185 llvm_unreachable("No helper name for inlined OpenMP construct");
186 }
187
188 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
189
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000190 static bool classof(const CGCapturedStmtInfo *Info) {
191 return CGOpenMPRegionInfo::classof(Info) &&
192 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
193 }
194
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000195private:
196 /// \brief CodeGen info about outer OpenMP region.
197 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
198 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000199};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000200
201/// \brief RAII for emitting code of OpenMP constructs.
202class InlinedOpenMPRegionRAII {
203 CodeGenFunction &CGF;
204
205public:
206 /// \brief Constructs region for combined constructs.
207 /// \param CodeGen Code generation sequence for combined directives. Includes
208 /// a list of functions used for code generation of implicitly inlined
209 /// regions.
210 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen)
211 : CGF(CGF) {
212 // Start emission for the construct.
213 CGF.CapturedStmtInfo =
214 new CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, CodeGen);
215 }
216 ~InlinedOpenMPRegionRAII() {
217 // Restore original CapturedStmtInfo only if we're done with code emission.
218 auto *OldCSI =
219 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
220 delete CGF.CapturedStmtInfo;
221 CGF.CapturedStmtInfo = OldCSI;
222 }
223};
224
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000225} // namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000226
227LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
228 return CGF.MakeNaturalAlignAddrLValue(
Alexey Bataev62b63b12015-03-10 07:28:44 +0000229 CGF.Builder.CreateAlignedLoad(
230 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
231 CGF.PointerAlignInBytes),
232 getThreadIDVariable()
233 ->getType()
234 ->castAs<PointerType>()
235 ->getPointeeType());
Alexey Bataev18095712014-10-10 12:19:54 +0000236}
237
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
239 // 1.2.2 OpenMP Language Terminology
240 // Structured block - An executable statement with a single entry at the
241 // top and a single exit at the bottom.
242 // The point of exit cannot be a branch out of the structured block.
243 // longjmp() and throw() must not violate the entry/exit criteria.
244 CGF.EHStack.pushTerminate();
245 {
246 CodeGenFunction::RunCleanupsScope Scope(CGF);
247 CodeGen(CGF);
248 }
249 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000250}
251
Alexey Bataev62b63b12015-03-10 07:28:44 +0000252LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
253 CodeGenFunction &CGF) {
254 return CGF.MakeNaturalAlignAddrLValue(
255 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
256 getThreadIDVariable()->getType());
257}
258
Alexey Bataev9959db52014-05-06 10:08:46 +0000259CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000260 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000261 IdentTy = llvm::StructType::create(
262 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
263 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000264 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000265 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000266 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
267 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000268 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000269 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000270}
271
Alexey Bataev91797552015-03-18 04:13:55 +0000272void CGOpenMPRuntime::clear() {
273 InternalVars.clear();
274}
275
Alexey Bataev9959db52014-05-06 10:08:46 +0000276llvm::Value *
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277CGOpenMPRuntime::emitParallelOutlinedFunction(const OMPExecutableDirective &D,
278 const VarDecl *ThreadIDVar,
279 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000280 assert(ThreadIDVar->getType()->isPointerType() &&
281 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000282 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
283 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000284 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataev18095712014-10-10 12:19:54 +0000285 CGF.CapturedStmtInfo = &CGInfo;
286 return CGF.GenerateCapturedStmtFunction(*CS);
287}
288
289llvm::Value *
Alexey Bataev62b63b12015-03-10 07:28:44 +0000290CGOpenMPRuntime::emitTaskOutlinedFunction(const OMPExecutableDirective &D,
291 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000292 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000293 assert(!ThreadIDVar->getType()->isPointerType() &&
294 "thread id variable must be of type kmp_int32 for tasks");
295 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
296 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000297 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000298 CGF.CapturedStmtInfo = &CGInfo;
299 return CGF.GenerateCapturedStmtFunction(*CS);
300}
301
302llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000303CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000304 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000305 if (!Entry) {
306 if (!DefaultOpenMPPSource) {
307 // Initialize default location for psource field of ident_t structure of
308 // all ident_t objects. Format is ";file;function;line;column;;".
309 // Taken from
310 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
311 DefaultOpenMPPSource =
312 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
313 DefaultOpenMPPSource =
314 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
315 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000316 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
317 CGM.getModule(), IdentTy, /*isConstant*/ true,
318 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000319 DefaultOpenMPLocation->setUnnamedAddr(true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000320
321 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000322 llvm::Constant *Values[] = {Zero,
323 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
324 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000325 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
326 DefaultOpenMPLocation->setInitializer(Init);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000327 OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000328 return DefaultOpenMPLocation;
329 }
330 return Entry;
331}
332
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000333llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
334 SourceLocation Loc,
335 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000336 // If no debug info is generated - return global default location.
337 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
338 Loc.isInvalid())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000339 return getOrCreateDefaultLocation(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000340
341 assert(CGF.CurFn && "No function in current CodeGenFunction.");
342
Alexey Bataev9959db52014-05-06 10:08:46 +0000343 llvm::Value *LocValue = nullptr;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000344 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
345 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataev18095712014-10-10 12:19:54 +0000346 LocValue = I->second.DebugLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +0000347 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
348 // GetOpenMPThreadID was called before this routine.
349 if (LocValue == nullptr) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000350 // Generate "ident_t .kmpc_loc.addr;"
351 llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
Alexey Bataev9959db52014-05-06 10:08:46 +0000352 AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
Alexey Bataev18095712014-10-10 12:19:54 +0000353 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
354 Elem.second.DebugLoc = AI;
Alexey Bataev9959db52014-05-06 10:08:46 +0000355 LocValue = AI;
356
357 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
358 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000359 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataev9959db52014-05-06 10:08:46 +0000360 llvm::ConstantExpr::getSizeOf(IdentTy),
361 CGM.PointerAlignInBytes);
362 }
363
364 // char **psource = &.kmpc_loc_<flags>.addr.psource;
David Blaikie1ed728c2015-04-05 22:45:47 +0000365 auto *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(IdentTy, LocValue, 0,
366 IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000367
Alexey Bataevf002aca2014-05-30 05:48:40 +0000368 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
369 if (OMPDebugLoc == nullptr) {
370 SmallString<128> Buffer2;
371 llvm::raw_svector_ostream OS2(Buffer2);
372 // Build debug location
373 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
374 OS2 << ";" << PLoc.getFilename() << ";";
375 if (const FunctionDecl *FD =
376 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
377 OS2 << FD->getQualifiedNameAsString();
378 }
379 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
380 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
381 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000382 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000383 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000384 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
385
Alexey Bataev9959db52014-05-06 10:08:46 +0000386 return LocValue;
387}
388
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000389llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
390 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000391 assert(CGF.CurFn && "No function in current CodeGenFunction.");
392
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000393 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000394 // Check whether we've already cached a load of the thread id in this
395 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000396 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000397 if (I != OpenMPLocThreadIDMap.end()) {
398 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000399 if (ThreadID != nullptr)
400 return ThreadID;
401 }
402 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000403 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000404 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000405 // Check if this an outlined function with thread id passed as argument.
406 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000407 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
408 // If value loaded in entry block, cache it and use it everywhere in
409 // function.
410 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
411 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
412 Elem.second.ThreadID = ThreadID;
413 }
414 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000415 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000416 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000417
418 // This is not an outlined function region - need to call __kmpc_int32
419 // kmpc_global_thread_num(ident_t *loc).
420 // Generate thread id value and cache this value for use across the
421 // function.
422 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
423 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
424 ThreadID =
425 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
426 emitUpdateLocation(CGF, Loc));
427 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
428 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000429 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000430}
431
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000432void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000433 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000434 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
435 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000436}
437
438llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
439 return llvm::PointerType::getUnqual(IdentTy);
440}
441
442llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
443 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
444}
445
446llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000447CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000448 llvm::Constant *RTLFn = nullptr;
449 switch (Function) {
450 case OMPRTL__kmpc_fork_call: {
451 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
452 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000453 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
454 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000455 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000456 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000457 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
458 break;
459 }
460 case OMPRTL__kmpc_global_thread_num: {
461 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000462 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000463 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
466 break;
467 }
Alexey Bataev97720002014-11-11 04:05:39 +0000468 case OMPRTL__kmpc_threadprivate_cached: {
469 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
470 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
472 CGM.VoidPtrTy, CGM.SizeTy,
473 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
474 llvm::FunctionType *FnTy =
475 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
476 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
477 break;
478 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000479 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000480 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
481 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000482 llvm::Type *TypeParams[] = {
483 getIdentTyPointerTy(), CGM.Int32Ty,
484 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
485 llvm::FunctionType *FnTy =
486 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
487 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
488 break;
489 }
Alexey Bataev97720002014-11-11 04:05:39 +0000490 case OMPRTL__kmpc_threadprivate_register: {
491 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
492 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
493 // typedef void *(*kmpc_ctor)(void *);
494 auto KmpcCtorTy =
495 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
496 /*isVarArg*/ false)->getPointerTo();
497 // typedef void *(*kmpc_cctor)(void *, void *);
498 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
499 auto KmpcCopyCtorTy =
500 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
501 /*isVarArg*/ false)->getPointerTo();
502 // typedef void (*kmpc_dtor)(void *);
503 auto KmpcDtorTy =
504 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
505 ->getPointerTo();
506 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
507 KmpcCopyCtorTy, KmpcDtorTy};
508 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
509 /*isVarArg*/ false);
510 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
511 break;
512 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000513 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000514 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
515 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000516 llvm::Type *TypeParams[] = {
517 getIdentTyPointerTy(), CGM.Int32Ty,
518 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
519 llvm::FunctionType *FnTy =
520 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
521 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
522 break;
523 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000524 case OMPRTL__kmpc_cancel_barrier: {
525 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
526 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000527 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
528 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000529 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
530 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000531 break;
532 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000533 case OMPRTL__kmpc_for_static_fini: {
534 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
535 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
536 llvm::FunctionType *FnTy =
537 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
538 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
539 break;
540 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000541 case OMPRTL__kmpc_push_num_threads: {
542 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
543 // kmp_int32 num_threads)
544 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
545 CGM.Int32Ty};
546 llvm::FunctionType *FnTy =
547 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
548 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
549 break;
550 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000551 case OMPRTL__kmpc_serialized_parallel: {
552 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
553 // global_tid);
554 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
555 llvm::FunctionType *FnTy =
556 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
557 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
558 break;
559 }
560 case OMPRTL__kmpc_end_serialized_parallel: {
561 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
562 // global_tid);
563 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
564 llvm::FunctionType *FnTy =
565 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
566 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
567 break;
568 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000569 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000570 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000571 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
572 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000573 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
575 break;
576 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000577 case OMPRTL__kmpc_master: {
578 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
580 llvm::FunctionType *FnTy =
581 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
582 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
583 break;
584 }
585 case OMPRTL__kmpc_end_master: {
586 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
587 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
588 llvm::FunctionType *FnTy =
589 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
590 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
591 break;
592 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000593 case OMPRTL__kmpc_omp_taskyield: {
594 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
595 // int end_part);
596 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
597 llvm::FunctionType *FnTy =
598 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
599 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
600 break;
601 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000602 case OMPRTL__kmpc_single: {
603 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
604 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
605 llvm::FunctionType *FnTy =
606 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
607 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
608 break;
609 }
610 case OMPRTL__kmpc_end_single: {
611 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
612 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
613 llvm::FunctionType *FnTy =
614 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
615 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
616 break;
617 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000618 case OMPRTL__kmpc_omp_task_alloc: {
619 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
620 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
621 // kmp_routine_entry_t *task_entry);
622 assert(KmpRoutineEntryPtrTy != nullptr &&
623 "Type kmp_routine_entry_t must be created.");
624 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
625 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
626 // Return void * and then cast to particular kmp_task_t type.
627 llvm::FunctionType *FnTy =
628 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
629 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
630 break;
631 }
632 case OMPRTL__kmpc_omp_task: {
633 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
634 // *new_task);
635 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
636 CGM.VoidPtrTy};
637 llvm::FunctionType *FnTy =
638 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
639 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
640 break;
641 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000642 case OMPRTL__kmpc_copyprivate: {
643 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
644 // kmp_int32 cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
645 // kmp_int32 didit);
646 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
647 auto *CpyFnTy =
648 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
650 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
651 CGM.Int32Ty};
652 llvm::FunctionType *FnTy =
653 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
654 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
655 break;
656 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000657 case OMPRTL__kmpc_reduce: {
658 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
659 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
660 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
661 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
662 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
663 /*isVarArg=*/false);
664 llvm::Type *TypeParams[] = {
665 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
666 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
667 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
668 llvm::FunctionType *FnTy =
669 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
670 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
671 break;
672 }
673 case OMPRTL__kmpc_reduce_nowait: {
674 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
675 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
676 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
677 // *lck);
678 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
679 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
680 /*isVarArg=*/false);
681 llvm::Type *TypeParams[] = {
682 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
683 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
684 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
685 llvm::FunctionType *FnTy =
686 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
687 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
688 break;
689 }
690 case OMPRTL__kmpc_end_reduce: {
691 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
692 // kmp_critical_name *lck);
693 llvm::Type *TypeParams[] = {
694 getIdentTyPointerTy(), CGM.Int32Ty,
695 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
696 llvm::FunctionType *FnTy =
697 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
698 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
699 break;
700 }
701 case OMPRTL__kmpc_end_reduce_nowait: {
702 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
703 // kmp_critical_name *lck);
704 llvm::Type *TypeParams[] = {
705 getIdentTyPointerTy(), CGM.Int32Ty,
706 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
707 llvm::FunctionType *FnTy =
708 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
709 RTLFn =
710 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
711 break;
712 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000713 case OMPRTL__kmpc_ordered: {
714 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
715 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
716 llvm::FunctionType *FnTy =
717 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
718 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
719 break;
720 }
721 case OMPRTL__kmpc_end_ordered: {
722 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
723 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
724 llvm::FunctionType *FnTy =
725 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
726 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
727 break;
728 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000729 }
730 return RTLFn;
731}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000732
Alexander Musman21212e42015-03-13 10:38:23 +0000733llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
734 bool IVSigned) {
735 assert((IVSize == 32 || IVSize == 64) &&
736 "IV size is not compatible with the omp runtime");
737 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
738 : "__kmpc_for_static_init_4u")
739 : (IVSigned ? "__kmpc_for_static_init_8"
740 : "__kmpc_for_static_init_8u");
741 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
742 auto PtrTy = llvm::PointerType::getUnqual(ITy);
743 llvm::Type *TypeParams[] = {
744 getIdentTyPointerTy(), // loc
745 CGM.Int32Ty, // tid
746 CGM.Int32Ty, // schedtype
747 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
748 PtrTy, // p_lower
749 PtrTy, // p_upper
750 PtrTy, // p_stride
751 ITy, // incr
752 ITy // chunk
753 };
754 llvm::FunctionType *FnTy =
755 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
756 return CGM.CreateRuntimeFunction(FnTy, Name);
757}
758
Alexander Musman92bdaab2015-03-12 13:37:50 +0000759llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
760 bool IVSigned) {
761 assert((IVSize == 32 || IVSize == 64) &&
762 "IV size is not compatible with the omp runtime");
763 auto Name =
764 IVSize == 32
765 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
766 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
767 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
768 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
769 CGM.Int32Ty, // tid
770 CGM.Int32Ty, // schedtype
771 ITy, // lower
772 ITy, // upper
773 ITy, // stride
774 ITy // chunk
775 };
776 llvm::FunctionType *FnTy =
777 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
778 return CGM.CreateRuntimeFunction(FnTy, Name);
779}
780
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000781llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
782 bool IVSigned) {
783 assert((IVSize == 32 || IVSize == 64) &&
784 "IV size is not compatible with the omp runtime");
785 auto Name =
786 IVSize == 32
787 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
788 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
789 llvm::Type *TypeParams[] = {
790 getIdentTyPointerTy(), // loc
791 CGM.Int32Ty, // tid
792 };
793 llvm::FunctionType *FnTy =
794 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
795 return CGM.CreateRuntimeFunction(FnTy, Name);
796}
797
Alexander Musman92bdaab2015-03-12 13:37:50 +0000798llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
799 bool IVSigned) {
800 assert((IVSize == 32 || IVSize == 64) &&
801 "IV size is not compatible with the omp runtime");
802 auto Name =
803 IVSize == 32
804 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
805 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
806 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
807 auto PtrTy = llvm::PointerType::getUnqual(ITy);
808 llvm::Type *TypeParams[] = {
809 getIdentTyPointerTy(), // loc
810 CGM.Int32Ty, // tid
811 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
812 PtrTy, // p_lower
813 PtrTy, // p_upper
814 PtrTy // p_stride
815 };
816 llvm::FunctionType *FnTy =
817 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
818 return CGM.CreateRuntimeFunction(FnTy, Name);
819}
820
Alexey Bataev97720002014-11-11 04:05:39 +0000821llvm::Constant *
822CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
823 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000824 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000825 Twine(CGM.getMangledName(VD)) + ".cache.");
826}
827
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000828llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
829 const VarDecl *VD,
830 llvm::Value *VDAddr,
831 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000832 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000833 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000834 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
835 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
836 getOrCreateThreadPrivateCache(VD)};
837 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000838 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000839}
840
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000841void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000842 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
843 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
844 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
845 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000846 auto OMPLoc = emitUpdateLocation(CGF, Loc);
847 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000848 OMPLoc);
849 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
850 // to register constructor/destructor for variable.
851 llvm::Value *Args[] = {OMPLoc,
852 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
853 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000854 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000855 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000856}
857
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000858llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000859 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
860 bool PerformInit, CodeGenFunction *CGF) {
861 VD = VD->getDefinition(CGM.getContext());
862 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
863 ThreadPrivateWithDefinition.insert(VD);
864 QualType ASTTy = VD->getType();
865
866 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
867 auto Init = VD->getAnyInitializer();
868 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
869 // Generate function that re-emits the declaration's initializer into the
870 // threadprivate copy of the variable VD
871 CodeGenFunction CtorCGF(CGM);
872 FunctionArgList Args;
873 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
874 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
875 Args.push_back(&Dst);
876
877 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
878 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
879 /*isVariadic=*/false);
880 auto FTy = CGM.getTypes().GetFunctionType(FI);
881 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
882 FTy, ".__kmpc_global_ctor_.", Loc);
883 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
884 Args, SourceLocation());
885 auto ArgVal = CtorCGF.EmitLoadOfScalar(
886 CtorCGF.GetAddrOfLocalVar(&Dst),
887 /*Volatile=*/false, CGM.PointerAlignInBytes,
888 CGM.getContext().VoidPtrTy, Dst.getLocation());
889 auto Arg = CtorCGF.Builder.CreatePointerCast(
890 ArgVal,
891 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
892 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
893 /*IsInitializer=*/true);
894 ArgVal = CtorCGF.EmitLoadOfScalar(
895 CtorCGF.GetAddrOfLocalVar(&Dst),
896 /*Volatile=*/false, CGM.PointerAlignInBytes,
897 CGM.getContext().VoidPtrTy, Dst.getLocation());
898 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
899 CtorCGF.FinishFunction();
900 Ctor = Fn;
901 }
902 if (VD->getType().isDestructedType() != QualType::DK_none) {
903 // Generate function that emits destructor call for the threadprivate copy
904 // of the variable VD
905 CodeGenFunction DtorCGF(CGM);
906 FunctionArgList Args;
907 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
908 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
909 Args.push_back(&Dst);
910
911 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
912 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
913 /*isVariadic=*/false);
914 auto FTy = CGM.getTypes().GetFunctionType(FI);
915 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
916 FTy, ".__kmpc_global_dtor_.", Loc);
917 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
918 SourceLocation());
919 auto ArgVal = DtorCGF.EmitLoadOfScalar(
920 DtorCGF.GetAddrOfLocalVar(&Dst),
921 /*Volatile=*/false, CGM.PointerAlignInBytes,
922 CGM.getContext().VoidPtrTy, Dst.getLocation());
923 DtorCGF.emitDestroy(ArgVal, ASTTy,
924 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
925 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
926 DtorCGF.FinishFunction();
927 Dtor = Fn;
928 }
929 // Do not emit init function if it is not required.
930 if (!Ctor && !Dtor)
931 return nullptr;
932
933 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
934 auto CopyCtorTy =
935 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
936 /*isVarArg=*/false)->getPointerTo();
937 // Copying constructor for the threadprivate variable.
938 // Must be NULL - reserved by runtime, but currently it requires that this
939 // parameter is always NULL. Otherwise it fires assertion.
940 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
941 if (Ctor == nullptr) {
942 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
943 /*isVarArg=*/false)->getPointerTo();
944 Ctor = llvm::Constant::getNullValue(CtorTy);
945 }
946 if (Dtor == nullptr) {
947 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
948 /*isVarArg=*/false)->getPointerTo();
949 Dtor = llvm::Constant::getNullValue(DtorTy);
950 }
951 if (!CGF) {
952 auto InitFunctionTy =
953 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
954 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
955 InitFunctionTy, ".__omp_threadprivate_init_.");
956 CodeGenFunction InitCGF(CGM);
957 FunctionArgList ArgList;
958 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
959 CGM.getTypes().arrangeNullaryFunction(), ArgList,
960 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000961 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000962 InitCGF.FinishFunction();
963 return InitFunction;
964 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000965 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000966 }
967 return nullptr;
968}
969
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000970void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
971 llvm::Value *OutlinedFn,
972 llvm::Value *CapturedStruct) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000973 // Build call __kmpc_fork_call(loc, 1, microtask, captured_struct/*context*/)
974 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000975 emitUpdateLocation(CGF, Loc),
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000976 CGF.Builder.getInt32(1), // Number of arguments after 'microtask' argument
977 // (there is only one additional argument - 'context')
978 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
979 CGF.EmitCastToVoidPtr(CapturedStruct)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000980 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000981 CGF.EmitRuntimeCall(RTLFn, Args);
982}
983
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000984void CGOpenMPRuntime::emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
985 llvm::Value *OutlinedFn,
986 llvm::Value *CapturedStruct) {
987 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000988 // Build calls:
989 // __kmpc_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000990 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), ThreadID};
991 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
992 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000993
994 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000995 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000996 auto Int32Ty =
997 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
998 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
999 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1000 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
1001 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
1002
1003 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001004 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1005 CGF.EmitRuntimeCall(
1006 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001007}
1008
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001009// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001010// thread-ID variable (it is passed in a first argument of the outlined function
1011// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1012// regular serial code region, get thread ID by calling kmp_int32
1013// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1014// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001015llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +00001016 SourceLocation Loc) {
1017 if (auto OMPRegionInfo =
1018 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001019 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001020 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001021
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001022 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001023 auto Int32Ty =
1024 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1025 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1026 CGF.EmitStoreOfScalar(ThreadID,
1027 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
1028
1029 return ThreadIDTemp;
1030}
1031
Alexey Bataev97720002014-11-11 04:05:39 +00001032llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001033CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001034 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001035 SmallString<256> Buffer;
1036 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001037 Out << Name;
1038 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001039 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1040 if (Elem.second) {
1041 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001042 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001043 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001044 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001045
David Blaikie13156b62014-11-19 03:06:06 +00001046 return Elem.second = new llvm::GlobalVariable(
1047 CGM.getModule(), Ty, /*IsConstant*/ false,
1048 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1049 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001050}
1051
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001052llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001053 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001054 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001055}
1056
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001057namespace {
1058class CallEndCleanup : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001059public:
1060 typedef ArrayRef<llvm::Value *> CleanupValuesTy;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001061private:
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001062 llvm::Value *Callee;
1063 llvm::SmallVector<llvm::Value *, 8> Args;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001064
1065public:
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001066 CallEndCleanup(llvm::Value *Callee, CleanupValuesTy Args)
1067 : Callee(Callee), Args(Args.begin(), Args.end()) {}
1068 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1069 CGF.EmitRuntimeCall(Callee, Args);
1070 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001071};
1072} // namespace
1073
1074void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1075 StringRef CriticalName,
1076 const RegionCodeGenTy &CriticalOpGen,
1077 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001078 // __kmpc_critical(ident_t *, gtid, Lock);
1079 // CriticalOpGen();
1080 // __kmpc_end_critical(ident_t *, gtid, Lock);
1081 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001082 {
1083 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001084 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1085 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001086 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001087 // Build a call to __kmpc_end_critical
1088 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001089 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1090 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001091 emitInlinedDirective(CGF, CriticalOpGen);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001092 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001093}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001094
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001095static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001096 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001097 llvm::Value *CallBool = CGF.EmitScalarConversion(
1098 IfCond,
1099 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1100 CGF.getContext().BoolTy);
1101
1102 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1103 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1104 // Generate the branch (If-stmt)
1105 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1106 CGF.EmitBlock(ThenBlock);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001107 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001108 // Emit the rest of bblocks/branches
1109 CGF.EmitBranch(ContBlock);
1110 CGF.EmitBlock(ContBlock, true);
1111}
1112
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001113void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001114 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001115 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001116 // if(__kmpc_master(ident_t *, gtid)) {
1117 // MasterOpGen();
1118 // __kmpc_end_master(ident_t *, gtid);
1119 // }
1120 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001121 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001122 auto *IsMaster =
1123 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001124 emitIfStmt(CGF, IsMaster, [&](CodeGenFunction &CGF) -> void {
1125 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001126 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001127 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1128 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001129 MasterOpGen(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001130 });
1131}
1132
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001133void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1134 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001135 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1136 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001137 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001138 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001139 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001140}
1141
Alexey Bataeva63048e2015-03-23 06:18:07 +00001142static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001143 CodeGenModule &CGM, llvm::Type *ArgsType,
1144 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1145 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001146 auto &C = CGM.getContext();
1147 // void copy_func(void *LHSArg, void *RHSArg);
1148 FunctionArgList Args;
1149 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1150 C.VoidPtrTy);
1151 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1152 C.VoidPtrTy);
1153 Args.push_back(&LHSArg);
1154 Args.push_back(&RHSArg);
1155 FunctionType::ExtInfo EI;
1156 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1157 C.VoidTy, Args, EI, /*isVariadic=*/false);
1158 auto *Fn = llvm::Function::Create(
1159 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1160 ".omp.copyprivate.copy_func", &CGM.getModule());
1161 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1162 CodeGenFunction CGF(CGM);
1163 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001164 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001165 // Src = (void*[n])(RHSArg);
1166 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1167 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1168 CGF.PointerAlignInBytes),
1169 ArgsType);
1170 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1171 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1172 CGF.PointerAlignInBytes),
1173 ArgsType);
1174 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1175 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1176 // ...
1177 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001178 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataev420d45b2015-04-14 05:11:24 +00001179 auto *DestAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1180 CGF.Builder.CreateAlignedLoad(
1181 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1182 CGM.PointerAlignInBytes),
1183 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1184 auto *SrcAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1185 CGF.Builder.CreateAlignedLoad(
1186 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1187 CGM.PointerAlignInBytes),
1188 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1189 CGF.EmitOMPCopy(CGF, CopyprivateVars[I]->getType(), DestAddr, SrcAddr,
1190 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()),
1191 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1192 AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001193 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001194 CGF.FinishFunction();
1195 return Fn;
1196}
1197
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001198void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001199 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001200 SourceLocation Loc,
1201 ArrayRef<const Expr *> CopyprivateVars,
1202 ArrayRef<const Expr *> SrcExprs,
1203 ArrayRef<const Expr *> DstExprs,
1204 ArrayRef<const Expr *> AssignmentOps) {
1205 assert(CopyprivateVars.size() == SrcExprs.size() &&
1206 CopyprivateVars.size() == DstExprs.size() &&
1207 CopyprivateVars.size() == AssignmentOps.size());
1208 auto &C = CGM.getContext();
1209 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001210 // if(__kmpc_single(ident_t *, gtid)) {
1211 // SingleOpGen();
1212 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001213 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001214 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001215 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1216 // <copy_func>, did_it);
1217
1218 llvm::AllocaInst *DidIt = nullptr;
1219 if (!CopyprivateVars.empty()) {
1220 // int32 did_it = 0;
1221 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1222 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
1223 CGF.InitTempAlloca(DidIt, CGF.Builder.getInt32(0));
1224 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001225 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001226 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001227 auto *IsSingle =
1228 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001229 emitIfStmt(CGF, IsSingle, [&](CodeGenFunction &CGF) -> void {
1230 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001231 CGF.EHStack.pushCleanup<CallEndCleanup>(
1232 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1233 llvm::makeArrayRef(Args));
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001234 SingleOpGen(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001235 if (DidIt) {
1236 // did_it = 1;
1237 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1238 DidIt->getAlignment());
1239 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001240 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001241 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1242 // <copy_func>, did_it);
1243 if (DidIt) {
1244 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1245 auto CopyprivateArrayTy =
1246 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1247 /*IndexTypeQuals=*/0);
1248 // Create a list of all private variables for copyprivate.
1249 auto *CopyprivateList =
1250 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1251 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001252 auto *Elem = CGF.Builder.CreateStructGEP(
1253 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001254 CGF.Builder.CreateAlignedStore(
1255 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1256 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1257 Elem, CGM.PointerAlignInBytes);
1258 }
1259 // Build function that copies private values from single region to all other
1260 // threads in the corresponding parallel region.
1261 auto *CpyFn = emitCopyprivateCopyFunction(
1262 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001263 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001264 auto *BufSize = CGF.Builder.getInt32(
1265 C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
1266 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1267 CGF.VoidPtrTy);
1268 auto *DidItVal =
1269 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1270 llvm::Value *Args[] = {
1271 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1272 getThreadID(CGF, Loc), // i32 <gtid>
1273 BufSize, // i32 <buf_size>
1274 CL, // void *<copyprivate list>
1275 CpyFn, // void (*) (void *, void *) <copy_func>
1276 DidItVal // i32 did_it
1277 };
1278 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1279 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001280}
1281
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001282void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1283 const RegionCodeGenTy &OrderedOpGen,
1284 SourceLocation Loc) {
1285 // __kmpc_ordered(ident_t *, gtid);
1286 // OrderedOpGen();
1287 // __kmpc_end_ordered(ident_t *, gtid);
1288 // Prepare arguments and build a call to __kmpc_ordered
1289 {
1290 CodeGenFunction::RunCleanupsScope Scope(CGF);
1291 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1292 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1293 // Build a call to __kmpc_end_ordered
1294 CGF.EHStack.pushCleanup<CallEndCleanup>(
1295 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1296 llvm::makeArrayRef(Args));
1297 emitInlinedDirective(CGF, OrderedOpGen);
1298 }
1299}
1300
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001301void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001302 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001303 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001304 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1305 if (Kind == OMPD_for) {
1306 Flags =
1307 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1308 } else if (Kind == OMPD_sections) {
1309 Flags = static_cast<OpenMPLocationFlags>(Flags |
1310 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1311 } else if (Kind == OMPD_single) {
1312 Flags =
1313 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1314 } else if (Kind == OMPD_barrier) {
1315 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1316 } else {
1317 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1318 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001319 // Build call __kmpc_cancel_barrier(loc, thread_id);
1320 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1321 // one provides the same functionality and adds initial support for
1322 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1323 // is provided default by the runtime library so it safe to make such
1324 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001325 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1326 getThreadID(CGF, Loc)};
1327 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001328}
1329
Alexander Musmanc6388682014-12-15 07:07:06 +00001330/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1331/// the enum sched_type in kmp.h).
1332enum OpenMPSchedType {
1333 /// \brief Lower bound for default (unordered) versions.
1334 OMP_sch_lower = 32,
1335 OMP_sch_static_chunked = 33,
1336 OMP_sch_static = 34,
1337 OMP_sch_dynamic_chunked = 35,
1338 OMP_sch_guided_chunked = 36,
1339 OMP_sch_runtime = 37,
1340 OMP_sch_auto = 38,
1341 /// \brief Lower bound for 'ordered' versions.
1342 OMP_ord_lower = 64,
1343 /// \brief Lower bound for 'nomerge' versions.
1344 OMP_nm_lower = 160,
1345};
1346
1347/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1348static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
1349 bool Chunked) {
1350 switch (ScheduleKind) {
1351 case OMPC_SCHEDULE_static:
1352 return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
1353 case OMPC_SCHEDULE_dynamic:
1354 return OMP_sch_dynamic_chunked;
1355 case OMPC_SCHEDULE_guided:
1356 return OMP_sch_guided_chunked;
1357 case OMPC_SCHEDULE_auto:
1358 return OMP_sch_auto;
1359 case OMPC_SCHEDULE_runtime:
1360 return OMP_sch_runtime;
1361 case OMPC_SCHEDULE_unknown:
1362 assert(!Chunked && "chunk was specified but schedule kind not known");
1363 return OMP_sch_static;
1364 }
1365 llvm_unreachable("Unexpected runtime schedule");
1366}
1367
1368bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1369 bool Chunked) const {
1370 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
1371 return Schedule == OMP_sch_static;
1372}
1373
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001374bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
1375 auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
1376 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1377 return Schedule != OMP_sch_static;
1378}
1379
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001380void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1381 OpenMPScheduleClauseKind ScheduleKind,
1382 unsigned IVSize, bool IVSigned,
1383 llvm::Value *IL, llvm::Value *LB,
1384 llvm::Value *UB, llvm::Value *ST,
1385 llvm::Value *Chunk) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001386 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001387 if (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked) {
1388 // Call __kmpc_dispatch_init(
1389 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1390 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1391 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001392
Alexander Musman92bdaab2015-03-12 13:37:50 +00001393 // If the Chunk was not specified in the clause - use default value 1.
1394 if (Chunk == nullptr)
1395 Chunk = CGF.Builder.getIntN(IVSize, 1);
1396 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1397 getThreadID(CGF, Loc),
1398 CGF.Builder.getInt32(Schedule), // Schedule type
1399 CGF.Builder.getIntN(IVSize, 0), // Lower
1400 UB, // Upper
1401 CGF.Builder.getIntN(IVSize, 1), // Stride
1402 Chunk // Chunk
1403 };
1404 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1405 } else {
1406 // Call __kmpc_for_static_init(
1407 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1408 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1409 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1410 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1411 if (Chunk == nullptr) {
1412 assert(Schedule == OMP_sch_static &&
1413 "expected static non-chunked schedule");
1414 // If the Chunk was not specified in the clause - use default value 1.
1415 Chunk = CGF.Builder.getIntN(IVSize, 1);
1416 } else
1417 assert(Schedule == OMP_sch_static_chunked &&
1418 "expected static chunked schedule");
1419 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1420 getThreadID(CGF, Loc),
1421 CGF.Builder.getInt32(Schedule), // Schedule type
1422 IL, // &isLastIter
1423 LB, // &LB
1424 UB, // &UB
1425 ST, // &Stride
1426 CGF.Builder.getIntN(IVSize, 1), // Incr
1427 Chunk // Chunk
1428 };
Alexander Musman21212e42015-03-13 10:38:23 +00001429 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001430 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001431}
1432
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001433void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1434 SourceLocation Loc) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001435 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001436 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1437 getThreadID(CGF, Loc)};
1438 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1439 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001440}
1441
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001442void CGOpenMPRuntime::emitForOrderedDynamicIterationEnd(CodeGenFunction &CGF,
1443 SourceLocation Loc,
1444 unsigned IVSize,
1445 bool IVSigned) {
1446 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1447 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1448 getThreadID(CGF, Loc)};
1449 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1450}
1451
Alexander Musman92bdaab2015-03-12 13:37:50 +00001452llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1453 SourceLocation Loc, unsigned IVSize,
1454 bool IVSigned, llvm::Value *IL,
1455 llvm::Value *LB, llvm::Value *UB,
1456 llvm::Value *ST) {
1457 // Call __kmpc_dispatch_next(
1458 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1459 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1460 // kmp_int[32|64] *p_stride);
1461 llvm::Value *Args[] = {
1462 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1463 IL, // &isLastIter
1464 LB, // &Lower
1465 UB, // &Upper
1466 ST // &Stride
1467 };
1468 llvm::Value *Call =
1469 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1470 return CGF.EmitScalarConversion(
1471 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1472 CGF.getContext().BoolTy);
1473}
1474
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001475void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1476 llvm::Value *NumThreads,
1477 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001478 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1479 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001480 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001481 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001482 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1483 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001484}
1485
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001486void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1487 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001488 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001489 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1490 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001491}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001492
Alexey Bataev62b63b12015-03-10 07:28:44 +00001493namespace {
1494/// \brief Indexes of fields for type kmp_task_t.
1495enum KmpTaskTFields {
1496 /// \brief List of shared variables.
1497 KmpTaskTShareds,
1498 /// \brief Task routine.
1499 KmpTaskTRoutine,
1500 /// \brief Partition id for the untied tasks.
1501 KmpTaskTPartId,
1502 /// \brief Function with call of destructors for private variables.
1503 KmpTaskTDestructors,
1504};
1505} // namespace
1506
1507void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1508 if (!KmpRoutineEntryPtrTy) {
1509 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1510 auto &C = CGM.getContext();
1511 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1512 FunctionProtoType::ExtProtoInfo EPI;
1513 KmpRoutineEntryPtrQTy = C.getPointerType(
1514 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1515 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1516 }
1517}
1518
1519static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1520 QualType FieldTy) {
1521 auto *Field = FieldDecl::Create(
1522 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1523 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1524 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1525 Field->setAccess(AS_public);
1526 DC->addDecl(Field);
1527}
1528
1529static QualType createKmpTaskTRecordDecl(CodeGenModule &CGM,
1530 QualType KmpInt32Ty,
1531 QualType KmpRoutineEntryPointerQTy) {
1532 auto &C = CGM.getContext();
1533 // Build struct kmp_task_t {
1534 // void * shareds;
1535 // kmp_routine_entry_t routine;
1536 // kmp_int32 part_id;
1537 // kmp_routine_entry_t destructors;
1538 // /* private vars */
1539 // };
1540 auto *RD = C.buildImplicitRecord("kmp_task_t");
1541 RD->startDefinition();
1542 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1543 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1544 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1545 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1546 // TODO: add private fields.
1547 RD->completeDefinition();
1548 return C.getRecordType(RD);
1549}
1550
1551/// \brief Emit a proxy function which accepts kmp_task_t as the second
1552/// argument.
1553/// \code
1554/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1555/// TaskFunction(gtid, tt->part_id, tt->shareds);
1556/// return 0;
1557/// }
1558/// \endcode
1559static llvm::Value *
1560emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
1561 QualType KmpInt32Ty, QualType KmpTaskTPtrQTy,
David Blaikie2e804282015-04-05 22:47:07 +00001562 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1563 llvm::Type *KmpTaskTTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001564 auto &C = CGM.getContext();
1565 FunctionArgList Args;
1566 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1567 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
1568 /*Id=*/nullptr, KmpTaskTPtrQTy);
1569 Args.push_back(&GtidArg);
1570 Args.push_back(&TaskTypeArg);
1571 FunctionType::ExtInfo Info;
1572 auto &TaskEntryFnInfo =
1573 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1574 /*isVariadic=*/false);
1575 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1576 auto *TaskEntry =
1577 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1578 ".omp_task_entry.", &CGM.getModule());
1579 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1580 CodeGenFunction CGF(CGM);
1581 CGF.disableDebugInfo();
1582 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1583
1584 // TaskFunction(gtid, tt->part_id, tt->shareds);
1585 auto *GtidParam = CGF.EmitLoadOfScalar(
1586 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1587 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1588 auto TaskTypeArgAddr = CGF.EmitLoadOfScalar(
1589 CGF.GetAddrOfLocalVar(&TaskTypeArg), /*Volatile=*/false,
1590 CGM.PointerAlignInBytes, KmpTaskTPtrQTy, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001591 auto *PartidPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001592 /*Idx=*/KmpTaskTPartId);
1593 auto *PartidParam = CGF.EmitLoadOfScalar(
1594 PartidPtr, /*Volatile=*/false,
1595 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001596 auto *SharedsPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001597 /*Idx=*/KmpTaskTShareds);
1598 auto *SharedsParam =
1599 CGF.EmitLoadOfScalar(SharedsPtr, /*Volatile=*/false,
1600 CGM.PointerAlignInBytes, C.VoidPtrTy, Loc);
1601 llvm::Value *CallArgs[] = {
1602 GtidParam, PartidParam,
1603 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1604 SharedsParam, CGF.ConvertTypeForMem(SharedsPtrTy))};
1605 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1606 CGF.EmitStoreThroughLValue(
1607 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1608 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1609 CGF.FinishFunction();
1610 return TaskEntry;
1611}
1612
1613void CGOpenMPRuntime::emitTaskCall(
1614 CodeGenFunction &CGF, SourceLocation Loc, bool Tied,
1615 llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1616 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds) {
1617 auto &C = CGM.getContext();
1618 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1619 // Build type kmp_routine_entry_t (if not built yet).
1620 emitKmpRoutineEntryT(KmpInt32Ty);
1621 // Build particular struct kmp_task_t for the given task.
1622 auto KmpTaskQTy =
1623 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy);
1624 QualType KmpTaskTPtrQTy = C.getPointerType(KmpTaskQTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00001625 auto *KmpTaskTTy = CGF.ConvertType(KmpTaskQTy);
1626 auto *KmpTaskTPtrTy = KmpTaskTTy->getPointerTo();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001627 auto KmpTaskTySize = CGM.getSize(C.getTypeSizeInChars(KmpTaskQTy));
1628 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
1629
1630 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
1631 // kmp_task_t *tt);
David Blaikie1ed728c2015-04-05 22:45:47 +00001632 auto *TaskEntry =
1633 emitProxyTaskFunction(CGM, Loc, KmpInt32Ty, KmpTaskTPtrQTy, SharedsPtrTy,
1634 TaskFunction, KmpTaskTTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001635
1636 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1637 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1638 // kmp_routine_entry_t *task_entry);
1639 // Task flags. Format is taken from
1640 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
1641 // description of kmp_tasking_flags struct.
1642 const unsigned TiedFlag = 0x1;
1643 const unsigned FinalFlag = 0x2;
1644 unsigned Flags = Tied ? TiedFlag : 0;
1645 auto *TaskFlags =
1646 Final.getPointer()
1647 ? CGF.Builder.CreateSelect(Final.getPointer(),
1648 CGF.Builder.getInt32(FinalFlag),
1649 CGF.Builder.getInt32(/*C=*/0))
1650 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
1651 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
1652 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
1653 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
1654 getThreadID(CGF, Loc), TaskFlags, KmpTaskTySize,
1655 CGM.getSize(SharedsSize),
1656 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1657 TaskEntry, KmpRoutineEntryPtrTy)};
1658 auto *NewTask = CGF.EmitRuntimeCall(
1659 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
1660 auto *NewTaskNewTaskTTy =
1661 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NewTask, KmpTaskTPtrTy);
1662 // Fill the data in the resulting kmp_task_t record.
1663 // Copy shareds if there are any.
1664 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty())
1665 CGF.EmitAggregateCopy(
1666 CGF.EmitLoadOfScalar(
David Blaikie1ed728c2015-04-05 22:45:47 +00001667 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001668 /*Idx=*/KmpTaskTShareds),
1669 /*Volatile=*/false, CGM.PointerAlignInBytes, SharedsPtrTy, Loc),
1670 Shareds, SharedsTy);
1671 // TODO: generate function with destructors for privates.
1672 // Provide pointer to function with destructors for privates.
1673 CGF.Builder.CreateAlignedStore(
1674 llvm::ConstantPointerNull::get(
1675 cast<llvm::PointerType>(KmpRoutineEntryPtrTy)),
David Blaikie1ed728c2015-04-05 22:45:47 +00001676 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001677 /*Idx=*/KmpTaskTDestructors),
1678 CGM.PointerAlignInBytes);
1679
1680 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
1681 // libcall.
1682 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1683 // *new_task);
1684 llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc),
1685 getThreadID(CGF, Loc), NewTask};
1686 // TODO: add check for untied tasks.
1687 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1688}
1689
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001690static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
1691 llvm::Type *ArgsType,
1692 ArrayRef<const Expr *> LHSExprs,
1693 ArrayRef<const Expr *> RHSExprs,
1694 ArrayRef<const Expr *> ReductionOps) {
1695 auto &C = CGM.getContext();
1696
1697 // void reduction_func(void *LHSArg, void *RHSArg);
1698 FunctionArgList Args;
1699 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1700 C.VoidPtrTy);
1701 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1702 C.VoidPtrTy);
1703 Args.push_back(&LHSArg);
1704 Args.push_back(&RHSArg);
1705 FunctionType::ExtInfo EI;
1706 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1707 C.VoidTy, Args, EI, /*isVariadic=*/false);
1708 auto *Fn = llvm::Function::Create(
1709 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1710 ".omp.reduction.reduction_func", &CGM.getModule());
1711 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1712 CodeGenFunction CGF(CGM);
1713 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1714
1715 // Dst = (void*[n])(LHSArg);
1716 // Src = (void*[n])(RHSArg);
1717 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1718 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1719 CGF.PointerAlignInBytes),
1720 ArgsType);
1721 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1722 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1723 CGF.PointerAlignInBytes),
1724 ArgsType);
1725
1726 // ...
1727 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
1728 // ...
1729 CodeGenFunction::OMPPrivateScope Scope(CGF);
1730 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
1731 Scope.addPrivate(
1732 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()),
1733 [&]() -> llvm::Value *{
1734 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1735 CGF.Builder.CreateAlignedLoad(
1736 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, RHS, I),
1737 CGM.PointerAlignInBytes),
1738 CGF.ConvertTypeForMem(C.getPointerType(RHSExprs[I]->getType())));
1739 });
1740 Scope.addPrivate(
1741 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()),
1742 [&]() -> llvm::Value *{
1743 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1744 CGF.Builder.CreateAlignedLoad(
1745 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, LHS, I),
1746 CGM.PointerAlignInBytes),
1747 CGF.ConvertTypeForMem(C.getPointerType(LHSExprs[I]->getType())));
1748 });
1749 }
1750 Scope.Privatize();
1751 for (auto *E : ReductionOps) {
1752 CGF.EmitIgnoredExpr(E);
1753 }
1754 Scope.ForceCleanup();
1755 CGF.FinishFunction();
1756 return Fn;
1757}
1758
1759void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
1760 ArrayRef<const Expr *> LHSExprs,
1761 ArrayRef<const Expr *> RHSExprs,
1762 ArrayRef<const Expr *> ReductionOps,
1763 bool WithNowait) {
1764 // Next code should be emitted for reduction:
1765 //
1766 // static kmp_critical_name lock = { 0 };
1767 //
1768 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
1769 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
1770 // ...
1771 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
1772 // *(Type<n>-1*)rhs[<n>-1]);
1773 // }
1774 //
1775 // ...
1776 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
1777 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
1778 // RedList, reduce_func, &<lock>)) {
1779 // case 1:
1780 // ...
1781 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
1782 // ...
1783 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
1784 // break;
1785 // case 2:
1786 // ...
1787 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
1788 // ...
1789 // break;
1790 // default:;
1791 // }
1792
1793 auto &C = CGM.getContext();
1794
1795 // 1. Build a list of reduction variables.
1796 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
1797 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
1798 QualType ReductionArrayTy =
1799 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1800 /*IndexTypeQuals=*/0);
1801 auto *ReductionList =
1802 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
1803 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
1804 auto *Elem = CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, ReductionList, I);
1805 CGF.Builder.CreateAlignedStore(
1806 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1807 CGF.EmitLValue(RHSExprs[I]).getAddress(), CGF.VoidPtrTy),
1808 Elem, CGM.PointerAlignInBytes);
1809 }
1810
1811 // 2. Emit reduce_func().
1812 auto *ReductionFn = emitReductionFunction(
1813 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
1814 RHSExprs, ReductionOps);
1815
1816 // 3. Create static kmp_critical_name lock = { 0 };
1817 auto *Lock = getCriticalRegionLock(".reduction");
1818
1819 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
1820 // RedList, reduce_func, &<lock>);
1821 auto *IdentTLoc = emitUpdateLocation(
1822 CGF, Loc,
1823 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
1824 auto *ThreadId = getThreadID(CGF, Loc);
1825 auto *ReductionArrayTySize = llvm::ConstantInt::get(
1826 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
1827 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList,
1828 CGF.VoidPtrTy);
1829 llvm::Value *Args[] = {
1830 IdentTLoc, // ident_t *<loc>
1831 ThreadId, // i32 <gtid>
1832 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
1833 ReductionArrayTySize, // size_type sizeof(RedList)
1834 RL, // void *RedList
1835 ReductionFn, // void (*) (void *, void *) <reduce_func>
1836 Lock // kmp_critical_name *&<lock>
1837 };
1838 auto Res = CGF.EmitRuntimeCall(
1839 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
1840 : OMPRTL__kmpc_reduce),
1841 Args);
1842
1843 // 5. Build switch(res)
1844 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
1845 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
1846
1847 // 6. Build case 1:
1848 // ...
1849 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
1850 // ...
1851 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
1852 // break;
1853 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
1854 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
1855 CGF.EmitBlock(Case1BB);
1856
1857 {
1858 CodeGenFunction::RunCleanupsScope Scope(CGF);
1859 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
1860 llvm::Value *EndArgs[] = {
1861 IdentTLoc, // ident_t *<loc>
1862 ThreadId, // i32 <gtid>
1863 Lock // kmp_critical_name *&<lock>
1864 };
1865 CGF.EHStack.pushCleanup<CallEndCleanup>(
1866 NormalAndEHCleanup,
1867 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
1868 : OMPRTL__kmpc_end_reduce),
1869 llvm::makeArrayRef(EndArgs));
1870 for (auto *E : ReductionOps) {
1871 CGF.EmitIgnoredExpr(E);
1872 }
1873 }
1874
1875 CGF.EmitBranch(DefaultBB);
1876
1877 // 7. Build case 2:
1878 // ...
1879 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
1880 // ...
1881 // break;
1882 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
1883 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
1884 CGF.EmitBlock(Case2BB);
1885
1886 {
1887 CodeGenFunction::RunCleanupsScope Scope(CGF);
1888 auto I = LHSExprs.begin();
1889 for (auto *E : ReductionOps) {
1890 const Expr *XExpr = nullptr;
1891 const Expr *EExpr = nullptr;
1892 const Expr *UpExpr = nullptr;
1893 BinaryOperatorKind BO = BO_Comma;
1894 // Try to emit update expression as a simple atomic.
1895 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) {
1896 // If this is a conditional operator, analyze it's condition for
1897 // min/max reduction operator.
1898 E = ACO->getCond();
1899 }
1900 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
1901 if (BO->getOpcode() == BO_Assign) {
1902 XExpr = BO->getLHS();
1903 UpExpr = BO->getRHS();
1904 }
1905 }
1906 // Analyze RHS part of the whole expression.
1907 if (UpExpr) {
1908 if (auto *BORHS =
1909 dyn_cast<BinaryOperator>(UpExpr->IgnoreParenImpCasts())) {
1910 EExpr = BORHS->getRHS();
1911 BO = BORHS->getOpcode();
1912 }
1913 }
1914 if (XExpr) {
1915 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
1916 LValue X = CGF.EmitLValue(XExpr);
1917 RValue E;
1918 if (EExpr)
1919 E = CGF.EmitAnyExpr(EExpr);
1920 CGF.EmitOMPAtomicSimpleUpdateExpr(
1921 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
1922 [&CGF, UpExpr, VD](RValue XRValue) {
1923 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
1924 PrivateScope.addPrivate(
1925 VD, [&CGF, VD, XRValue]() -> llvm::Value *{
1926 auto *LHSTemp = CGF.CreateMemTemp(VD->getType());
1927 CGF.EmitStoreThroughLValue(
1928 XRValue,
1929 CGF.MakeNaturalAlignAddrLValue(LHSTemp, VD->getType()));
1930 return LHSTemp;
1931 });
1932 (void)PrivateScope.Privatize();
1933 return CGF.EmitAnyExpr(UpExpr);
1934 });
1935 } else {
1936 // Emit as a critical region.
1937 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
1938 CGF.EmitIgnoredExpr(E);
1939 }, Loc);
1940 }
1941 ++I;
1942 }
1943 }
1944
1945 CGF.EmitBranch(DefaultBB);
1946 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
1947}
1948
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001949void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
1950 const RegionCodeGenTy &CodeGen) {
1951 InlinedOpenMPRegionRAII Region(CGF, CodeGen);
1952 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001953}
1954