blob: bb00a0cd3751efe7389a112fcbdf51ea4bda22ac [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 Bataev794ba0d2015-04-10 10:43:45 +0000660 case OMPRTL__kmpc_reduce: {
661 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
662 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
663 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
664 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
665 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
666 /*isVarArg=*/false);
667 llvm::Type *TypeParams[] = {
668 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
669 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
670 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
671 llvm::FunctionType *FnTy =
672 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
673 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
674 break;
675 }
676 case OMPRTL__kmpc_reduce_nowait: {
677 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
678 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
679 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
680 // *lck);
681 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
682 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
683 /*isVarArg=*/false);
684 llvm::Type *TypeParams[] = {
685 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
686 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
687 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
688 llvm::FunctionType *FnTy =
689 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
690 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
691 break;
692 }
693 case OMPRTL__kmpc_end_reduce: {
694 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
695 // kmp_critical_name *lck);
696 llvm::Type *TypeParams[] = {
697 getIdentTyPointerTy(), CGM.Int32Ty,
698 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
699 llvm::FunctionType *FnTy =
700 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
701 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
702 break;
703 }
704 case OMPRTL__kmpc_end_reduce_nowait: {
705 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
706 // kmp_critical_name *lck);
707 llvm::Type *TypeParams[] = {
708 getIdentTyPointerTy(), CGM.Int32Ty,
709 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
710 llvm::FunctionType *FnTy =
711 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
712 RTLFn =
713 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
714 break;
715 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000716 }
717 return RTLFn;
718}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000719
Alexander Musman21212e42015-03-13 10:38:23 +0000720llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
721 bool IVSigned) {
722 assert((IVSize == 32 || IVSize == 64) &&
723 "IV size is not compatible with the omp runtime");
724 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
725 : "__kmpc_for_static_init_4u")
726 : (IVSigned ? "__kmpc_for_static_init_8"
727 : "__kmpc_for_static_init_8u");
728 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
729 auto PtrTy = llvm::PointerType::getUnqual(ITy);
730 llvm::Type *TypeParams[] = {
731 getIdentTyPointerTy(), // loc
732 CGM.Int32Ty, // tid
733 CGM.Int32Ty, // schedtype
734 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
735 PtrTy, // p_lower
736 PtrTy, // p_upper
737 PtrTy, // p_stride
738 ITy, // incr
739 ITy // chunk
740 };
741 llvm::FunctionType *FnTy =
742 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
743 return CGM.CreateRuntimeFunction(FnTy, Name);
744}
745
Alexander Musman92bdaab2015-03-12 13:37:50 +0000746llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
747 bool IVSigned) {
748 assert((IVSize == 32 || IVSize == 64) &&
749 "IV size is not compatible with the omp runtime");
750 auto Name =
751 IVSize == 32
752 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
753 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
754 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
755 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
756 CGM.Int32Ty, // tid
757 CGM.Int32Ty, // schedtype
758 ITy, // lower
759 ITy, // upper
760 ITy, // stride
761 ITy // chunk
762 };
763 llvm::FunctionType *FnTy =
764 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
765 return CGM.CreateRuntimeFunction(FnTy, Name);
766}
767
768llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
769 bool IVSigned) {
770 assert((IVSize == 32 || IVSize == 64) &&
771 "IV size is not compatible with the omp runtime");
772 auto Name =
773 IVSize == 32
774 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
775 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
776 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
777 auto PtrTy = llvm::PointerType::getUnqual(ITy);
778 llvm::Type *TypeParams[] = {
779 getIdentTyPointerTy(), // loc
780 CGM.Int32Ty, // tid
781 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
782 PtrTy, // p_lower
783 PtrTy, // p_upper
784 PtrTy // p_stride
785 };
786 llvm::FunctionType *FnTy =
787 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
788 return CGM.CreateRuntimeFunction(FnTy, Name);
789}
790
Alexey Bataev97720002014-11-11 04:05:39 +0000791llvm::Constant *
792CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
793 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000794 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000795 Twine(CGM.getMangledName(VD)) + ".cache.");
796}
797
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000798llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
799 const VarDecl *VD,
800 llvm::Value *VDAddr,
801 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000802 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000803 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000804 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
805 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
806 getOrCreateThreadPrivateCache(VD)};
807 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000808 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000809}
810
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000811void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000812 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
813 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
814 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
815 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000816 auto OMPLoc = emitUpdateLocation(CGF, Loc);
817 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000818 OMPLoc);
819 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
820 // to register constructor/destructor for variable.
821 llvm::Value *Args[] = {OMPLoc,
822 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
823 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000824 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000825 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000826}
827
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000828llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000829 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
830 bool PerformInit, CodeGenFunction *CGF) {
831 VD = VD->getDefinition(CGM.getContext());
832 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
833 ThreadPrivateWithDefinition.insert(VD);
834 QualType ASTTy = VD->getType();
835
836 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
837 auto Init = VD->getAnyInitializer();
838 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
839 // Generate function that re-emits the declaration's initializer into the
840 // threadprivate copy of the variable VD
841 CodeGenFunction CtorCGF(CGM);
842 FunctionArgList Args;
843 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
844 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
845 Args.push_back(&Dst);
846
847 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
848 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
849 /*isVariadic=*/false);
850 auto FTy = CGM.getTypes().GetFunctionType(FI);
851 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
852 FTy, ".__kmpc_global_ctor_.", Loc);
853 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
854 Args, SourceLocation());
855 auto ArgVal = CtorCGF.EmitLoadOfScalar(
856 CtorCGF.GetAddrOfLocalVar(&Dst),
857 /*Volatile=*/false, CGM.PointerAlignInBytes,
858 CGM.getContext().VoidPtrTy, Dst.getLocation());
859 auto Arg = CtorCGF.Builder.CreatePointerCast(
860 ArgVal,
861 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
862 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
863 /*IsInitializer=*/true);
864 ArgVal = CtorCGF.EmitLoadOfScalar(
865 CtorCGF.GetAddrOfLocalVar(&Dst),
866 /*Volatile=*/false, CGM.PointerAlignInBytes,
867 CGM.getContext().VoidPtrTy, Dst.getLocation());
868 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
869 CtorCGF.FinishFunction();
870 Ctor = Fn;
871 }
872 if (VD->getType().isDestructedType() != QualType::DK_none) {
873 // Generate function that emits destructor call for the threadprivate copy
874 // of the variable VD
875 CodeGenFunction DtorCGF(CGM);
876 FunctionArgList Args;
877 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
878 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
879 Args.push_back(&Dst);
880
881 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
882 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
883 /*isVariadic=*/false);
884 auto FTy = CGM.getTypes().GetFunctionType(FI);
885 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
886 FTy, ".__kmpc_global_dtor_.", Loc);
887 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
888 SourceLocation());
889 auto ArgVal = DtorCGF.EmitLoadOfScalar(
890 DtorCGF.GetAddrOfLocalVar(&Dst),
891 /*Volatile=*/false, CGM.PointerAlignInBytes,
892 CGM.getContext().VoidPtrTy, Dst.getLocation());
893 DtorCGF.emitDestroy(ArgVal, ASTTy,
894 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
895 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
896 DtorCGF.FinishFunction();
897 Dtor = Fn;
898 }
899 // Do not emit init function if it is not required.
900 if (!Ctor && !Dtor)
901 return nullptr;
902
903 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
904 auto CopyCtorTy =
905 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
906 /*isVarArg=*/false)->getPointerTo();
907 // Copying constructor for the threadprivate variable.
908 // Must be NULL - reserved by runtime, but currently it requires that this
909 // parameter is always NULL. Otherwise it fires assertion.
910 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
911 if (Ctor == nullptr) {
912 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
913 /*isVarArg=*/false)->getPointerTo();
914 Ctor = llvm::Constant::getNullValue(CtorTy);
915 }
916 if (Dtor == nullptr) {
917 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
918 /*isVarArg=*/false)->getPointerTo();
919 Dtor = llvm::Constant::getNullValue(DtorTy);
920 }
921 if (!CGF) {
922 auto InitFunctionTy =
923 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
924 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
925 InitFunctionTy, ".__omp_threadprivate_init_.");
926 CodeGenFunction InitCGF(CGM);
927 FunctionArgList ArgList;
928 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
929 CGM.getTypes().arrangeNullaryFunction(), ArgList,
930 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000931 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000932 InitCGF.FinishFunction();
933 return InitFunction;
934 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000935 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000936 }
937 return nullptr;
938}
939
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000940void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
941 llvm::Value *OutlinedFn,
942 llvm::Value *CapturedStruct) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000943 // Build call __kmpc_fork_call(loc, 1, microtask, captured_struct/*context*/)
944 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000945 emitUpdateLocation(CGF, Loc),
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000946 CGF.Builder.getInt32(1), // Number of arguments after 'microtask' argument
947 // (there is only one additional argument - 'context')
948 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
949 CGF.EmitCastToVoidPtr(CapturedStruct)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000950 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000951 CGF.EmitRuntimeCall(RTLFn, Args);
952}
953
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000954void CGOpenMPRuntime::emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
955 llvm::Value *OutlinedFn,
956 llvm::Value *CapturedStruct) {
957 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000958 // Build calls:
959 // __kmpc_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000960 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), ThreadID};
961 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
962 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000963
964 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000965 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000966 auto Int32Ty =
967 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
968 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
969 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
970 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
971 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
972
973 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000974 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
975 CGF.EmitRuntimeCall(
976 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000977}
978
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +0000979// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +0000980// thread-ID variable (it is passed in a first argument of the outlined function
981// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
982// regular serial code region, get thread ID by calling kmp_int32
983// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
984// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000985llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +0000986 SourceLocation Loc) {
987 if (auto OMPRegionInfo =
988 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000989 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +0000990 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000991
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000992 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000993 auto Int32Ty =
994 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
995 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
996 CGF.EmitStoreOfScalar(ThreadID,
997 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
998
999 return ThreadIDTemp;
1000}
1001
Alexey Bataev97720002014-11-11 04:05:39 +00001002llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001003CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001004 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001005 SmallString<256> Buffer;
1006 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001007 Out << Name;
1008 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001009 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1010 if (Elem.second) {
1011 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001012 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001013 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001014 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001015
David Blaikie13156b62014-11-19 03:06:06 +00001016 return Elem.second = new llvm::GlobalVariable(
1017 CGM.getModule(), Ty, /*IsConstant*/ false,
1018 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1019 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001020}
1021
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001022llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001023 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001024 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001025}
1026
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001027namespace {
1028class CallEndCleanup : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001029public:
1030 typedef ArrayRef<llvm::Value *> CleanupValuesTy;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001031private:
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001032 llvm::Value *Callee;
1033 llvm::SmallVector<llvm::Value *, 8> Args;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001034
1035public:
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001036 CallEndCleanup(llvm::Value *Callee, CleanupValuesTy Args)
1037 : Callee(Callee), Args(Args.begin(), Args.end()) {}
1038 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1039 CGF.EmitRuntimeCall(Callee, Args);
1040 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001041};
1042} // namespace
1043
1044void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1045 StringRef CriticalName,
1046 const RegionCodeGenTy &CriticalOpGen,
1047 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001048 // __kmpc_critical(ident_t *, gtid, Lock);
1049 // CriticalOpGen();
1050 // __kmpc_end_critical(ident_t *, gtid, Lock);
1051 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001052 {
1053 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001054 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1055 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001056 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001057 // Build a call to __kmpc_end_critical
1058 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001059 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1060 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001061 emitInlinedDirective(CGF, CriticalOpGen);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001062 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001063}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001064
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001065static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001066 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001067 llvm::Value *CallBool = CGF.EmitScalarConversion(
1068 IfCond,
1069 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1070 CGF.getContext().BoolTy);
1071
1072 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1073 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1074 // Generate the branch (If-stmt)
1075 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1076 CGF.EmitBlock(ThenBlock);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001077 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001078 // Emit the rest of bblocks/branches
1079 CGF.EmitBranch(ContBlock);
1080 CGF.EmitBlock(ContBlock, true);
1081}
1082
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001083void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001084 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001085 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001086 // if(__kmpc_master(ident_t *, gtid)) {
1087 // MasterOpGen();
1088 // __kmpc_end_master(ident_t *, gtid);
1089 // }
1090 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001091 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001092 auto *IsMaster =
1093 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001094 emitIfStmt(CGF, IsMaster, [&](CodeGenFunction &CGF) -> void {
1095 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001096 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001097 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1098 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001099 MasterOpGen(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001100 });
1101}
1102
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001103void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1104 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001105 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1106 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001107 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001108 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001109 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001110}
1111
Alexey Bataeva63048e2015-03-23 06:18:07 +00001112static llvm::Value *emitCopyprivateCopyFunction(
1113 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> SrcExprs,
1114 ArrayRef<const Expr *> DstExprs, ArrayRef<const Expr *> AssignmentOps) {
1115 auto &C = CGM.getContext();
1116 // void copy_func(void *LHSArg, void *RHSArg);
1117 FunctionArgList Args;
1118 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1119 C.VoidPtrTy);
1120 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1121 C.VoidPtrTy);
1122 Args.push_back(&LHSArg);
1123 Args.push_back(&RHSArg);
1124 FunctionType::ExtInfo EI;
1125 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1126 C.VoidTy, Args, EI, /*isVariadic=*/false);
1127 auto *Fn = llvm::Function::Create(
1128 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1129 ".omp.copyprivate.copy_func", &CGM.getModule());
1130 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1131 CodeGenFunction CGF(CGM);
1132 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1133 // Dst = (void*[n])(LHSArg);
1134 // Src = (void*[n])(RHSArg);
1135 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1136 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1137 CGF.PointerAlignInBytes),
1138 ArgsType);
1139 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1140 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1141 CGF.PointerAlignInBytes),
1142 ArgsType);
1143 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1144 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1145 // ...
1146 // *(Typen*)Dst[n] = *(Typen*)Src[n];
1147 CodeGenFunction::OMPPrivateScope Scope(CGF);
1148 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
1149 Scope.addPrivate(
1150 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1151 [&]() -> llvm::Value *{
1152 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001153 CGF.Builder.CreateAlignedLoad(
1154 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1155 CGM.PointerAlignInBytes),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001156 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1157 });
1158 Scope.addPrivate(
1159 cast<VarDecl>(cast<DeclRefExpr>(DstExprs[I])->getDecl()),
1160 [&]() -> llvm::Value *{
1161 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001162 CGF.Builder.CreateAlignedLoad(
1163 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1164 CGM.PointerAlignInBytes),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001165 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1166 });
1167 }
1168 Scope.Privatize();
1169 for (auto *E : AssignmentOps) {
1170 CGF.EmitIgnoredExpr(E);
1171 }
1172 Scope.ForceCleanup();
1173 CGF.FinishFunction();
1174 return Fn;
1175}
1176
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001177void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001178 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001179 SourceLocation Loc,
1180 ArrayRef<const Expr *> CopyprivateVars,
1181 ArrayRef<const Expr *> SrcExprs,
1182 ArrayRef<const Expr *> DstExprs,
1183 ArrayRef<const Expr *> AssignmentOps) {
1184 assert(CopyprivateVars.size() == SrcExprs.size() &&
1185 CopyprivateVars.size() == DstExprs.size() &&
1186 CopyprivateVars.size() == AssignmentOps.size());
1187 auto &C = CGM.getContext();
1188 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001189 // if(__kmpc_single(ident_t *, gtid)) {
1190 // SingleOpGen();
1191 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001192 // did_it = 1;
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
1197 llvm::AllocaInst *DidIt = nullptr;
1198 if (!CopyprivateVars.empty()) {
1199 // int32 did_it = 0;
1200 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1201 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
1202 CGF.InitTempAlloca(DidIt, CGF.Builder.getInt32(0));
1203 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001204 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001205 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001206 auto *IsSingle =
1207 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001208 emitIfStmt(CGF, IsSingle, [&](CodeGenFunction &CGF) -> void {
1209 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001210 CGF.EHStack.pushCleanup<CallEndCleanup>(
1211 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1212 llvm::makeArrayRef(Args));
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001213 SingleOpGen(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001214 if (DidIt) {
1215 // did_it = 1;
1216 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1217 DidIt->getAlignment());
1218 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001219 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001220 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1221 // <copy_func>, did_it);
1222 if (DidIt) {
1223 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1224 auto CopyprivateArrayTy =
1225 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1226 /*IndexTypeQuals=*/0);
1227 // Create a list of all private variables for copyprivate.
1228 auto *CopyprivateList =
1229 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1230 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001231 auto *Elem = CGF.Builder.CreateStructGEP(
1232 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001233 CGF.Builder.CreateAlignedStore(
1234 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1235 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1236 Elem, CGM.PointerAlignInBytes);
1237 }
1238 // Build function that copies private values from single region to all other
1239 // threads in the corresponding parallel region.
1240 auto *CpyFn = emitCopyprivateCopyFunction(
1241 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
1242 SrcExprs, DstExprs, AssignmentOps);
1243 auto *BufSize = CGF.Builder.getInt32(
1244 C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
1245 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1246 CGF.VoidPtrTy);
1247 auto *DidItVal =
1248 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1249 llvm::Value *Args[] = {
1250 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1251 getThreadID(CGF, Loc), // i32 <gtid>
1252 BufSize, // i32 <buf_size>
1253 CL, // void *<copyprivate list>
1254 CpyFn, // void (*) (void *, void *) <copy_func>
1255 DidItVal // i32 did_it
1256 };
1257 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1258 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001259}
1260
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001261void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001262 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001263 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001264 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1265 if (Kind == OMPD_for) {
1266 Flags =
1267 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1268 } else if (Kind == OMPD_sections) {
1269 Flags = static_cast<OpenMPLocationFlags>(Flags |
1270 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1271 } else if (Kind == OMPD_single) {
1272 Flags =
1273 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1274 } else if (Kind == OMPD_barrier) {
1275 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1276 } else {
1277 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1278 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001279 // Build call __kmpc_cancel_barrier(loc, thread_id);
1280 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1281 // one provides the same functionality and adds initial support for
1282 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1283 // is provided default by the runtime library so it safe to make such
1284 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001285 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1286 getThreadID(CGF, Loc)};
1287 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001288}
1289
Alexander Musmanc6388682014-12-15 07:07:06 +00001290/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1291/// the enum sched_type in kmp.h).
1292enum OpenMPSchedType {
1293 /// \brief Lower bound for default (unordered) versions.
1294 OMP_sch_lower = 32,
1295 OMP_sch_static_chunked = 33,
1296 OMP_sch_static = 34,
1297 OMP_sch_dynamic_chunked = 35,
1298 OMP_sch_guided_chunked = 36,
1299 OMP_sch_runtime = 37,
1300 OMP_sch_auto = 38,
1301 /// \brief Lower bound for 'ordered' versions.
1302 OMP_ord_lower = 64,
1303 /// \brief Lower bound for 'nomerge' versions.
1304 OMP_nm_lower = 160,
1305};
1306
1307/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1308static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
1309 bool Chunked) {
1310 switch (ScheduleKind) {
1311 case OMPC_SCHEDULE_static:
1312 return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
1313 case OMPC_SCHEDULE_dynamic:
1314 return OMP_sch_dynamic_chunked;
1315 case OMPC_SCHEDULE_guided:
1316 return OMP_sch_guided_chunked;
1317 case OMPC_SCHEDULE_auto:
1318 return OMP_sch_auto;
1319 case OMPC_SCHEDULE_runtime:
1320 return OMP_sch_runtime;
1321 case OMPC_SCHEDULE_unknown:
1322 assert(!Chunked && "chunk was specified but schedule kind not known");
1323 return OMP_sch_static;
1324 }
1325 llvm_unreachable("Unexpected runtime schedule");
1326}
1327
1328bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1329 bool Chunked) const {
1330 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
1331 return Schedule == OMP_sch_static;
1332}
1333
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001334bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
1335 auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
1336 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1337 return Schedule != OMP_sch_static;
1338}
1339
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001340void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1341 OpenMPScheduleClauseKind ScheduleKind,
1342 unsigned IVSize, bool IVSigned,
1343 llvm::Value *IL, llvm::Value *LB,
1344 llvm::Value *UB, llvm::Value *ST,
1345 llvm::Value *Chunk) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001346 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001347 if (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked) {
1348 // Call __kmpc_dispatch_init(
1349 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1350 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1351 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001352
Alexander Musman92bdaab2015-03-12 13:37:50 +00001353 // If the Chunk was not specified in the clause - use default value 1.
1354 if (Chunk == nullptr)
1355 Chunk = CGF.Builder.getIntN(IVSize, 1);
1356 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1357 getThreadID(CGF, Loc),
1358 CGF.Builder.getInt32(Schedule), // Schedule type
1359 CGF.Builder.getIntN(IVSize, 0), // Lower
1360 UB, // Upper
1361 CGF.Builder.getIntN(IVSize, 1), // Stride
1362 Chunk // Chunk
1363 };
1364 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1365 } else {
1366 // Call __kmpc_for_static_init(
1367 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1368 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1369 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1370 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1371 if (Chunk == nullptr) {
1372 assert(Schedule == OMP_sch_static &&
1373 "expected static non-chunked schedule");
1374 // If the Chunk was not specified in the clause - use default value 1.
1375 Chunk = CGF.Builder.getIntN(IVSize, 1);
1376 } else
1377 assert(Schedule == OMP_sch_static_chunked &&
1378 "expected static chunked schedule");
1379 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1380 getThreadID(CGF, Loc),
1381 CGF.Builder.getInt32(Schedule), // Schedule type
1382 IL, // &isLastIter
1383 LB, // &LB
1384 UB, // &UB
1385 ST, // &Stride
1386 CGF.Builder.getIntN(IVSize, 1), // Incr
1387 Chunk // Chunk
1388 };
Alexander Musman21212e42015-03-13 10:38:23 +00001389 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001390 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001391}
1392
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001393void CGOpenMPRuntime::emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
1394 OpenMPScheduleClauseKind ScheduleKind) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001395 assert((ScheduleKind == OMPC_SCHEDULE_static ||
1396 ScheduleKind == OMPC_SCHEDULE_unknown) &&
1397 "Non-static schedule kinds are not yet implemented");
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001398 (void)ScheduleKind;
Alexander Musmanc6388682014-12-15 07:07:06 +00001399 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001400 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1401 getThreadID(CGF, Loc)};
1402 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1403 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001404}
1405
Alexander Musman92bdaab2015-03-12 13:37:50 +00001406llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1407 SourceLocation Loc, unsigned IVSize,
1408 bool IVSigned, llvm::Value *IL,
1409 llvm::Value *LB, llvm::Value *UB,
1410 llvm::Value *ST) {
1411 // Call __kmpc_dispatch_next(
1412 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1413 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1414 // kmp_int[32|64] *p_stride);
1415 llvm::Value *Args[] = {
1416 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1417 IL, // &isLastIter
1418 LB, // &Lower
1419 UB, // &Upper
1420 ST // &Stride
1421 };
1422 llvm::Value *Call =
1423 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1424 return CGF.EmitScalarConversion(
1425 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1426 CGF.getContext().BoolTy);
1427}
1428
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001429void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1430 llvm::Value *NumThreads,
1431 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001432 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1433 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001434 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001435 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001436 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1437 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001438}
1439
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001440void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1441 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001442 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001443 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1444 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001445}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001446
Alexey Bataev62b63b12015-03-10 07:28:44 +00001447namespace {
1448/// \brief Indexes of fields for type kmp_task_t.
1449enum KmpTaskTFields {
1450 /// \brief List of shared variables.
1451 KmpTaskTShareds,
1452 /// \brief Task routine.
1453 KmpTaskTRoutine,
1454 /// \brief Partition id for the untied tasks.
1455 KmpTaskTPartId,
1456 /// \brief Function with call of destructors for private variables.
1457 KmpTaskTDestructors,
1458};
1459} // namespace
1460
1461void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1462 if (!KmpRoutineEntryPtrTy) {
1463 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1464 auto &C = CGM.getContext();
1465 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1466 FunctionProtoType::ExtProtoInfo EPI;
1467 KmpRoutineEntryPtrQTy = C.getPointerType(
1468 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1469 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1470 }
1471}
1472
1473static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1474 QualType FieldTy) {
1475 auto *Field = FieldDecl::Create(
1476 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1477 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1478 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1479 Field->setAccess(AS_public);
1480 DC->addDecl(Field);
1481}
1482
1483static QualType createKmpTaskTRecordDecl(CodeGenModule &CGM,
1484 QualType KmpInt32Ty,
1485 QualType KmpRoutineEntryPointerQTy) {
1486 auto &C = CGM.getContext();
1487 // Build struct kmp_task_t {
1488 // void * shareds;
1489 // kmp_routine_entry_t routine;
1490 // kmp_int32 part_id;
1491 // kmp_routine_entry_t destructors;
1492 // /* private vars */
1493 // };
1494 auto *RD = C.buildImplicitRecord("kmp_task_t");
1495 RD->startDefinition();
1496 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1497 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1498 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1499 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1500 // TODO: add private fields.
1501 RD->completeDefinition();
1502 return C.getRecordType(RD);
1503}
1504
1505/// \brief Emit a proxy function which accepts kmp_task_t as the second
1506/// argument.
1507/// \code
1508/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1509/// TaskFunction(gtid, tt->part_id, tt->shareds);
1510/// return 0;
1511/// }
1512/// \endcode
1513static llvm::Value *
1514emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
1515 QualType KmpInt32Ty, QualType KmpTaskTPtrQTy,
David Blaikie2e804282015-04-05 22:47:07 +00001516 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1517 llvm::Type *KmpTaskTTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001518 auto &C = CGM.getContext();
1519 FunctionArgList Args;
1520 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1521 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
1522 /*Id=*/nullptr, KmpTaskTPtrQTy);
1523 Args.push_back(&GtidArg);
1524 Args.push_back(&TaskTypeArg);
1525 FunctionType::ExtInfo Info;
1526 auto &TaskEntryFnInfo =
1527 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1528 /*isVariadic=*/false);
1529 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1530 auto *TaskEntry =
1531 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1532 ".omp_task_entry.", &CGM.getModule());
1533 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1534 CodeGenFunction CGF(CGM);
1535 CGF.disableDebugInfo();
1536 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1537
1538 // TaskFunction(gtid, tt->part_id, tt->shareds);
1539 auto *GtidParam = CGF.EmitLoadOfScalar(
1540 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1541 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1542 auto TaskTypeArgAddr = CGF.EmitLoadOfScalar(
1543 CGF.GetAddrOfLocalVar(&TaskTypeArg), /*Volatile=*/false,
1544 CGM.PointerAlignInBytes, KmpTaskTPtrQTy, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001545 auto *PartidPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001546 /*Idx=*/KmpTaskTPartId);
1547 auto *PartidParam = CGF.EmitLoadOfScalar(
1548 PartidPtr, /*Volatile=*/false,
1549 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001550 auto *SharedsPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001551 /*Idx=*/KmpTaskTShareds);
1552 auto *SharedsParam =
1553 CGF.EmitLoadOfScalar(SharedsPtr, /*Volatile=*/false,
1554 CGM.PointerAlignInBytes, C.VoidPtrTy, Loc);
1555 llvm::Value *CallArgs[] = {
1556 GtidParam, PartidParam,
1557 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1558 SharedsParam, CGF.ConvertTypeForMem(SharedsPtrTy))};
1559 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1560 CGF.EmitStoreThroughLValue(
1561 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1562 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1563 CGF.FinishFunction();
1564 return TaskEntry;
1565}
1566
1567void CGOpenMPRuntime::emitTaskCall(
1568 CodeGenFunction &CGF, SourceLocation Loc, bool Tied,
1569 llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1570 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds) {
1571 auto &C = CGM.getContext();
1572 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1573 // Build type kmp_routine_entry_t (if not built yet).
1574 emitKmpRoutineEntryT(KmpInt32Ty);
1575 // Build particular struct kmp_task_t for the given task.
1576 auto KmpTaskQTy =
1577 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy);
1578 QualType KmpTaskTPtrQTy = C.getPointerType(KmpTaskQTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00001579 auto *KmpTaskTTy = CGF.ConvertType(KmpTaskQTy);
1580 auto *KmpTaskTPtrTy = KmpTaskTTy->getPointerTo();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001581 auto KmpTaskTySize = CGM.getSize(C.getTypeSizeInChars(KmpTaskQTy));
1582 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
1583
1584 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
1585 // kmp_task_t *tt);
David Blaikie1ed728c2015-04-05 22:45:47 +00001586 auto *TaskEntry =
1587 emitProxyTaskFunction(CGM, Loc, KmpInt32Ty, KmpTaskTPtrQTy, SharedsPtrTy,
1588 TaskFunction, KmpTaskTTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001589
1590 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1591 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1592 // kmp_routine_entry_t *task_entry);
1593 // Task flags. Format is taken from
1594 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
1595 // description of kmp_tasking_flags struct.
1596 const unsigned TiedFlag = 0x1;
1597 const unsigned FinalFlag = 0x2;
1598 unsigned Flags = Tied ? TiedFlag : 0;
1599 auto *TaskFlags =
1600 Final.getPointer()
1601 ? CGF.Builder.CreateSelect(Final.getPointer(),
1602 CGF.Builder.getInt32(FinalFlag),
1603 CGF.Builder.getInt32(/*C=*/0))
1604 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
1605 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
1606 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
1607 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
1608 getThreadID(CGF, Loc), TaskFlags, KmpTaskTySize,
1609 CGM.getSize(SharedsSize),
1610 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1611 TaskEntry, KmpRoutineEntryPtrTy)};
1612 auto *NewTask = CGF.EmitRuntimeCall(
1613 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
1614 auto *NewTaskNewTaskTTy =
1615 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NewTask, KmpTaskTPtrTy);
1616 // Fill the data in the resulting kmp_task_t record.
1617 // Copy shareds if there are any.
1618 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty())
1619 CGF.EmitAggregateCopy(
1620 CGF.EmitLoadOfScalar(
David Blaikie1ed728c2015-04-05 22:45:47 +00001621 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001622 /*Idx=*/KmpTaskTShareds),
1623 /*Volatile=*/false, CGM.PointerAlignInBytes, SharedsPtrTy, Loc),
1624 Shareds, SharedsTy);
1625 // TODO: generate function with destructors for privates.
1626 // Provide pointer to function with destructors for privates.
1627 CGF.Builder.CreateAlignedStore(
1628 llvm::ConstantPointerNull::get(
1629 cast<llvm::PointerType>(KmpRoutineEntryPtrTy)),
David Blaikie1ed728c2015-04-05 22:45:47 +00001630 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001631 /*Idx=*/KmpTaskTDestructors),
1632 CGM.PointerAlignInBytes);
1633
1634 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
1635 // libcall.
1636 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1637 // *new_task);
1638 llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc),
1639 getThreadID(CGF, Loc), NewTask};
1640 // TODO: add check for untied tasks.
1641 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1642}
1643
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001644static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
1645 llvm::Type *ArgsType,
1646 ArrayRef<const Expr *> LHSExprs,
1647 ArrayRef<const Expr *> RHSExprs,
1648 ArrayRef<const Expr *> ReductionOps) {
1649 auto &C = CGM.getContext();
1650
1651 // void reduction_func(void *LHSArg, void *RHSArg);
1652 FunctionArgList Args;
1653 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1654 C.VoidPtrTy);
1655 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1656 C.VoidPtrTy);
1657 Args.push_back(&LHSArg);
1658 Args.push_back(&RHSArg);
1659 FunctionType::ExtInfo EI;
1660 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1661 C.VoidTy, Args, EI, /*isVariadic=*/false);
1662 auto *Fn = llvm::Function::Create(
1663 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1664 ".omp.reduction.reduction_func", &CGM.getModule());
1665 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1666 CodeGenFunction CGF(CGM);
1667 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1668
1669 // Dst = (void*[n])(LHSArg);
1670 // Src = (void*[n])(RHSArg);
1671 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1672 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1673 CGF.PointerAlignInBytes),
1674 ArgsType);
1675 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1676 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1677 CGF.PointerAlignInBytes),
1678 ArgsType);
1679
1680 // ...
1681 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
1682 // ...
1683 CodeGenFunction::OMPPrivateScope Scope(CGF);
1684 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
1685 Scope.addPrivate(
1686 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()),
1687 [&]() -> llvm::Value *{
1688 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1689 CGF.Builder.CreateAlignedLoad(
1690 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, RHS, I),
1691 CGM.PointerAlignInBytes),
1692 CGF.ConvertTypeForMem(C.getPointerType(RHSExprs[I]->getType())));
1693 });
1694 Scope.addPrivate(
1695 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()),
1696 [&]() -> llvm::Value *{
1697 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1698 CGF.Builder.CreateAlignedLoad(
1699 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, LHS, I),
1700 CGM.PointerAlignInBytes),
1701 CGF.ConvertTypeForMem(C.getPointerType(LHSExprs[I]->getType())));
1702 });
1703 }
1704 Scope.Privatize();
1705 for (auto *E : ReductionOps) {
1706 CGF.EmitIgnoredExpr(E);
1707 }
1708 Scope.ForceCleanup();
1709 CGF.FinishFunction();
1710 return Fn;
1711}
1712
1713void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
1714 ArrayRef<const Expr *> LHSExprs,
1715 ArrayRef<const Expr *> RHSExprs,
1716 ArrayRef<const Expr *> ReductionOps,
1717 bool WithNowait) {
1718 // Next code should be emitted for reduction:
1719 //
1720 // static kmp_critical_name lock = { 0 };
1721 //
1722 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
1723 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
1724 // ...
1725 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
1726 // *(Type<n>-1*)rhs[<n>-1]);
1727 // }
1728 //
1729 // ...
1730 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
1731 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
1732 // RedList, reduce_func, &<lock>)) {
1733 // case 1:
1734 // ...
1735 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
1736 // ...
1737 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
1738 // break;
1739 // case 2:
1740 // ...
1741 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
1742 // ...
1743 // break;
1744 // default:;
1745 // }
1746
1747 auto &C = CGM.getContext();
1748
1749 // 1. Build a list of reduction variables.
1750 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
1751 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
1752 QualType ReductionArrayTy =
1753 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1754 /*IndexTypeQuals=*/0);
1755 auto *ReductionList =
1756 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
1757 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
1758 auto *Elem = CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, ReductionList, I);
1759 CGF.Builder.CreateAlignedStore(
1760 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1761 CGF.EmitLValue(RHSExprs[I]).getAddress(), CGF.VoidPtrTy),
1762 Elem, CGM.PointerAlignInBytes);
1763 }
1764
1765 // 2. Emit reduce_func().
1766 auto *ReductionFn = emitReductionFunction(
1767 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
1768 RHSExprs, ReductionOps);
1769
1770 // 3. Create static kmp_critical_name lock = { 0 };
1771 auto *Lock = getCriticalRegionLock(".reduction");
1772
1773 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
1774 // RedList, reduce_func, &<lock>);
1775 auto *IdentTLoc = emitUpdateLocation(
1776 CGF, Loc,
1777 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
1778 auto *ThreadId = getThreadID(CGF, Loc);
1779 auto *ReductionArrayTySize = llvm::ConstantInt::get(
1780 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
1781 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList,
1782 CGF.VoidPtrTy);
1783 llvm::Value *Args[] = {
1784 IdentTLoc, // ident_t *<loc>
1785 ThreadId, // i32 <gtid>
1786 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
1787 ReductionArrayTySize, // size_type sizeof(RedList)
1788 RL, // void *RedList
1789 ReductionFn, // void (*) (void *, void *) <reduce_func>
1790 Lock // kmp_critical_name *&<lock>
1791 };
1792 auto Res = CGF.EmitRuntimeCall(
1793 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
1794 : OMPRTL__kmpc_reduce),
1795 Args);
1796
1797 // 5. Build switch(res)
1798 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
1799 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
1800
1801 // 6. Build case 1:
1802 // ...
1803 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
1804 // ...
1805 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
1806 // break;
1807 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
1808 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
1809 CGF.EmitBlock(Case1BB);
1810
1811 {
1812 CodeGenFunction::RunCleanupsScope Scope(CGF);
1813 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
1814 llvm::Value *EndArgs[] = {
1815 IdentTLoc, // ident_t *<loc>
1816 ThreadId, // i32 <gtid>
1817 Lock // kmp_critical_name *&<lock>
1818 };
1819 CGF.EHStack.pushCleanup<CallEndCleanup>(
1820 NormalAndEHCleanup,
1821 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
1822 : OMPRTL__kmpc_end_reduce),
1823 llvm::makeArrayRef(EndArgs));
1824 for (auto *E : ReductionOps) {
1825 CGF.EmitIgnoredExpr(E);
1826 }
1827 }
1828
1829 CGF.EmitBranch(DefaultBB);
1830
1831 // 7. Build case 2:
1832 // ...
1833 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
1834 // ...
1835 // break;
1836 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
1837 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
1838 CGF.EmitBlock(Case2BB);
1839
1840 {
1841 CodeGenFunction::RunCleanupsScope Scope(CGF);
1842 auto I = LHSExprs.begin();
1843 for (auto *E : ReductionOps) {
1844 const Expr *XExpr = nullptr;
1845 const Expr *EExpr = nullptr;
1846 const Expr *UpExpr = nullptr;
1847 BinaryOperatorKind BO = BO_Comma;
1848 // Try to emit update expression as a simple atomic.
1849 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) {
1850 // If this is a conditional operator, analyze it's condition for
1851 // min/max reduction operator.
1852 E = ACO->getCond();
1853 }
1854 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
1855 if (BO->getOpcode() == BO_Assign) {
1856 XExpr = BO->getLHS();
1857 UpExpr = BO->getRHS();
1858 }
1859 }
1860 // Analyze RHS part of the whole expression.
1861 if (UpExpr) {
1862 if (auto *BORHS =
1863 dyn_cast<BinaryOperator>(UpExpr->IgnoreParenImpCasts())) {
1864 EExpr = BORHS->getRHS();
1865 BO = BORHS->getOpcode();
1866 }
1867 }
1868 if (XExpr) {
1869 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
1870 LValue X = CGF.EmitLValue(XExpr);
1871 RValue E;
1872 if (EExpr)
1873 E = CGF.EmitAnyExpr(EExpr);
1874 CGF.EmitOMPAtomicSimpleUpdateExpr(
1875 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
1876 [&CGF, UpExpr, VD](RValue XRValue) {
1877 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
1878 PrivateScope.addPrivate(
1879 VD, [&CGF, VD, XRValue]() -> llvm::Value *{
1880 auto *LHSTemp = CGF.CreateMemTemp(VD->getType());
1881 CGF.EmitStoreThroughLValue(
1882 XRValue,
1883 CGF.MakeNaturalAlignAddrLValue(LHSTemp, VD->getType()));
1884 return LHSTemp;
1885 });
1886 (void)PrivateScope.Privatize();
1887 return CGF.EmitAnyExpr(UpExpr);
1888 });
1889 } else {
1890 // Emit as a critical region.
1891 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
1892 CGF.EmitIgnoredExpr(E);
1893 }, Loc);
1894 }
1895 ++I;
1896 }
1897 }
1898
1899 CGF.EmitBranch(DefaultBB);
1900 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
1901}
1902
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001903void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
1904 const RegionCodeGenTy &CodeGen) {
1905 InlinedOpenMPRegionRAII Region(CGF, CodeGen);
1906 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001907}
1908