blob: 2b9fbd666132962db63d7d36a454f796ca91bc3c [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.
90 virtual const VarDecl *getThreadIDVariable() const override {
91 return ThreadIDVar;
92 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000093
Alexey Bataev18095712014-10-10 12:19:54 +000094 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +000095 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +000096
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000097 static bool classof(const CGCapturedStmtInfo *Info) {
98 return CGOpenMPRegionInfo::classof(Info) &&
99 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
100 ParallelOutlinedRegion;
101 }
102
Alexey Bataev18095712014-10-10 12:19:54 +0000103private:
104 /// \brief A variable or parameter storing global thread id for OpenMP
105 /// constructs.
106 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000107};
108
Alexey Bataev62b63b12015-03-10 07:28:44 +0000109/// \brief API for captured statement code generation in OpenMP constructs.
110class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
111public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000112 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000113 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114 const RegionCodeGenTy &CodeGen)
115 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen),
116 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000117 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
118 }
119 /// \brief Get a variable or parameter for storing global thread id
120 /// inside OpenMP construct.
121 virtual const VarDecl *getThreadIDVariable() const override {
122 return ThreadIDVar;
123 }
124
125 /// \brief Get an LValue for the current ThreadID variable.
126 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
127
Alexey Bataev62b63b12015-03-10 07:28:44 +0000128 /// \brief Get the name of the capture helper.
129 StringRef getHelperName() const override { return ".omp_outlined."; }
130
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000131 static bool classof(const CGCapturedStmtInfo *Info) {
132 return CGOpenMPRegionInfo::classof(Info) &&
133 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
134 TaskOutlinedRegion;
135 }
136
Alexey Bataev62b63b12015-03-10 07:28:44 +0000137private:
138 /// \brief A variable or parameter storing global thread id for OpenMP
139 /// constructs.
140 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000141};
142
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000143/// \brief API for inlined captured statement code generation in OpenMP
144/// constructs.
145class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
146public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000147 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
148 const RegionCodeGenTy &CodeGen)
149 : CGOpenMPRegionInfo(InlinedRegion, CodeGen), OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000150 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
151 // \brief Retrieve the value of the context parameter.
152 virtual llvm::Value *getContextValue() const override {
153 if (OuterRegionInfo)
154 return OuterRegionInfo->getContextValue();
155 llvm_unreachable("No context value for inlined OpenMP region");
156 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000157 virtual void setContextValue(llvm::Value *V) override {
158 if (OuterRegionInfo) {
159 OuterRegionInfo->setContextValue(V);
160 return;
161 }
162 llvm_unreachable("No context value for inlined OpenMP region");
163 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000164 /// \brief Lookup the captured field decl for a variable.
165 virtual const FieldDecl *lookup(const VarDecl *VD) const override {
166 if (OuterRegionInfo)
167 return OuterRegionInfo->lookup(VD);
168 llvm_unreachable("Trying to reference VarDecl that is neither local nor "
169 "captured in outer OpenMP region");
170 }
171 virtual FieldDecl *getThisFieldDecl() const override {
172 if (OuterRegionInfo)
173 return OuterRegionInfo->getThisFieldDecl();
174 return nullptr;
175 }
176 /// \brief Get a variable or parameter for storing global thread id
177 /// inside OpenMP construct.
178 virtual const VarDecl *getThreadIDVariable() const override {
179 if (OuterRegionInfo)
180 return OuterRegionInfo->getThreadIDVariable();
181 return nullptr;
182 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000183
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000184 /// \brief Get the name of the capture helper.
185 virtual StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000186 if (auto *OuterRegionInfo = getOldCSI())
187 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000188 llvm_unreachable("No helper name for inlined OpenMP construct");
189 }
190
191 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
192
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000193 static bool classof(const CGCapturedStmtInfo *Info) {
194 return CGOpenMPRegionInfo::classof(Info) &&
195 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
196 }
197
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000198private:
199 /// \brief CodeGen info about outer OpenMP region.
200 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
201 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000202};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000203
204/// \brief RAII for emitting code of OpenMP constructs.
205class InlinedOpenMPRegionRAII {
206 CodeGenFunction &CGF;
207
208public:
209 /// \brief Constructs region for combined constructs.
210 /// \param CodeGen Code generation sequence for combined directives. Includes
211 /// a list of functions used for code generation of implicitly inlined
212 /// regions.
213 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen)
214 : CGF(CGF) {
215 // Start emission for the construct.
216 CGF.CapturedStmtInfo =
217 new CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, CodeGen);
218 }
219 ~InlinedOpenMPRegionRAII() {
220 // Restore original CapturedStmtInfo only if we're done with code emission.
221 auto *OldCSI =
222 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
223 delete CGF.CapturedStmtInfo;
224 CGF.CapturedStmtInfo = OldCSI;
225 }
226};
227
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000228} // namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000229
230LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
231 return CGF.MakeNaturalAlignAddrLValue(
Alexey Bataev62b63b12015-03-10 07:28:44 +0000232 CGF.Builder.CreateAlignedLoad(
233 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
234 CGF.PointerAlignInBytes),
235 getThreadIDVariable()
236 ->getType()
237 ->castAs<PointerType>()
238 ->getPointeeType());
Alexey Bataev18095712014-10-10 12:19:54 +0000239}
240
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000241void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
242 // 1.2.2 OpenMP Language Terminology
243 // Structured block - An executable statement with a single entry at the
244 // top and a single exit at the bottom.
245 // The point of exit cannot be a branch out of the structured block.
246 // longjmp() and throw() must not violate the entry/exit criteria.
247 CGF.EHStack.pushTerminate();
248 {
249 CodeGenFunction::RunCleanupsScope Scope(CGF);
250 CodeGen(CGF);
251 }
252 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000253}
254
Alexey Bataev62b63b12015-03-10 07:28:44 +0000255LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
256 CodeGenFunction &CGF) {
257 return CGF.MakeNaturalAlignAddrLValue(
258 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
259 getThreadIDVariable()->getType());
260}
261
Alexey Bataev9959db52014-05-06 10:08:46 +0000262CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000263 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000264 IdentTy = llvm::StructType::create(
265 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
266 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000267 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000268 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000269 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
270 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000271 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000272 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000273}
274
Alexey Bataev91797552015-03-18 04:13:55 +0000275void CGOpenMPRuntime::clear() {
276 InternalVars.clear();
277}
278
Alexey Bataev9959db52014-05-06 10:08:46 +0000279llvm::Value *
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000280CGOpenMPRuntime::emitParallelOutlinedFunction(const OMPExecutableDirective &D,
281 const VarDecl *ThreadIDVar,
282 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000283 assert(ThreadIDVar->getType()->isPointerType() &&
284 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000285 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
286 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000287 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataev18095712014-10-10 12:19:54 +0000288 CGF.CapturedStmtInfo = &CGInfo;
289 return CGF.GenerateCapturedStmtFunction(*CS);
290}
291
292llvm::Value *
Alexey Bataev62b63b12015-03-10 07:28:44 +0000293CGOpenMPRuntime::emitTaskOutlinedFunction(const OMPExecutableDirective &D,
294 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000295 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000296 assert(!ThreadIDVar->getType()->isPointerType() &&
297 "thread id variable must be of type kmp_int32 for tasks");
298 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
299 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000300 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000301 CGF.CapturedStmtInfo = &CGInfo;
302 return CGF.GenerateCapturedStmtFunction(*CS);
303}
304
305llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000306CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000307 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000308 if (!Entry) {
309 if (!DefaultOpenMPPSource) {
310 // Initialize default location for psource field of ident_t structure of
311 // all ident_t objects. Format is ";file;function;line;column;;".
312 // Taken from
313 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
314 DefaultOpenMPPSource =
315 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
316 DefaultOpenMPPSource =
317 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
318 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000319 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
320 CGM.getModule(), IdentTy, /*isConstant*/ true,
321 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000322 DefaultOpenMPLocation->setUnnamedAddr(true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000323
324 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000325 llvm::Constant *Values[] = {Zero,
326 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
327 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000328 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
329 DefaultOpenMPLocation->setInitializer(Init);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000330 OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000331 return DefaultOpenMPLocation;
332 }
333 return Entry;
334}
335
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000336llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
337 SourceLocation Loc,
338 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000339 // If no debug info is generated - return global default location.
340 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
341 Loc.isInvalid())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000342 return getOrCreateDefaultLocation(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000343
344 assert(CGF.CurFn && "No function in current CodeGenFunction.");
345
Alexey Bataev9959db52014-05-06 10:08:46 +0000346 llvm::Value *LocValue = nullptr;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000347 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
348 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataev18095712014-10-10 12:19:54 +0000349 LocValue = I->second.DebugLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +0000350 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
351 // GetOpenMPThreadID was called before this routine.
352 if (LocValue == nullptr) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000353 // Generate "ident_t .kmpc_loc.addr;"
354 llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
Alexey Bataev9959db52014-05-06 10:08:46 +0000355 AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
Alexey Bataev18095712014-10-10 12:19:54 +0000356 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
357 Elem.second.DebugLoc = AI;
Alexey Bataev9959db52014-05-06 10:08:46 +0000358 LocValue = AI;
359
360 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
361 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000362 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataev9959db52014-05-06 10:08:46 +0000363 llvm::ConstantExpr::getSizeOf(IdentTy),
364 CGM.PointerAlignInBytes);
365 }
366
367 // char **psource = &.kmpc_loc_<flags>.addr.psource;
David Blaikie1ed728c2015-04-05 22:45:47 +0000368 auto *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(IdentTy, LocValue, 0,
369 IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000370
Alexey Bataevf002aca2014-05-30 05:48:40 +0000371 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
372 if (OMPDebugLoc == nullptr) {
373 SmallString<128> Buffer2;
374 llvm::raw_svector_ostream OS2(Buffer2);
375 // Build debug location
376 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
377 OS2 << ";" << PLoc.getFilename() << ";";
378 if (const FunctionDecl *FD =
379 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
380 OS2 << FD->getQualifiedNameAsString();
381 }
382 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
383 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
384 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000385 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000386 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000387 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
388
Alexey Bataev9959db52014-05-06 10:08:46 +0000389 return LocValue;
390}
391
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000392llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
393 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000394 assert(CGF.CurFn && "No function in current CodeGenFunction.");
395
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000396 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000397 // Check whether we've already cached a load of the thread id in this
398 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000399 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000400 if (I != OpenMPLocThreadIDMap.end()) {
401 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000402 if (ThreadID != nullptr)
403 return ThreadID;
404 }
405 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000406 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000407 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000408 // Check if this an outlined function with thread id passed as argument.
409 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000410 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
411 // If value loaded in entry block, cache it and use it everywhere in
412 // function.
413 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
414 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
415 Elem.second.ThreadID = ThreadID;
416 }
417 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000418 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000419 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000420
421 // This is not an outlined function region - need to call __kmpc_int32
422 // kmpc_global_thread_num(ident_t *loc).
423 // Generate thread id value and cache this value for use across the
424 // function.
425 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
426 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
427 ThreadID =
428 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
429 emitUpdateLocation(CGF, Loc));
430 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
431 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000432 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000433}
434
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000435void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000436 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000437 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
438 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000439}
440
441llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
442 return llvm::PointerType::getUnqual(IdentTy);
443}
444
445llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
446 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
447}
448
449llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000450CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000451 llvm::Constant *RTLFn = nullptr;
452 switch (Function) {
453 case OMPRTL__kmpc_fork_call: {
454 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
455 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000456 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
457 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000458 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000459 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000460 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
461 break;
462 }
463 case OMPRTL__kmpc_global_thread_num: {
464 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000465 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000466 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000467 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000468 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
469 break;
470 }
Alexey Bataev97720002014-11-11 04:05:39 +0000471 case OMPRTL__kmpc_threadprivate_cached: {
472 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
473 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
474 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
475 CGM.VoidPtrTy, CGM.SizeTy,
476 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
477 llvm::FunctionType *FnTy =
478 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
479 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
480 break;
481 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000482 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000483 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
484 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000485 llvm::Type *TypeParams[] = {
486 getIdentTyPointerTy(), CGM.Int32Ty,
487 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
488 llvm::FunctionType *FnTy =
489 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
490 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
491 break;
492 }
Alexey Bataev97720002014-11-11 04:05:39 +0000493 case OMPRTL__kmpc_threadprivate_register: {
494 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
495 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
496 // typedef void *(*kmpc_ctor)(void *);
497 auto KmpcCtorTy =
498 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
499 /*isVarArg*/ false)->getPointerTo();
500 // typedef void *(*kmpc_cctor)(void *, void *);
501 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
502 auto KmpcCopyCtorTy =
503 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
504 /*isVarArg*/ false)->getPointerTo();
505 // typedef void (*kmpc_dtor)(void *);
506 auto KmpcDtorTy =
507 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
508 ->getPointerTo();
509 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
510 KmpcCopyCtorTy, KmpcDtorTy};
511 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
512 /*isVarArg*/ false);
513 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
514 break;
515 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000516 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000517 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
518 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000519 llvm::Type *TypeParams[] = {
520 getIdentTyPointerTy(), CGM.Int32Ty,
521 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
522 llvm::FunctionType *FnTy =
523 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
524 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
525 break;
526 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000527 case OMPRTL__kmpc_cancel_barrier: {
528 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
529 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000530 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
531 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000532 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
533 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000534 break;
535 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000536 case OMPRTL__kmpc_for_static_fini: {
537 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
538 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
539 llvm::FunctionType *FnTy =
540 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
541 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
542 break;
543 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000544 case OMPRTL__kmpc_push_num_threads: {
545 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
546 // kmp_int32 num_threads)
547 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
548 CGM.Int32Ty};
549 llvm::FunctionType *FnTy =
550 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
552 break;
553 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000554 case OMPRTL__kmpc_serialized_parallel: {
555 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
556 // global_tid);
557 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
558 llvm::FunctionType *FnTy =
559 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
560 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
561 break;
562 }
563 case OMPRTL__kmpc_end_serialized_parallel: {
564 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
565 // global_tid);
566 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
567 llvm::FunctionType *FnTy =
568 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
569 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
570 break;
571 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000572 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000573 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000574 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
575 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000576 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000577 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
578 break;
579 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000580 case OMPRTL__kmpc_master: {
581 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
582 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
583 llvm::FunctionType *FnTy =
584 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
585 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
586 break;
587 }
588 case OMPRTL__kmpc_end_master: {
589 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
590 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
591 llvm::FunctionType *FnTy =
592 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
593 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
594 break;
595 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000596 case OMPRTL__kmpc_omp_taskyield: {
597 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
598 // int end_part);
599 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
600 llvm::FunctionType *FnTy =
601 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
602 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
603 break;
604 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000605 case OMPRTL__kmpc_single: {
606 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
607 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
608 llvm::FunctionType *FnTy =
609 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
610 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
611 break;
612 }
613 case OMPRTL__kmpc_end_single: {
614 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
615 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
616 llvm::FunctionType *FnTy =
617 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
618 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
619 break;
620 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000621 case OMPRTL__kmpc_omp_task_alloc: {
622 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
623 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
624 // kmp_routine_entry_t *task_entry);
625 assert(KmpRoutineEntryPtrTy != nullptr &&
626 "Type kmp_routine_entry_t must be created.");
627 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
628 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
629 // Return void * and then cast to particular kmp_task_t type.
630 llvm::FunctionType *FnTy =
631 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
632 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
633 break;
634 }
635 case OMPRTL__kmpc_omp_task: {
636 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
637 // *new_task);
638 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
639 CGM.VoidPtrTy};
640 llvm::FunctionType *FnTy =
641 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
642 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
643 break;
644 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000645 case OMPRTL__kmpc_copyprivate: {
646 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
647 // kmp_int32 cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
648 // kmp_int32 didit);
649 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
650 auto *CpyFnTy =
651 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
652 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
653 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
654 CGM.Int32Ty};
655 llvm::FunctionType *FnTy =
656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
657 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
658 break;
659 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000660 }
661 return RTLFn;
662}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000663
Alexander Musman21212e42015-03-13 10:38:23 +0000664llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
665 bool IVSigned) {
666 assert((IVSize == 32 || IVSize == 64) &&
667 "IV size is not compatible with the omp runtime");
668 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
669 : "__kmpc_for_static_init_4u")
670 : (IVSigned ? "__kmpc_for_static_init_8"
671 : "__kmpc_for_static_init_8u");
672 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
673 auto PtrTy = llvm::PointerType::getUnqual(ITy);
674 llvm::Type *TypeParams[] = {
675 getIdentTyPointerTy(), // loc
676 CGM.Int32Ty, // tid
677 CGM.Int32Ty, // schedtype
678 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
679 PtrTy, // p_lower
680 PtrTy, // p_upper
681 PtrTy, // p_stride
682 ITy, // incr
683 ITy // chunk
684 };
685 llvm::FunctionType *FnTy =
686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
687 return CGM.CreateRuntimeFunction(FnTy, Name);
688}
689
Alexander Musman92bdaab2015-03-12 13:37:50 +0000690llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
691 bool IVSigned) {
692 assert((IVSize == 32 || IVSize == 64) &&
693 "IV size is not compatible with the omp runtime");
694 auto Name =
695 IVSize == 32
696 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
697 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
698 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
699 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
700 CGM.Int32Ty, // tid
701 CGM.Int32Ty, // schedtype
702 ITy, // lower
703 ITy, // upper
704 ITy, // stride
705 ITy // chunk
706 };
707 llvm::FunctionType *FnTy =
708 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
709 return CGM.CreateRuntimeFunction(FnTy, Name);
710}
711
712llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
713 bool IVSigned) {
714 assert((IVSize == 32 || IVSize == 64) &&
715 "IV size is not compatible with the omp runtime");
716 auto Name =
717 IVSize == 32
718 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
719 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
720 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
721 auto PtrTy = llvm::PointerType::getUnqual(ITy);
722 llvm::Type *TypeParams[] = {
723 getIdentTyPointerTy(), // loc
724 CGM.Int32Ty, // tid
725 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
726 PtrTy, // p_lower
727 PtrTy, // p_upper
728 PtrTy // p_stride
729 };
730 llvm::FunctionType *FnTy =
731 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
732 return CGM.CreateRuntimeFunction(FnTy, Name);
733}
734
Alexey Bataev97720002014-11-11 04:05:39 +0000735llvm::Constant *
736CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
737 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000738 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000739 Twine(CGM.getMangledName(VD)) + ".cache.");
740}
741
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000742llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
743 const VarDecl *VD,
744 llvm::Value *VDAddr,
745 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000746 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000747 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000748 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
749 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
750 getOrCreateThreadPrivateCache(VD)};
751 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000752 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000753}
754
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000755void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000756 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
757 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
758 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
759 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000760 auto OMPLoc = emitUpdateLocation(CGF, Loc);
761 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000762 OMPLoc);
763 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
764 // to register constructor/destructor for variable.
765 llvm::Value *Args[] = {OMPLoc,
766 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
767 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000768 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000769 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000770}
771
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000772llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000773 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
774 bool PerformInit, CodeGenFunction *CGF) {
775 VD = VD->getDefinition(CGM.getContext());
776 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
777 ThreadPrivateWithDefinition.insert(VD);
778 QualType ASTTy = VD->getType();
779
780 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
781 auto Init = VD->getAnyInitializer();
782 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
783 // Generate function that re-emits the declaration's initializer into the
784 // threadprivate copy of the variable VD
785 CodeGenFunction CtorCGF(CGM);
786 FunctionArgList Args;
787 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
788 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
789 Args.push_back(&Dst);
790
791 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
792 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
793 /*isVariadic=*/false);
794 auto FTy = CGM.getTypes().GetFunctionType(FI);
795 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
796 FTy, ".__kmpc_global_ctor_.", Loc);
797 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
798 Args, SourceLocation());
799 auto ArgVal = CtorCGF.EmitLoadOfScalar(
800 CtorCGF.GetAddrOfLocalVar(&Dst),
801 /*Volatile=*/false, CGM.PointerAlignInBytes,
802 CGM.getContext().VoidPtrTy, Dst.getLocation());
803 auto Arg = CtorCGF.Builder.CreatePointerCast(
804 ArgVal,
805 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
806 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
807 /*IsInitializer=*/true);
808 ArgVal = CtorCGF.EmitLoadOfScalar(
809 CtorCGF.GetAddrOfLocalVar(&Dst),
810 /*Volatile=*/false, CGM.PointerAlignInBytes,
811 CGM.getContext().VoidPtrTy, Dst.getLocation());
812 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
813 CtorCGF.FinishFunction();
814 Ctor = Fn;
815 }
816 if (VD->getType().isDestructedType() != QualType::DK_none) {
817 // Generate function that emits destructor call for the threadprivate copy
818 // of the variable VD
819 CodeGenFunction DtorCGF(CGM);
820 FunctionArgList Args;
821 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
822 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
823 Args.push_back(&Dst);
824
825 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
826 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
827 /*isVariadic=*/false);
828 auto FTy = CGM.getTypes().GetFunctionType(FI);
829 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
830 FTy, ".__kmpc_global_dtor_.", Loc);
831 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
832 SourceLocation());
833 auto ArgVal = DtorCGF.EmitLoadOfScalar(
834 DtorCGF.GetAddrOfLocalVar(&Dst),
835 /*Volatile=*/false, CGM.PointerAlignInBytes,
836 CGM.getContext().VoidPtrTy, Dst.getLocation());
837 DtorCGF.emitDestroy(ArgVal, ASTTy,
838 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
839 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
840 DtorCGF.FinishFunction();
841 Dtor = Fn;
842 }
843 // Do not emit init function if it is not required.
844 if (!Ctor && !Dtor)
845 return nullptr;
846
847 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
848 auto CopyCtorTy =
849 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
850 /*isVarArg=*/false)->getPointerTo();
851 // Copying constructor for the threadprivate variable.
852 // Must be NULL - reserved by runtime, but currently it requires that this
853 // parameter is always NULL. Otherwise it fires assertion.
854 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
855 if (Ctor == nullptr) {
856 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
857 /*isVarArg=*/false)->getPointerTo();
858 Ctor = llvm::Constant::getNullValue(CtorTy);
859 }
860 if (Dtor == nullptr) {
861 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
862 /*isVarArg=*/false)->getPointerTo();
863 Dtor = llvm::Constant::getNullValue(DtorTy);
864 }
865 if (!CGF) {
866 auto InitFunctionTy =
867 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
868 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
869 InitFunctionTy, ".__omp_threadprivate_init_.");
870 CodeGenFunction InitCGF(CGM);
871 FunctionArgList ArgList;
872 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
873 CGM.getTypes().arrangeNullaryFunction(), ArgList,
874 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000875 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000876 InitCGF.FinishFunction();
877 return InitFunction;
878 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000879 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000880 }
881 return nullptr;
882}
883
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000884void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
885 llvm::Value *OutlinedFn,
886 llvm::Value *CapturedStruct) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000887 // Build call __kmpc_fork_call(loc, 1, microtask, captured_struct/*context*/)
888 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000889 emitUpdateLocation(CGF, Loc),
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000890 CGF.Builder.getInt32(1), // Number of arguments after 'microtask' argument
891 // (there is only one additional argument - 'context')
892 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
893 CGF.EmitCastToVoidPtr(CapturedStruct)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000894 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000895 CGF.EmitRuntimeCall(RTLFn, Args);
896}
897
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000898void CGOpenMPRuntime::emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
899 llvm::Value *OutlinedFn,
900 llvm::Value *CapturedStruct) {
901 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000902 // Build calls:
903 // __kmpc_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000904 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), ThreadID};
905 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
906 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000907
908 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000909 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000910 auto Int32Ty =
911 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
912 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
913 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
914 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
915 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
916
917 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000918 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
919 CGF.EmitRuntimeCall(
920 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000921}
922
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +0000923// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +0000924// thread-ID variable (it is passed in a first argument of the outlined function
925// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
926// regular serial code region, get thread ID by calling kmp_int32
927// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
928// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000929llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +0000930 SourceLocation Loc) {
931 if (auto OMPRegionInfo =
932 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000933 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +0000934 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000935
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000936 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000937 auto Int32Ty =
938 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
939 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
940 CGF.EmitStoreOfScalar(ThreadID,
941 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
942
943 return ThreadIDTemp;
944}
945
Alexey Bataev97720002014-11-11 04:05:39 +0000946llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000947CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +0000948 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000949 SmallString<256> Buffer;
950 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +0000951 Out << Name;
952 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +0000953 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
954 if (Elem.second) {
955 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +0000956 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +0000957 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +0000958 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000959
David Blaikie13156b62014-11-19 03:06:06 +0000960 return Elem.second = new llvm::GlobalVariable(
961 CGM.getModule(), Ty, /*IsConstant*/ false,
962 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
963 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +0000964}
965
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000966llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +0000967 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000968 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000969}
970
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000971namespace {
972class CallEndCleanup : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +0000973public:
974 typedef ArrayRef<llvm::Value *> CleanupValuesTy;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000975private:
Alexey Bataev3e6124b2015-04-10 07:48:12 +0000976 llvm::Value *Callee;
977 llvm::SmallVector<llvm::Value *, 8> Args;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000978
979public:
Alexey Bataev3e6124b2015-04-10 07:48:12 +0000980 CallEndCleanup(llvm::Value *Callee, CleanupValuesTy Args)
981 : Callee(Callee), Args(Args.begin(), Args.end()) {}
982 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
983 CGF.EmitRuntimeCall(Callee, Args);
984 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000985};
986} // namespace
987
988void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
989 StringRef CriticalName,
990 const RegionCodeGenTy &CriticalOpGen,
991 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +0000992 // __kmpc_critical(ident_t *, gtid, Lock);
993 // CriticalOpGen();
994 // __kmpc_end_critical(ident_t *, gtid, Lock);
995 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000996 {
997 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +0000998 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
999 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001000 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
1001 emitInlinedDirective(CGF, CriticalOpGen);
1002 // Build a call to __kmpc_end_critical
1003 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001004 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1005 llvm::makeArrayRef(Args));
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001006 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001007}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001008
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001009static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001010 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001011 llvm::Value *CallBool = CGF.EmitScalarConversion(
1012 IfCond,
1013 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1014 CGF.getContext().BoolTy);
1015
1016 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1017 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1018 // Generate the branch (If-stmt)
1019 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1020 CGF.EmitBlock(ThenBlock);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001021 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001022 // Emit the rest of bblocks/branches
1023 CGF.EmitBranch(ContBlock);
1024 CGF.EmitBlock(ContBlock, true);
1025}
1026
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001027void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001028 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001029 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001030 // if(__kmpc_master(ident_t *, gtid)) {
1031 // MasterOpGen();
1032 // __kmpc_end_master(ident_t *, gtid);
1033 // }
1034 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001035 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001036 auto *IsMaster =
1037 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001038 emitIfStmt(CGF, IsMaster, [&](CodeGenFunction &CGF) -> void {
1039 CodeGenFunction::RunCleanupsScope Scope(CGF);
1040 MasterOpGen(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001041 // Build a call to __kmpc_end_master.
1042 // OpenMP [1.2.2 OpenMP Language Terminology]
1043 // For C/C++, an executable statement, possibly compound, with a single
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001044 // entry at the top and a single exit at the bottom, or an OpenMP
1045 // construct.
Alexey Bataev8d690652014-12-04 07:23:53 +00001046 // * Access to the structured block must not be the result of a branch.
1047 // * The point of exit cannot be a branch out of the structured block.
1048 // * The point of entry must not be a call to setjmp().
1049 // * longjmp() and throw() must not violate the entry/exit criteria.
1050 // * An expression statement, iteration statement, selection statement, or
1051 // try block is considered to be a structured block if the corresponding
1052 // compound statement obtained by enclosing it in { and } would be a
1053 // structured block.
1054 // It is analyzed in Sema, so we can just call __kmpc_end_master() on
1055 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001056 // Build a call to __kmpc_end_critical
1057 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001058 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1059 llvm::makeArrayRef(Args));
Alexey Bataev8d690652014-12-04 07:23:53 +00001060 });
1061}
1062
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001063void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1064 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001065 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1066 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001067 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001068 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001069 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001070}
1071
Alexey Bataeva63048e2015-03-23 06:18:07 +00001072static llvm::Value *emitCopyprivateCopyFunction(
1073 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> SrcExprs,
1074 ArrayRef<const Expr *> DstExprs, ArrayRef<const Expr *> AssignmentOps) {
1075 auto &C = CGM.getContext();
1076 // void copy_func(void *LHSArg, void *RHSArg);
1077 FunctionArgList Args;
1078 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1079 C.VoidPtrTy);
1080 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1081 C.VoidPtrTy);
1082 Args.push_back(&LHSArg);
1083 Args.push_back(&RHSArg);
1084 FunctionType::ExtInfo EI;
1085 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1086 C.VoidTy, Args, EI, /*isVariadic=*/false);
1087 auto *Fn = llvm::Function::Create(
1088 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1089 ".omp.copyprivate.copy_func", &CGM.getModule());
1090 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1091 CodeGenFunction CGF(CGM);
1092 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1093 // Dst = (void*[n])(LHSArg);
1094 // Src = (void*[n])(RHSArg);
1095 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1096 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1097 CGF.PointerAlignInBytes),
1098 ArgsType);
1099 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1100 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1101 CGF.PointerAlignInBytes),
1102 ArgsType);
1103 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1104 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1105 // ...
1106 // *(Typen*)Dst[n] = *(Typen*)Src[n];
1107 CodeGenFunction::OMPPrivateScope Scope(CGF);
1108 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
1109 Scope.addPrivate(
1110 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1111 [&]() -> llvm::Value *{
1112 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001113 CGF.Builder.CreateAlignedLoad(
1114 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1115 CGM.PointerAlignInBytes),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001116 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1117 });
1118 Scope.addPrivate(
1119 cast<VarDecl>(cast<DeclRefExpr>(DstExprs[I])->getDecl()),
1120 [&]() -> llvm::Value *{
1121 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001122 CGF.Builder.CreateAlignedLoad(
1123 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1124 CGM.PointerAlignInBytes),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001125 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1126 });
1127 }
1128 Scope.Privatize();
1129 for (auto *E : AssignmentOps) {
1130 CGF.EmitIgnoredExpr(E);
1131 }
1132 Scope.ForceCleanup();
1133 CGF.FinishFunction();
1134 return Fn;
1135}
1136
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001137void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001138 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001139 SourceLocation Loc,
1140 ArrayRef<const Expr *> CopyprivateVars,
1141 ArrayRef<const Expr *> SrcExprs,
1142 ArrayRef<const Expr *> DstExprs,
1143 ArrayRef<const Expr *> AssignmentOps) {
1144 assert(CopyprivateVars.size() == SrcExprs.size() &&
1145 CopyprivateVars.size() == DstExprs.size() &&
1146 CopyprivateVars.size() == AssignmentOps.size());
1147 auto &C = CGM.getContext();
1148 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001149 // if(__kmpc_single(ident_t *, gtid)) {
1150 // SingleOpGen();
1151 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001152 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001153 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001154 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1155 // <copy_func>, did_it);
1156
1157 llvm::AllocaInst *DidIt = nullptr;
1158 if (!CopyprivateVars.empty()) {
1159 // int32 did_it = 0;
1160 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1161 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
1162 CGF.InitTempAlloca(DidIt, CGF.Builder.getInt32(0));
1163 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001164 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001165 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001166 auto *IsSingle =
1167 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001168 emitIfStmt(CGF, IsSingle, [&](CodeGenFunction &CGF) -> void {
1169 CodeGenFunction::RunCleanupsScope Scope(CGF);
1170 SingleOpGen(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001171 if (DidIt) {
1172 // did_it = 1;
1173 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1174 DidIt->getAlignment());
1175 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001176 // Build a call to __kmpc_end_single.
1177 // OpenMP [1.2.2 OpenMP Language Terminology]
1178 // For C/C++, an executable statement, possibly compound, with a single
1179 // entry at the top and a single exit at the bottom, or an OpenMP construct.
1180 // * Access to the structured block must not be the result of a branch.
1181 // * The point of exit cannot be a branch out of the structured block.
1182 // * The point of entry must not be a call to setjmp().
1183 // * longjmp() and throw() must not violate the entry/exit criteria.
1184 // * An expression statement, iteration statement, selection statement, or
1185 // try block is considered to be a structured block if the corresponding
1186 // compound statement obtained by enclosing it in { and } would be a
1187 // structured block.
1188 // It is analyzed in Sema, so we can just call __kmpc_end_single() on
1189 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001190 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001191 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1192 llvm::makeArrayRef(Args));
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001193 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001194 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1195 // <copy_func>, did_it);
1196 if (DidIt) {
1197 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1198 auto CopyprivateArrayTy =
1199 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1200 /*IndexTypeQuals=*/0);
1201 // Create a list of all private variables for copyprivate.
1202 auto *CopyprivateList =
1203 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1204 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001205 auto *Elem = CGF.Builder.CreateStructGEP(
1206 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001207 CGF.Builder.CreateAlignedStore(
1208 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1209 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1210 Elem, CGM.PointerAlignInBytes);
1211 }
1212 // Build function that copies private values from single region to all other
1213 // threads in the corresponding parallel region.
1214 auto *CpyFn = emitCopyprivateCopyFunction(
1215 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
1216 SrcExprs, DstExprs, AssignmentOps);
1217 auto *BufSize = CGF.Builder.getInt32(
1218 C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
1219 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1220 CGF.VoidPtrTy);
1221 auto *DidItVal =
1222 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1223 llvm::Value *Args[] = {
1224 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1225 getThreadID(CGF, Loc), // i32 <gtid>
1226 BufSize, // i32 <buf_size>
1227 CL, // void *<copyprivate list>
1228 CpyFn, // void (*) (void *, void *) <copy_func>
1229 DidItVal // i32 did_it
1230 };
1231 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1232 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001233}
1234
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001235void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001236 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001237 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001238 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1239 if (Kind == OMPD_for) {
1240 Flags =
1241 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1242 } else if (Kind == OMPD_sections) {
1243 Flags = static_cast<OpenMPLocationFlags>(Flags |
1244 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1245 } else if (Kind == OMPD_single) {
1246 Flags =
1247 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1248 } else if (Kind == OMPD_barrier) {
1249 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1250 } else {
1251 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1252 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001253 // Build call __kmpc_cancel_barrier(loc, thread_id);
1254 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1255 // one provides the same functionality and adds initial support for
1256 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1257 // is provided default by the runtime library so it safe to make such
1258 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001259 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1260 getThreadID(CGF, Loc)};
1261 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001262}
1263
Alexander Musmanc6388682014-12-15 07:07:06 +00001264/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1265/// the enum sched_type in kmp.h).
1266enum OpenMPSchedType {
1267 /// \brief Lower bound for default (unordered) versions.
1268 OMP_sch_lower = 32,
1269 OMP_sch_static_chunked = 33,
1270 OMP_sch_static = 34,
1271 OMP_sch_dynamic_chunked = 35,
1272 OMP_sch_guided_chunked = 36,
1273 OMP_sch_runtime = 37,
1274 OMP_sch_auto = 38,
1275 /// \brief Lower bound for 'ordered' versions.
1276 OMP_ord_lower = 64,
1277 /// \brief Lower bound for 'nomerge' versions.
1278 OMP_nm_lower = 160,
1279};
1280
1281/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1282static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
1283 bool Chunked) {
1284 switch (ScheduleKind) {
1285 case OMPC_SCHEDULE_static:
1286 return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
1287 case OMPC_SCHEDULE_dynamic:
1288 return OMP_sch_dynamic_chunked;
1289 case OMPC_SCHEDULE_guided:
1290 return OMP_sch_guided_chunked;
1291 case OMPC_SCHEDULE_auto:
1292 return OMP_sch_auto;
1293 case OMPC_SCHEDULE_runtime:
1294 return OMP_sch_runtime;
1295 case OMPC_SCHEDULE_unknown:
1296 assert(!Chunked && "chunk was specified but schedule kind not known");
1297 return OMP_sch_static;
1298 }
1299 llvm_unreachable("Unexpected runtime schedule");
1300}
1301
1302bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1303 bool Chunked) const {
1304 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
1305 return Schedule == OMP_sch_static;
1306}
1307
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001308bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
1309 auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
1310 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1311 return Schedule != OMP_sch_static;
1312}
1313
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001314void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1315 OpenMPScheduleClauseKind ScheduleKind,
1316 unsigned IVSize, bool IVSigned,
1317 llvm::Value *IL, llvm::Value *LB,
1318 llvm::Value *UB, llvm::Value *ST,
1319 llvm::Value *Chunk) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001320 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001321 if (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked) {
1322 // Call __kmpc_dispatch_init(
1323 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1324 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1325 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001326
Alexander Musman92bdaab2015-03-12 13:37:50 +00001327 // If the Chunk was not specified in the clause - use default value 1.
1328 if (Chunk == nullptr)
1329 Chunk = CGF.Builder.getIntN(IVSize, 1);
1330 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1331 getThreadID(CGF, Loc),
1332 CGF.Builder.getInt32(Schedule), // Schedule type
1333 CGF.Builder.getIntN(IVSize, 0), // Lower
1334 UB, // Upper
1335 CGF.Builder.getIntN(IVSize, 1), // Stride
1336 Chunk // Chunk
1337 };
1338 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1339 } else {
1340 // Call __kmpc_for_static_init(
1341 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1342 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1343 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1344 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1345 if (Chunk == nullptr) {
1346 assert(Schedule == OMP_sch_static &&
1347 "expected static non-chunked schedule");
1348 // If the Chunk was not specified in the clause - use default value 1.
1349 Chunk = CGF.Builder.getIntN(IVSize, 1);
1350 } else
1351 assert(Schedule == OMP_sch_static_chunked &&
1352 "expected static chunked schedule");
1353 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1354 getThreadID(CGF, Loc),
1355 CGF.Builder.getInt32(Schedule), // Schedule type
1356 IL, // &isLastIter
1357 LB, // &LB
1358 UB, // &UB
1359 ST, // &Stride
1360 CGF.Builder.getIntN(IVSize, 1), // Incr
1361 Chunk // Chunk
1362 };
Alexander Musman21212e42015-03-13 10:38:23 +00001363 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001364 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001365}
1366
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001367void CGOpenMPRuntime::emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
1368 OpenMPScheduleClauseKind ScheduleKind) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001369 assert((ScheduleKind == OMPC_SCHEDULE_static ||
1370 ScheduleKind == OMPC_SCHEDULE_unknown) &&
1371 "Non-static schedule kinds are not yet implemented");
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001372 (void)ScheduleKind;
Alexander Musmanc6388682014-12-15 07:07:06 +00001373 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001374 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1375 getThreadID(CGF, Loc)};
1376 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1377 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001378}
1379
Alexander Musman92bdaab2015-03-12 13:37:50 +00001380llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1381 SourceLocation Loc, unsigned IVSize,
1382 bool IVSigned, llvm::Value *IL,
1383 llvm::Value *LB, llvm::Value *UB,
1384 llvm::Value *ST) {
1385 // Call __kmpc_dispatch_next(
1386 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1387 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1388 // kmp_int[32|64] *p_stride);
1389 llvm::Value *Args[] = {
1390 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1391 IL, // &isLastIter
1392 LB, // &Lower
1393 UB, // &Upper
1394 ST // &Stride
1395 };
1396 llvm::Value *Call =
1397 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1398 return CGF.EmitScalarConversion(
1399 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1400 CGF.getContext().BoolTy);
1401}
1402
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001403void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1404 llvm::Value *NumThreads,
1405 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001406 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1407 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001408 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001409 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001410 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1411 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001412}
1413
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001414void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1415 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001416 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001417 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1418 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001419}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001420
Alexey Bataev62b63b12015-03-10 07:28:44 +00001421namespace {
1422/// \brief Indexes of fields for type kmp_task_t.
1423enum KmpTaskTFields {
1424 /// \brief List of shared variables.
1425 KmpTaskTShareds,
1426 /// \brief Task routine.
1427 KmpTaskTRoutine,
1428 /// \brief Partition id for the untied tasks.
1429 KmpTaskTPartId,
1430 /// \brief Function with call of destructors for private variables.
1431 KmpTaskTDestructors,
1432};
1433} // namespace
1434
1435void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1436 if (!KmpRoutineEntryPtrTy) {
1437 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1438 auto &C = CGM.getContext();
1439 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1440 FunctionProtoType::ExtProtoInfo EPI;
1441 KmpRoutineEntryPtrQTy = C.getPointerType(
1442 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1443 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1444 }
1445}
1446
1447static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1448 QualType FieldTy) {
1449 auto *Field = FieldDecl::Create(
1450 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1451 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1452 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1453 Field->setAccess(AS_public);
1454 DC->addDecl(Field);
1455}
1456
1457static QualType createKmpTaskTRecordDecl(CodeGenModule &CGM,
1458 QualType KmpInt32Ty,
1459 QualType KmpRoutineEntryPointerQTy) {
1460 auto &C = CGM.getContext();
1461 // Build struct kmp_task_t {
1462 // void * shareds;
1463 // kmp_routine_entry_t routine;
1464 // kmp_int32 part_id;
1465 // kmp_routine_entry_t destructors;
1466 // /* private vars */
1467 // };
1468 auto *RD = C.buildImplicitRecord("kmp_task_t");
1469 RD->startDefinition();
1470 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1471 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1472 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1473 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1474 // TODO: add private fields.
1475 RD->completeDefinition();
1476 return C.getRecordType(RD);
1477}
1478
1479/// \brief Emit a proxy function which accepts kmp_task_t as the second
1480/// argument.
1481/// \code
1482/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1483/// TaskFunction(gtid, tt->part_id, tt->shareds);
1484/// return 0;
1485/// }
1486/// \endcode
1487static llvm::Value *
1488emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
1489 QualType KmpInt32Ty, QualType KmpTaskTPtrQTy,
David Blaikie2e804282015-04-05 22:47:07 +00001490 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1491 llvm::Type *KmpTaskTTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001492 auto &C = CGM.getContext();
1493 FunctionArgList Args;
1494 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1495 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
1496 /*Id=*/nullptr, KmpTaskTPtrQTy);
1497 Args.push_back(&GtidArg);
1498 Args.push_back(&TaskTypeArg);
1499 FunctionType::ExtInfo Info;
1500 auto &TaskEntryFnInfo =
1501 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1502 /*isVariadic=*/false);
1503 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1504 auto *TaskEntry =
1505 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1506 ".omp_task_entry.", &CGM.getModule());
1507 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1508 CodeGenFunction CGF(CGM);
1509 CGF.disableDebugInfo();
1510 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1511
1512 // TaskFunction(gtid, tt->part_id, tt->shareds);
1513 auto *GtidParam = CGF.EmitLoadOfScalar(
1514 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1515 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1516 auto TaskTypeArgAddr = CGF.EmitLoadOfScalar(
1517 CGF.GetAddrOfLocalVar(&TaskTypeArg), /*Volatile=*/false,
1518 CGM.PointerAlignInBytes, KmpTaskTPtrQTy, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001519 auto *PartidPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001520 /*Idx=*/KmpTaskTPartId);
1521 auto *PartidParam = CGF.EmitLoadOfScalar(
1522 PartidPtr, /*Volatile=*/false,
1523 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001524 auto *SharedsPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001525 /*Idx=*/KmpTaskTShareds);
1526 auto *SharedsParam =
1527 CGF.EmitLoadOfScalar(SharedsPtr, /*Volatile=*/false,
1528 CGM.PointerAlignInBytes, C.VoidPtrTy, Loc);
1529 llvm::Value *CallArgs[] = {
1530 GtidParam, PartidParam,
1531 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1532 SharedsParam, CGF.ConvertTypeForMem(SharedsPtrTy))};
1533 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1534 CGF.EmitStoreThroughLValue(
1535 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1536 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1537 CGF.FinishFunction();
1538 return TaskEntry;
1539}
1540
1541void CGOpenMPRuntime::emitTaskCall(
1542 CodeGenFunction &CGF, SourceLocation Loc, bool Tied,
1543 llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1544 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds) {
1545 auto &C = CGM.getContext();
1546 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1547 // Build type kmp_routine_entry_t (if not built yet).
1548 emitKmpRoutineEntryT(KmpInt32Ty);
1549 // Build particular struct kmp_task_t for the given task.
1550 auto KmpTaskQTy =
1551 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy);
1552 QualType KmpTaskTPtrQTy = C.getPointerType(KmpTaskQTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00001553 auto *KmpTaskTTy = CGF.ConvertType(KmpTaskQTy);
1554 auto *KmpTaskTPtrTy = KmpTaskTTy->getPointerTo();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001555 auto KmpTaskTySize = CGM.getSize(C.getTypeSizeInChars(KmpTaskQTy));
1556 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
1557
1558 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
1559 // kmp_task_t *tt);
David Blaikie1ed728c2015-04-05 22:45:47 +00001560 auto *TaskEntry =
1561 emitProxyTaskFunction(CGM, Loc, KmpInt32Ty, KmpTaskTPtrQTy, SharedsPtrTy,
1562 TaskFunction, KmpTaskTTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001563
1564 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1565 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1566 // kmp_routine_entry_t *task_entry);
1567 // Task flags. Format is taken from
1568 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
1569 // description of kmp_tasking_flags struct.
1570 const unsigned TiedFlag = 0x1;
1571 const unsigned FinalFlag = 0x2;
1572 unsigned Flags = Tied ? TiedFlag : 0;
1573 auto *TaskFlags =
1574 Final.getPointer()
1575 ? CGF.Builder.CreateSelect(Final.getPointer(),
1576 CGF.Builder.getInt32(FinalFlag),
1577 CGF.Builder.getInt32(/*C=*/0))
1578 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
1579 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
1580 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
1581 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
1582 getThreadID(CGF, Loc), TaskFlags, KmpTaskTySize,
1583 CGM.getSize(SharedsSize),
1584 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1585 TaskEntry, KmpRoutineEntryPtrTy)};
1586 auto *NewTask = CGF.EmitRuntimeCall(
1587 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
1588 auto *NewTaskNewTaskTTy =
1589 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NewTask, KmpTaskTPtrTy);
1590 // Fill the data in the resulting kmp_task_t record.
1591 // Copy shareds if there are any.
1592 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty())
1593 CGF.EmitAggregateCopy(
1594 CGF.EmitLoadOfScalar(
David Blaikie1ed728c2015-04-05 22:45:47 +00001595 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001596 /*Idx=*/KmpTaskTShareds),
1597 /*Volatile=*/false, CGM.PointerAlignInBytes, SharedsPtrTy, Loc),
1598 Shareds, SharedsTy);
1599 // TODO: generate function with destructors for privates.
1600 // Provide pointer to function with destructors for privates.
1601 CGF.Builder.CreateAlignedStore(
1602 llvm::ConstantPointerNull::get(
1603 cast<llvm::PointerType>(KmpRoutineEntryPtrTy)),
David Blaikie1ed728c2015-04-05 22:45:47 +00001604 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001605 /*Idx=*/KmpTaskTDestructors),
1606 CGM.PointerAlignInBytes);
1607
1608 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
1609 // libcall.
1610 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1611 // *new_task);
1612 llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc),
1613 getThreadID(CGF, Loc), NewTask};
1614 // TODO: add check for untied tasks.
1615 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1616}
1617
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001618void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
1619 const RegionCodeGenTy &CodeGen) {
1620 InlinedOpenMPRegionRAII Region(CGF, CodeGen);
1621 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001622}
1623