File: | build/source/clang/lib/CodeGen/CGOpenMPRuntime.cpp |
Warning: | line 2215, column 3 Address of stack memory associated with local variable 'Action' is still referred to by a temporary object on the stack upon returning to the caller. This will be a dangling reference |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This provides a class for OpenMP runtime code generation. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "CGOpenMPRuntime.h" | |||
14 | #include "CGCXXABI.h" | |||
15 | #include "CGCleanup.h" | |||
16 | #include "CGRecordLayout.h" | |||
17 | #include "CodeGenFunction.h" | |||
18 | #include "TargetInfo.h" | |||
19 | #include "clang/AST/APValue.h" | |||
20 | #include "clang/AST/Attr.h" | |||
21 | #include "clang/AST/Decl.h" | |||
22 | #include "clang/AST/OpenMPClause.h" | |||
23 | #include "clang/AST/StmtOpenMP.h" | |||
24 | #include "clang/AST/StmtVisitor.h" | |||
25 | #include "clang/Basic/BitmaskEnum.h" | |||
26 | #include "clang/Basic/FileManager.h" | |||
27 | #include "clang/Basic/OpenMPKinds.h" | |||
28 | #include "clang/Basic/SourceManager.h" | |||
29 | #include "clang/CodeGen/ConstantInitBuilder.h" | |||
30 | #include "llvm/ADT/ArrayRef.h" | |||
31 | #include "llvm/ADT/SetOperations.h" | |||
32 | #include "llvm/ADT/SmallBitVector.h" | |||
33 | #include "llvm/ADT/StringExtras.h" | |||
34 | #include "llvm/Bitcode/BitcodeReader.h" | |||
35 | #include "llvm/IR/Constants.h" | |||
36 | #include "llvm/IR/DerivedTypes.h" | |||
37 | #include "llvm/IR/GlobalValue.h" | |||
38 | #include "llvm/IR/InstrTypes.h" | |||
39 | #include "llvm/IR/Value.h" | |||
40 | #include "llvm/Support/AtomicOrdering.h" | |||
41 | #include "llvm/Support/Format.h" | |||
42 | #include "llvm/Support/raw_ostream.h" | |||
43 | #include <cassert> | |||
44 | #include <numeric> | |||
45 | #include <optional> | |||
46 | ||||
47 | using namespace clang; | |||
48 | using namespace CodeGen; | |||
49 | using namespace llvm::omp; | |||
50 | ||||
51 | namespace { | |||
52 | /// Base class for handling code generation inside OpenMP regions. | |||
53 | class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo { | |||
54 | public: | |||
55 | /// Kinds of OpenMP regions used in codegen. | |||
56 | enum CGOpenMPRegionKind { | |||
57 | /// Region with outlined function for standalone 'parallel' | |||
58 | /// directive. | |||
59 | ParallelOutlinedRegion, | |||
60 | /// Region with outlined function for standalone 'task' directive. | |||
61 | TaskOutlinedRegion, | |||
62 | /// Region for constructs that do not require function outlining, | |||
63 | /// like 'for', 'sections', 'atomic' etc. directives. | |||
64 | InlinedRegion, | |||
65 | /// Region with outlined function for standalone 'target' directive. | |||
66 | TargetRegion, | |||
67 | }; | |||
68 | ||||
69 | CGOpenMPRegionInfo(const CapturedStmt &CS, | |||
70 | const CGOpenMPRegionKind RegionKind, | |||
71 | const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind, | |||
72 | bool HasCancel) | |||
73 | : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind), | |||
74 | CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {} | |||
75 | ||||
76 | CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind, | |||
77 | const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind, | |||
78 | bool HasCancel) | |||
79 | : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen), | |||
80 | Kind(Kind), HasCancel(HasCancel) {} | |||
81 | ||||
82 | /// Get a variable or parameter for storing global thread id | |||
83 | /// inside OpenMP construct. | |||
84 | virtual const VarDecl *getThreadIDVariable() const = 0; | |||
85 | ||||
86 | /// Emit the captured statement body. | |||
87 | void EmitBody(CodeGenFunction &CGF, const Stmt *S) override; | |||
88 | ||||
89 | /// Get an LValue for the current ThreadID variable. | |||
90 | /// \return LValue for thread id variable. This LValue always has type int32*. | |||
91 | virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF); | |||
92 | ||||
93 | virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {} | |||
94 | ||||
95 | CGOpenMPRegionKind getRegionKind() const { return RegionKind; } | |||
96 | ||||
97 | OpenMPDirectiveKind getDirectiveKind() const { return Kind; } | |||
98 | ||||
99 | bool hasCancel() const { return HasCancel; } | |||
100 | ||||
101 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
102 | return Info->getKind() == CR_OpenMP; | |||
103 | } | |||
104 | ||||
105 | ~CGOpenMPRegionInfo() override = default; | |||
106 | ||||
107 | protected: | |||
108 | CGOpenMPRegionKind RegionKind; | |||
109 | RegionCodeGenTy CodeGen; | |||
110 | OpenMPDirectiveKind Kind; | |||
111 | bool HasCancel; | |||
112 | }; | |||
113 | ||||
114 | /// API for captured statement code generation in OpenMP constructs. | |||
115 | class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo { | |||
116 | public: | |||
117 | CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar, | |||
118 | const RegionCodeGenTy &CodeGen, | |||
119 | OpenMPDirectiveKind Kind, bool HasCancel, | |||
120 | StringRef HelperName) | |||
121 | : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind, | |||
122 | HasCancel), | |||
123 | ThreadIDVar(ThreadIDVar), HelperName(HelperName) { | |||
124 | assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.")(static_cast <bool> (ThreadIDVar != nullptr && "No ThreadID in OpenMP region." ) ? void (0) : __assert_fail ("ThreadIDVar != nullptr && \"No ThreadID in OpenMP region.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 124, __extension__ __PRETTY_FUNCTION__)); | |||
125 | } | |||
126 | ||||
127 | /// Get a variable or parameter for storing global thread id | |||
128 | /// inside OpenMP construct. | |||
129 | const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; } | |||
130 | ||||
131 | /// Get the name of the capture helper. | |||
132 | StringRef getHelperName() const override { return HelperName; } | |||
133 | ||||
134 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
135 | return CGOpenMPRegionInfo::classof(Info) && | |||
136 | cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == | |||
137 | ParallelOutlinedRegion; | |||
138 | } | |||
139 | ||||
140 | private: | |||
141 | /// A variable or parameter storing global thread id for OpenMP | |||
142 | /// constructs. | |||
143 | const VarDecl *ThreadIDVar; | |||
144 | StringRef HelperName; | |||
145 | }; | |||
146 | ||||
147 | /// API for captured statement code generation in OpenMP constructs. | |||
148 | class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo { | |||
149 | public: | |||
150 | class UntiedTaskActionTy final : public PrePostActionTy { | |||
151 | bool Untied; | |||
152 | const VarDecl *PartIDVar; | |||
153 | const RegionCodeGenTy UntiedCodeGen; | |||
154 | llvm::SwitchInst *UntiedSwitch = nullptr; | |||
155 | ||||
156 | public: | |||
157 | UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar, | |||
158 | const RegionCodeGenTy &UntiedCodeGen) | |||
159 | : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {} | |||
160 | void Enter(CodeGenFunction &CGF) override { | |||
161 | if (Untied) { | |||
162 | // Emit task switching point. | |||
163 | LValue PartIdLVal = CGF.EmitLoadOfPointerLValue( | |||
164 | CGF.GetAddrOfLocalVar(PartIDVar), | |||
165 | PartIDVar->getType()->castAs<PointerType>()); | |||
166 | llvm::Value *Res = | |||
167 | CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation()); | |||
168 | llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done."); | |||
169 | UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB); | |||
170 | CGF.EmitBlock(DoneBB); | |||
171 | CGF.EmitBranchThroughCleanup(CGF.ReturnBlock); | |||
172 | CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp.")); | |||
173 | UntiedSwitch->addCase(CGF.Builder.getInt32(0), | |||
174 | CGF.Builder.GetInsertBlock()); | |||
175 | emitUntiedSwitch(CGF); | |||
176 | } | |||
177 | } | |||
178 | void emitUntiedSwitch(CodeGenFunction &CGF) const { | |||
179 | if (Untied) { | |||
180 | LValue PartIdLVal = CGF.EmitLoadOfPointerLValue( | |||
181 | CGF.GetAddrOfLocalVar(PartIDVar), | |||
182 | PartIDVar->getType()->castAs<PointerType>()); | |||
183 | CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()), | |||
184 | PartIdLVal); | |||
185 | UntiedCodeGen(CGF); | |||
186 | CodeGenFunction::JumpDest CurPoint = | |||
187 | CGF.getJumpDestInCurrentScope(".untied.next."); | |||
188 | CGF.EmitBranch(CGF.ReturnBlock.getBlock()); | |||
189 | CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp.")); | |||
190 | UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()), | |||
191 | CGF.Builder.GetInsertBlock()); | |||
192 | CGF.EmitBranchThroughCleanup(CurPoint); | |||
193 | CGF.EmitBlock(CurPoint.getBlock()); | |||
194 | } | |||
195 | } | |||
196 | unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); } | |||
197 | }; | |||
198 | CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS, | |||
199 | const VarDecl *ThreadIDVar, | |||
200 | const RegionCodeGenTy &CodeGen, | |||
201 | OpenMPDirectiveKind Kind, bool HasCancel, | |||
202 | const UntiedTaskActionTy &Action) | |||
203 | : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel), | |||
204 | ThreadIDVar(ThreadIDVar), Action(Action) { | |||
205 | assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.")(static_cast <bool> (ThreadIDVar != nullptr && "No ThreadID in OpenMP region." ) ? void (0) : __assert_fail ("ThreadIDVar != nullptr && \"No ThreadID in OpenMP region.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 205, __extension__ __PRETTY_FUNCTION__)); | |||
206 | } | |||
207 | ||||
208 | /// Get a variable or parameter for storing global thread id | |||
209 | /// inside OpenMP construct. | |||
210 | const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; } | |||
211 | ||||
212 | /// Get an LValue for the current ThreadID variable. | |||
213 | LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override; | |||
214 | ||||
215 | /// Get the name of the capture helper. | |||
216 | StringRef getHelperName() const override { return ".omp_outlined."; } | |||
217 | ||||
218 | void emitUntiedSwitch(CodeGenFunction &CGF) override { | |||
219 | Action.emitUntiedSwitch(CGF); | |||
220 | } | |||
221 | ||||
222 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
223 | return CGOpenMPRegionInfo::classof(Info) && | |||
224 | cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == | |||
225 | TaskOutlinedRegion; | |||
226 | } | |||
227 | ||||
228 | private: | |||
229 | /// A variable or parameter storing global thread id for OpenMP | |||
230 | /// constructs. | |||
231 | const VarDecl *ThreadIDVar; | |||
232 | /// Action for emitting code for untied tasks. | |||
233 | const UntiedTaskActionTy &Action; | |||
234 | }; | |||
235 | ||||
236 | /// API for inlined captured statement code generation in OpenMP | |||
237 | /// constructs. | |||
238 | class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo { | |||
239 | public: | |||
240 | CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI, | |||
241 | const RegionCodeGenTy &CodeGen, | |||
242 | OpenMPDirectiveKind Kind, bool HasCancel) | |||
243 | : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel), | |||
244 | OldCSI(OldCSI), | |||
245 | OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {} | |||
246 | ||||
247 | // Retrieve the value of the context parameter. | |||
248 | llvm::Value *getContextValue() const override { | |||
249 | if (OuterRegionInfo) | |||
250 | return OuterRegionInfo->getContextValue(); | |||
251 | llvm_unreachable("No context value for inlined OpenMP region")::llvm::llvm_unreachable_internal("No context value for inlined OpenMP region" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 251); | |||
252 | } | |||
253 | ||||
254 | void setContextValue(llvm::Value *V) override { | |||
255 | if (OuterRegionInfo) { | |||
256 | OuterRegionInfo->setContextValue(V); | |||
257 | return; | |||
258 | } | |||
259 | llvm_unreachable("No context value for inlined OpenMP region")::llvm::llvm_unreachable_internal("No context value for inlined OpenMP region" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 259); | |||
260 | } | |||
261 | ||||
262 | /// Lookup the captured field decl for a variable. | |||
263 | const FieldDecl *lookup(const VarDecl *VD) const override { | |||
264 | if (OuterRegionInfo) | |||
265 | return OuterRegionInfo->lookup(VD); | |||
266 | // If there is no outer outlined region,no need to lookup in a list of | |||
267 | // captured variables, we can use the original one. | |||
268 | return nullptr; | |||
269 | } | |||
270 | ||||
271 | FieldDecl *getThisFieldDecl() const override { | |||
272 | if (OuterRegionInfo) | |||
273 | return OuterRegionInfo->getThisFieldDecl(); | |||
274 | return nullptr; | |||
275 | } | |||
276 | ||||
277 | /// Get a variable or parameter for storing global thread id | |||
278 | /// inside OpenMP construct. | |||
279 | const VarDecl *getThreadIDVariable() const override { | |||
280 | if (OuterRegionInfo) | |||
281 | return OuterRegionInfo->getThreadIDVariable(); | |||
282 | return nullptr; | |||
283 | } | |||
284 | ||||
285 | /// Get an LValue for the current ThreadID variable. | |||
286 | LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override { | |||
287 | if (OuterRegionInfo) | |||
288 | return OuterRegionInfo->getThreadIDVariableLValue(CGF); | |||
289 | llvm_unreachable("No LValue for inlined OpenMP construct")::llvm::llvm_unreachable_internal("No LValue for inlined OpenMP construct" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 289); | |||
290 | } | |||
291 | ||||
292 | /// Get the name of the capture helper. | |||
293 | StringRef getHelperName() const override { | |||
294 | if (auto *OuterRegionInfo = getOldCSI()) | |||
295 | return OuterRegionInfo->getHelperName(); | |||
296 | llvm_unreachable("No helper name for inlined OpenMP construct")::llvm::llvm_unreachable_internal("No helper name for inlined OpenMP construct" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 296); | |||
297 | } | |||
298 | ||||
299 | void emitUntiedSwitch(CodeGenFunction &CGF) override { | |||
300 | if (OuterRegionInfo) | |||
301 | OuterRegionInfo->emitUntiedSwitch(CGF); | |||
302 | } | |||
303 | ||||
304 | CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; } | |||
305 | ||||
306 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
307 | return CGOpenMPRegionInfo::classof(Info) && | |||
308 | cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion; | |||
309 | } | |||
310 | ||||
311 | ~CGOpenMPInlinedRegionInfo() override = default; | |||
312 | ||||
313 | private: | |||
314 | /// CodeGen info about outer OpenMP region. | |||
315 | CodeGenFunction::CGCapturedStmtInfo *OldCSI; | |||
316 | CGOpenMPRegionInfo *OuterRegionInfo; | |||
317 | }; | |||
318 | ||||
319 | /// API for captured statement code generation in OpenMP target | |||
320 | /// constructs. For this captures, implicit parameters are used instead of the | |||
321 | /// captured fields. The name of the target region has to be unique in a given | |||
322 | /// application so it is provided by the client, because only the client has | |||
323 | /// the information to generate that. | |||
324 | class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo { | |||
325 | public: | |||
326 | CGOpenMPTargetRegionInfo(const CapturedStmt &CS, | |||
327 | const RegionCodeGenTy &CodeGen, StringRef HelperName) | |||
328 | : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target, | |||
329 | /*HasCancel=*/false), | |||
330 | HelperName(HelperName) {} | |||
331 | ||||
332 | /// This is unused for target regions because each starts executing | |||
333 | /// with a single thread. | |||
334 | const VarDecl *getThreadIDVariable() const override { return nullptr; } | |||
335 | ||||
336 | /// Get the name of the capture helper. | |||
337 | StringRef getHelperName() const override { return HelperName; } | |||
338 | ||||
339 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
340 | return CGOpenMPRegionInfo::classof(Info) && | |||
341 | cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion; | |||
342 | } | |||
343 | ||||
344 | private: | |||
345 | StringRef HelperName; | |||
346 | }; | |||
347 | ||||
348 | static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) { | |||
349 | llvm_unreachable("No codegen for expressions")::llvm::llvm_unreachable_internal("No codegen for expressions" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 349); | |||
350 | } | |||
351 | /// API for generation of expressions captured in a innermost OpenMP | |||
352 | /// region. | |||
353 | class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo { | |||
354 | public: | |||
355 | CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS) | |||
356 | : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen, | |||
357 | OMPD_unknown, | |||
358 | /*HasCancel=*/false), | |||
359 | PrivScope(CGF) { | |||
360 | // Make sure the globals captured in the provided statement are local by | |||
361 | // using the privatization logic. We assume the same variable is not | |||
362 | // captured more than once. | |||
363 | for (const auto &C : CS.captures()) { | |||
364 | if (!C.capturesVariable() && !C.capturesVariableByCopy()) | |||
365 | continue; | |||
366 | ||||
367 | const VarDecl *VD = C.getCapturedVar(); | |||
368 | if (VD->isLocalVarDeclOrParm()) | |||
369 | continue; | |||
370 | ||||
371 | DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD), | |||
372 | /*RefersToEnclosingVariableOrCapture=*/false, | |||
373 | VD->getType().getNonReferenceType(), VK_LValue, | |||
374 | C.getLocation()); | |||
375 | PrivScope.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress(CGF)); | |||
376 | } | |||
377 | (void)PrivScope.Privatize(); | |||
378 | } | |||
379 | ||||
380 | /// Lookup the captured field decl for a variable. | |||
381 | const FieldDecl *lookup(const VarDecl *VD) const override { | |||
382 | if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD)) | |||
383 | return FD; | |||
384 | return nullptr; | |||
385 | } | |||
386 | ||||
387 | /// Emit the captured statement body. | |||
388 | void EmitBody(CodeGenFunction &CGF, const Stmt *S) override { | |||
389 | llvm_unreachable("No body for expressions")::llvm::llvm_unreachable_internal("No body for expressions", "clang/lib/CodeGen/CGOpenMPRuntime.cpp" , 389); | |||
390 | } | |||
391 | ||||
392 | /// Get a variable or parameter for storing global thread id | |||
393 | /// inside OpenMP construct. | |||
394 | const VarDecl *getThreadIDVariable() const override { | |||
395 | llvm_unreachable("No thread id for expressions")::llvm::llvm_unreachable_internal("No thread id for expressions" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 395); | |||
396 | } | |||
397 | ||||
398 | /// Get the name of the capture helper. | |||
399 | StringRef getHelperName() const override { | |||
400 | llvm_unreachable("No helper name for expressions")::llvm::llvm_unreachable_internal("No helper name for expressions" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 400); | |||
401 | } | |||
402 | ||||
403 | static bool classof(const CGCapturedStmtInfo *Info) { return false; } | |||
404 | ||||
405 | private: | |||
406 | /// Private scope to capture global variables. | |||
407 | CodeGenFunction::OMPPrivateScope PrivScope; | |||
408 | }; | |||
409 | ||||
410 | /// RAII for emitting code of OpenMP constructs. | |||
411 | class InlinedOpenMPRegionRAII { | |||
412 | CodeGenFunction &CGF; | |||
413 | llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields; | |||
414 | FieldDecl *LambdaThisCaptureField = nullptr; | |||
415 | const CodeGen::CGBlockInfo *BlockInfo = nullptr; | |||
416 | bool NoInheritance = false; | |||
417 | ||||
418 | public: | |||
419 | /// Constructs region for combined constructs. | |||
420 | /// \param CodeGen Code generation sequence for combined directives. Includes | |||
421 | /// a list of functions used for code generation of implicitly inlined | |||
422 | /// regions. | |||
423 | InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen, | |||
424 | OpenMPDirectiveKind Kind, bool HasCancel, | |||
425 | bool NoInheritance = true) | |||
426 | : CGF(CGF), NoInheritance(NoInheritance) { | |||
427 | // Start emission for the construct. | |||
428 | CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo( | |||
429 | CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel); | |||
430 | if (NoInheritance) { | |||
431 | std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields); | |||
432 | LambdaThisCaptureField = CGF.LambdaThisCaptureField; | |||
433 | CGF.LambdaThisCaptureField = nullptr; | |||
434 | BlockInfo = CGF.BlockInfo; | |||
435 | CGF.BlockInfo = nullptr; | |||
436 | } | |||
437 | } | |||
438 | ||||
439 | ~InlinedOpenMPRegionRAII() { | |||
440 | // Restore original CapturedStmtInfo only if we're done with code emission. | |||
441 | auto *OldCSI = | |||
442 | cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI(); | |||
443 | delete CGF.CapturedStmtInfo; | |||
444 | CGF.CapturedStmtInfo = OldCSI; | |||
445 | if (NoInheritance) { | |||
446 | std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields); | |||
447 | CGF.LambdaThisCaptureField = LambdaThisCaptureField; | |||
448 | CGF.BlockInfo = BlockInfo; | |||
449 | } | |||
450 | } | |||
451 | }; | |||
452 | ||||
453 | /// Values for bit flags used in the ident_t to describe the fields. | |||
454 | /// All enumeric elements are named and described in accordance with the code | |||
455 | /// from https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h | |||
456 | enum OpenMPLocationFlags : unsigned { | |||
457 | /// Use trampoline for internal microtask. | |||
458 | OMP_IDENT_IMD = 0x01, | |||
459 | /// Use c-style ident structure. | |||
460 | OMP_IDENT_KMPC = 0x02, | |||
461 | /// Atomic reduction option for kmpc_reduce. | |||
462 | OMP_ATOMIC_REDUCE = 0x10, | |||
463 | /// Explicit 'barrier' directive. | |||
464 | OMP_IDENT_BARRIER_EXPL = 0x20, | |||
465 | /// Implicit barrier in code. | |||
466 | OMP_IDENT_BARRIER_IMPL = 0x40, | |||
467 | /// Implicit barrier in 'for' directive. | |||
468 | OMP_IDENT_BARRIER_IMPL_FOR = 0x40, | |||
469 | /// Implicit barrier in 'sections' directive. | |||
470 | OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0, | |||
471 | /// Implicit barrier in 'single' directive. | |||
472 | OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140, | |||
473 | /// Call of __kmp_for_static_init for static loop. | |||
474 | OMP_IDENT_WORK_LOOP = 0x200, | |||
475 | /// Call of __kmp_for_static_init for sections. | |||
476 | OMP_IDENT_WORK_SECTIONS = 0x400, | |||
477 | /// Call of __kmp_for_static_init for distribute. | |||
478 | OMP_IDENT_WORK_DISTRIBUTE = 0x800, | |||
479 | LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)LLVM_BITMASK_LARGEST_ENUMERATOR = OMP_IDENT_WORK_DISTRIBUTE | |||
480 | }; | |||
481 | ||||
482 | namespace { | |||
483 | LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE()using ::llvm::BitmaskEnumDetail::operator~; using ::llvm::BitmaskEnumDetail ::operator|; using ::llvm::BitmaskEnumDetail::operator&; using ::llvm::BitmaskEnumDetail::operator^; using ::llvm::BitmaskEnumDetail ::operator|=; using ::llvm::BitmaskEnumDetail::operator&= ; using ::llvm::BitmaskEnumDetail::operator^=; | |||
484 | /// Values for bit flags for marking which requires clauses have been used. | |||
485 | enum OpenMPOffloadingRequiresDirFlags : int64_t { | |||
486 | /// flag undefined. | |||
487 | OMP_REQ_UNDEFINED = 0x000, | |||
488 | /// no requires clause present. | |||
489 | OMP_REQ_NONE = 0x001, | |||
490 | /// reverse_offload clause. | |||
491 | OMP_REQ_REVERSE_OFFLOAD = 0x002, | |||
492 | /// unified_address clause. | |||
493 | OMP_REQ_UNIFIED_ADDRESS = 0x004, | |||
494 | /// unified_shared_memory clause. | |||
495 | OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008, | |||
496 | /// dynamic_allocators clause. | |||
497 | OMP_REQ_DYNAMIC_ALLOCATORS = 0x010, | |||
498 | LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)LLVM_BITMASK_LARGEST_ENUMERATOR = OMP_REQ_DYNAMIC_ALLOCATORS | |||
499 | }; | |||
500 | ||||
501 | } // anonymous namespace | |||
502 | ||||
503 | /// Describes ident structure that describes a source location. | |||
504 | /// All descriptions are taken from | |||
505 | /// https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h | |||
506 | /// Original structure: | |||
507 | /// typedef struct ident { | |||
508 | /// kmp_int32 reserved_1; /**< might be used in Fortran; | |||
509 | /// see above */ | |||
510 | /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags; | |||
511 | /// KMP_IDENT_KMPC identifies this union | |||
512 | /// member */ | |||
513 | /// kmp_int32 reserved_2; /**< not really used in Fortran any more; | |||
514 | /// see above */ | |||
515 | ///#if USE_ITT_BUILD | |||
516 | /// /* but currently used for storing | |||
517 | /// region-specific ITT */ | |||
518 | /// /* contextual information. */ | |||
519 | ///#endif /* USE_ITT_BUILD */ | |||
520 | /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for | |||
521 | /// C++ */ | |||
522 | /// char const *psource; /**< String describing the source location. | |||
523 | /// The string is composed of semi-colon separated | |||
524 | // fields which describe the source file, | |||
525 | /// the function and a pair of line numbers that | |||
526 | /// delimit the construct. | |||
527 | /// */ | |||
528 | /// } ident_t; | |||
529 | enum IdentFieldIndex { | |||
530 | /// might be used in Fortran | |||
531 | IdentField_Reserved_1, | |||
532 | /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member. | |||
533 | IdentField_Flags, | |||
534 | /// Not really used in Fortran any more | |||
535 | IdentField_Reserved_2, | |||
536 | /// Source[4] in Fortran, do not use for C++ | |||
537 | IdentField_Reserved_3, | |||
538 | /// String describing the source location. The string is composed of | |||
539 | /// semi-colon separated fields which describe the source file, the function | |||
540 | /// and a pair of line numbers that delimit the construct. | |||
541 | IdentField_PSource | |||
542 | }; | |||
543 | ||||
544 | /// Schedule types for 'omp for' loops (these enumerators are taken from | |||
545 | /// the enum sched_type in kmp.h). | |||
546 | enum OpenMPSchedType { | |||
547 | /// Lower bound for default (unordered) versions. | |||
548 | OMP_sch_lower = 32, | |||
549 | OMP_sch_static_chunked = 33, | |||
550 | OMP_sch_static = 34, | |||
551 | OMP_sch_dynamic_chunked = 35, | |||
552 | OMP_sch_guided_chunked = 36, | |||
553 | OMP_sch_runtime = 37, | |||
554 | OMP_sch_auto = 38, | |||
555 | /// static with chunk adjustment (e.g., simd) | |||
556 | OMP_sch_static_balanced_chunked = 45, | |||
557 | /// Lower bound for 'ordered' versions. | |||
558 | OMP_ord_lower = 64, | |||
559 | OMP_ord_static_chunked = 65, | |||
560 | OMP_ord_static = 66, | |||
561 | OMP_ord_dynamic_chunked = 67, | |||
562 | OMP_ord_guided_chunked = 68, | |||
563 | OMP_ord_runtime = 69, | |||
564 | OMP_ord_auto = 70, | |||
565 | OMP_sch_default = OMP_sch_static, | |||
566 | /// dist_schedule types | |||
567 | OMP_dist_sch_static_chunked = 91, | |||
568 | OMP_dist_sch_static = 92, | |||
569 | /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers. | |||
570 | /// Set if the monotonic schedule modifier was present. | |||
571 | OMP_sch_modifier_monotonic = (1 << 29), | |||
572 | /// Set if the nonmonotonic schedule modifier was present. | |||
573 | OMP_sch_modifier_nonmonotonic = (1 << 30), | |||
574 | }; | |||
575 | ||||
576 | /// A basic class for pre|post-action for advanced codegen sequence for OpenMP | |||
577 | /// region. | |||
578 | class CleanupTy final : public EHScopeStack::Cleanup { | |||
579 | PrePostActionTy *Action; | |||
580 | ||||
581 | public: | |||
582 | explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {} | |||
583 | void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { | |||
584 | if (!CGF.HaveInsertPoint()) | |||
585 | return; | |||
586 | Action->Exit(CGF); | |||
587 | } | |||
588 | }; | |||
589 | ||||
590 | } // anonymous namespace | |||
591 | ||||
592 | void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const { | |||
593 | CodeGenFunction::RunCleanupsScope Scope(CGF); | |||
594 | if (PrePostAction) { | |||
595 | CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction); | |||
596 | Callback(CodeGen, CGF, *PrePostAction); | |||
597 | } else { | |||
598 | PrePostActionTy Action; | |||
599 | Callback(CodeGen, CGF, Action); | |||
600 | } | |||
601 | } | |||
602 | ||||
603 | /// Check if the combiner is a call to UDR combiner and if it is so return the | |||
604 | /// UDR decl used for reduction. | |||
605 | static const OMPDeclareReductionDecl * | |||
606 | getReductionInit(const Expr *ReductionOp) { | |||
607 | if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) | |||
608 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) | |||
609 | if (const auto *DRE = | |||
610 | dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) | |||
611 | if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) | |||
612 | return DRD; | |||
613 | return nullptr; | |||
614 | } | |||
615 | ||||
616 | static void emitInitWithReductionInitializer(CodeGenFunction &CGF, | |||
617 | const OMPDeclareReductionDecl *DRD, | |||
618 | const Expr *InitOp, | |||
619 | Address Private, Address Original, | |||
620 | QualType Ty) { | |||
621 | if (DRD->getInitializer()) { | |||
622 | std::pair<llvm::Function *, llvm::Function *> Reduction = | |||
623 | CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); | |||
624 | const auto *CE = cast<CallExpr>(InitOp); | |||
625 | const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee()); | |||
626 | const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); | |||
627 | const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); | |||
628 | const auto *LHSDRE = | |||
629 | cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr()); | |||
630 | const auto *RHSDRE = | |||
631 | cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr()); | |||
632 | CodeGenFunction::OMPPrivateScope PrivateScope(CGF); | |||
633 | PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()), Private); | |||
634 | PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()), Original); | |||
635 | (void)PrivateScope.Privatize(); | |||
636 | RValue Func = RValue::get(Reduction.second); | |||
637 | CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); | |||
638 | CGF.EmitIgnoredExpr(InitOp); | |||
639 | } else { | |||
640 | llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty); | |||
641 | std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"}); | |||
642 | auto *GV = new llvm::GlobalVariable( | |||
643 | CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true, | |||
644 | llvm::GlobalValue::PrivateLinkage, Init, Name); | |||
645 | LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty); | |||
646 | RValue InitRVal; | |||
647 | switch (CGF.getEvaluationKind(Ty)) { | |||
648 | case TEK_Scalar: | |||
649 | InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation()); | |||
650 | break; | |||
651 | case TEK_Complex: | |||
652 | InitRVal = | |||
653 | RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation())); | |||
654 | break; | |||
655 | case TEK_Aggregate: { | |||
656 | OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_LValue); | |||
657 | CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, LV); | |||
658 | CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(), | |||
659 | /*IsInitializer=*/false); | |||
660 | return; | |||
661 | } | |||
662 | } | |||
663 | OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_PRValue); | |||
664 | CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal); | |||
665 | CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(), | |||
666 | /*IsInitializer=*/false); | |||
667 | } | |||
668 | } | |||
669 | ||||
670 | /// Emit initialization of arrays of complex types. | |||
671 | /// \param DestAddr Address of the array. | |||
672 | /// \param Type Type of array. | |||
673 | /// \param Init Initial expression of array. | |||
674 | /// \param SrcAddr Address of the original array. | |||
675 | static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr, | |||
676 | QualType Type, bool EmitDeclareReductionInit, | |||
677 | const Expr *Init, | |||
678 | const OMPDeclareReductionDecl *DRD, | |||
679 | Address SrcAddr = Address::invalid()) { | |||
680 | // Perform element-by-element initialization. | |||
681 | QualType ElementTy; | |||
682 | ||||
683 | // Drill down to the base element type on both arrays. | |||
684 | const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe(); | |||
685 | llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr); | |||
686 | if (DRD) | |||
687 | SrcAddr = | |||
688 | CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); | |||
689 | ||||
690 | llvm::Value *SrcBegin = nullptr; | |||
691 | if (DRD) | |||
692 | SrcBegin = SrcAddr.getPointer(); | |||
693 | llvm::Value *DestBegin = DestAddr.getPointer(); | |||
694 | // Cast from pointer to array type to pointer to single element. | |||
695 | llvm::Value *DestEnd = | |||
696 | CGF.Builder.CreateGEP(DestAddr.getElementType(), DestBegin, NumElements); | |||
697 | // The basic structure here is a while-do loop. | |||
698 | llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body"); | |||
699 | llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done"); | |||
700 | llvm::Value *IsEmpty = | |||
701 | CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty"); | |||
702 | CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); | |||
703 | ||||
704 | // Enter the loop body, making that address the current address. | |||
705 | llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); | |||
706 | CGF.EmitBlock(BodyBB); | |||
707 | ||||
708 | CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); | |||
709 | ||||
710 | llvm::PHINode *SrcElementPHI = nullptr; | |||
711 | Address SrcElementCurrent = Address::invalid(); | |||
712 | if (DRD) { | |||
713 | SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2, | |||
714 | "omp.arraycpy.srcElementPast"); | |||
715 | SrcElementPHI->addIncoming(SrcBegin, EntryBB); | |||
716 | SrcElementCurrent = | |||
717 | Address(SrcElementPHI, SrcAddr.getElementType(), | |||
718 | SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); | |||
719 | } | |||
720 | llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI( | |||
721 | DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); | |||
722 | DestElementPHI->addIncoming(DestBegin, EntryBB); | |||
723 | Address DestElementCurrent = | |||
724 | Address(DestElementPHI, DestAddr.getElementType(), | |||
725 | DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); | |||
726 | ||||
727 | // Emit copy. | |||
728 | { | |||
729 | CodeGenFunction::RunCleanupsScope InitScope(CGF); | |||
730 | if (EmitDeclareReductionInit) { | |||
731 | emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent, | |||
732 | SrcElementCurrent, ElementTy); | |||
733 | } else | |||
734 | CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(), | |||
735 | /*IsInitializer=*/false); | |||
736 | } | |||
737 | ||||
738 | if (DRD) { | |||
739 | // Shift the address forward by one element. | |||
740 | llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32( | |||
741 | SrcAddr.getElementType(), SrcElementPHI, /*Idx0=*/1, | |||
742 | "omp.arraycpy.dest.element"); | |||
743 | SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock()); | |||
744 | } | |||
745 | ||||
746 | // Shift the address forward by one element. | |||
747 | llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32( | |||
748 | DestAddr.getElementType(), DestElementPHI, /*Idx0=*/1, | |||
749 | "omp.arraycpy.dest.element"); | |||
750 | // Check whether we've reached the end. | |||
751 | llvm::Value *Done = | |||
752 | CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); | |||
753 | CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); | |||
754 | DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock()); | |||
755 | ||||
756 | // Done. | |||
757 | CGF.EmitBlock(DoneBB, /*IsFinished=*/true); | |||
758 | } | |||
759 | ||||
760 | LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) { | |||
761 | return CGF.EmitOMPSharedLValue(E); | |||
762 | } | |||
763 | ||||
764 | LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF, | |||
765 | const Expr *E) { | |||
766 | if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E)) | |||
767 | return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false); | |||
768 | return LValue(); | |||
769 | } | |||
770 | ||||
771 | void ReductionCodeGen::emitAggregateInitialization( | |||
772 | CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr, | |||
773 | const OMPDeclareReductionDecl *DRD) { | |||
774 | // Emit VarDecl with copy init for arrays. | |||
775 | // Get the address of the original variable captured in current | |||
776 | // captured region. | |||
777 | const auto *PrivateVD = | |||
778 | cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); | |||
779 | bool EmitDeclareReductionInit = | |||
780 | DRD && (DRD->getInitializer() || !PrivateVD->hasInit()); | |||
781 | EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(), | |||
782 | EmitDeclareReductionInit, | |||
783 | EmitDeclareReductionInit ? ClausesData[N].ReductionOp | |||
784 | : PrivateVD->getInit(), | |||
785 | DRD, SharedAddr); | |||
786 | } | |||
787 | ||||
788 | ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds, | |||
789 | ArrayRef<const Expr *> Origs, | |||
790 | ArrayRef<const Expr *> Privates, | |||
791 | ArrayRef<const Expr *> ReductionOps) { | |||
792 | ClausesData.reserve(Shareds.size()); | |||
793 | SharedAddresses.reserve(Shareds.size()); | |||
794 | Sizes.reserve(Shareds.size()); | |||
795 | BaseDecls.reserve(Shareds.size()); | |||
796 | const auto *IOrig = Origs.begin(); | |||
797 | const auto *IPriv = Privates.begin(); | |||
798 | const auto *IRed = ReductionOps.begin(); | |||
799 | for (const Expr *Ref : Shareds) { | |||
800 | ClausesData.emplace_back(Ref, *IOrig, *IPriv, *IRed); | |||
801 | std::advance(IOrig, 1); | |||
802 | std::advance(IPriv, 1); | |||
803 | std::advance(IRed, 1); | |||
804 | } | |||
805 | } | |||
806 | ||||
807 | void ReductionCodeGen::emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N) { | |||
808 | assert(SharedAddresses.size() == N && OrigAddresses.size() == N &&(static_cast <bool> (SharedAddresses.size() == N && OrigAddresses.size() == N && "Number of generated lvalues must be exactly N." ) ? void (0) : __assert_fail ("SharedAddresses.size() == N && OrigAddresses.size() == N && \"Number of generated lvalues must be exactly N.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 809, __extension__ __PRETTY_FUNCTION__)) | |||
809 | "Number of generated lvalues must be exactly N.")(static_cast <bool> (SharedAddresses.size() == N && OrigAddresses.size() == N && "Number of generated lvalues must be exactly N." ) ? void (0) : __assert_fail ("SharedAddresses.size() == N && OrigAddresses.size() == N && \"Number of generated lvalues must be exactly N.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 809, __extension__ __PRETTY_FUNCTION__)); | |||
810 | LValue First = emitSharedLValue(CGF, ClausesData[N].Shared); | |||
811 | LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Shared); | |||
812 | SharedAddresses.emplace_back(First, Second); | |||
813 | if (ClausesData[N].Shared == ClausesData[N].Ref) { | |||
814 | OrigAddresses.emplace_back(First, Second); | |||
815 | } else { | |||
816 | LValue First = emitSharedLValue(CGF, ClausesData[N].Ref); | |||
817 | LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref); | |||
818 | OrigAddresses.emplace_back(First, Second); | |||
819 | } | |||
820 | } | |||
821 | ||||
822 | void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) { | |||
823 | QualType PrivateType = getPrivateType(N); | |||
824 | bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref); | |||
825 | if (!PrivateType->isVariablyModifiedType()) { | |||
826 | Sizes.emplace_back( | |||
827 | CGF.getTypeSize(OrigAddresses[N].first.getType().getNonReferenceType()), | |||
828 | nullptr); | |||
829 | return; | |||
830 | } | |||
831 | llvm::Value *Size; | |||
832 | llvm::Value *SizeInChars; | |||
833 | auto *ElemType = OrigAddresses[N].first.getAddress(CGF).getElementType(); | |||
834 | auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType); | |||
835 | if (AsArraySection) { | |||
836 | Size = CGF.Builder.CreatePtrDiff(ElemType, | |||
837 | OrigAddresses[N].second.getPointer(CGF), | |||
838 | OrigAddresses[N].first.getPointer(CGF)); | |||
839 | Size = CGF.Builder.CreateNUWAdd( | |||
840 | Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1)); | |||
841 | SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf); | |||
842 | } else { | |||
843 | SizeInChars = | |||
844 | CGF.getTypeSize(OrigAddresses[N].first.getType().getNonReferenceType()); | |||
845 | Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf); | |||
846 | } | |||
847 | Sizes.emplace_back(SizeInChars, Size); | |||
848 | CodeGenFunction::OpaqueValueMapping OpaqueMap( | |||
849 | CGF, | |||
850 | cast<OpaqueValueExpr>( | |||
851 | CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()), | |||
852 | RValue::get(Size)); | |||
853 | CGF.EmitVariablyModifiedType(PrivateType); | |||
854 | } | |||
855 | ||||
856 | void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N, | |||
857 | llvm::Value *Size) { | |||
858 | QualType PrivateType = getPrivateType(N); | |||
859 | if (!PrivateType->isVariablyModifiedType()) { | |||
860 | assert(!Size && !Sizes[N].second &&(static_cast <bool> (!Size && !Sizes[N].second && "Size should be nullptr for non-variably modified reduction " "items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 862, __extension__ __PRETTY_FUNCTION__)) | |||
861 | "Size should be nullptr for non-variably modified reduction "(static_cast <bool> (!Size && !Sizes[N].second && "Size should be nullptr for non-variably modified reduction " "items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 862, __extension__ __PRETTY_FUNCTION__)) | |||
862 | "items.")(static_cast <bool> (!Size && !Sizes[N].second && "Size should be nullptr for non-variably modified reduction " "items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 862, __extension__ __PRETTY_FUNCTION__)); | |||
863 | return; | |||
864 | } | |||
865 | CodeGenFunction::OpaqueValueMapping OpaqueMap( | |||
866 | CGF, | |||
867 | cast<OpaqueValueExpr>( | |||
868 | CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()), | |||
869 | RValue::get(Size)); | |||
870 | CGF.EmitVariablyModifiedType(PrivateType); | |||
871 | } | |||
872 | ||||
873 | void ReductionCodeGen::emitInitialization( | |||
874 | CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr, | |||
875 | llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) { | |||
876 | assert(SharedAddresses.size() > N && "No variable was generated")(static_cast <bool> (SharedAddresses.size() > N && "No variable was generated") ? void (0) : __assert_fail ("SharedAddresses.size() > N && \"No variable was generated\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 876, __extension__ __PRETTY_FUNCTION__)); | |||
877 | const auto *PrivateVD = | |||
878 | cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); | |||
879 | const OMPDeclareReductionDecl *DRD = | |||
880 | getReductionInit(ClausesData[N].ReductionOp); | |||
881 | if (CGF.getContext().getAsArrayType(PrivateVD->getType())) { | |||
882 | if (DRD && DRD->getInitializer()) | |||
883 | (void)DefaultInit(CGF); | |||
884 | emitAggregateInitialization(CGF, N, PrivateAddr, SharedAddr, DRD); | |||
885 | } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) { | |||
886 | (void)DefaultInit(CGF); | |||
887 | QualType SharedType = SharedAddresses[N].first.getType(); | |||
888 | emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp, | |||
889 | PrivateAddr, SharedAddr, SharedType); | |||
890 | } else if (!DefaultInit(CGF) && PrivateVD->hasInit() && | |||
891 | !CGF.isTrivialInitializer(PrivateVD->getInit())) { | |||
892 | CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr, | |||
893 | PrivateVD->getType().getQualifiers(), | |||
894 | /*IsInitializer=*/false); | |||
895 | } | |||
896 | } | |||
897 | ||||
898 | bool ReductionCodeGen::needCleanups(unsigned N) { | |||
899 | QualType PrivateType = getPrivateType(N); | |||
900 | QualType::DestructionKind DTorKind = PrivateType.isDestructedType(); | |||
901 | return DTorKind != QualType::DK_none; | |||
902 | } | |||
903 | ||||
904 | void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N, | |||
905 | Address PrivateAddr) { | |||
906 | QualType PrivateType = getPrivateType(N); | |||
907 | QualType::DestructionKind DTorKind = PrivateType.isDestructedType(); | |||
908 | if (needCleanups(N)) { | |||
909 | PrivateAddr = CGF.Builder.CreateElementBitCast( | |||
910 | PrivateAddr, CGF.ConvertTypeForMem(PrivateType)); | |||
911 | CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType); | |||
912 | } | |||
913 | } | |||
914 | ||||
915 | static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, | |||
916 | LValue BaseLV) { | |||
917 | BaseTy = BaseTy.getNonReferenceType(); | |||
918 | while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && | |||
919 | !CGF.getContext().hasSameType(BaseTy, ElTy)) { | |||
920 | if (const auto *PtrTy = BaseTy->getAs<PointerType>()) { | |||
921 | BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(CGF), PtrTy); | |||
922 | } else { | |||
923 | LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(CGF), BaseTy); | |||
924 | BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal); | |||
925 | } | |||
926 | BaseTy = BaseTy->getPointeeType(); | |||
927 | } | |||
928 | return CGF.MakeAddrLValue( | |||
929 | CGF.Builder.CreateElementBitCast(BaseLV.getAddress(CGF), | |||
930 | CGF.ConvertTypeForMem(ElTy)), | |||
931 | BaseLV.getType(), BaseLV.getBaseInfo(), | |||
932 | CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType())); | |||
933 | } | |||
934 | ||||
935 | static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, | |||
936 | Address OriginalBaseAddress, llvm::Value *Addr) { | |||
937 | Address Tmp = Address::invalid(); | |||
938 | Address TopTmp = Address::invalid(); | |||
939 | Address MostTopTmp = Address::invalid(); | |||
940 | BaseTy = BaseTy.getNonReferenceType(); | |||
941 | while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && | |||
942 | !CGF.getContext().hasSameType(BaseTy, ElTy)) { | |||
943 | Tmp = CGF.CreateMemTemp(BaseTy); | |||
944 | if (TopTmp.isValid()) | |||
945 | CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp); | |||
946 | else | |||
947 | MostTopTmp = Tmp; | |||
948 | TopTmp = Tmp; | |||
949 | BaseTy = BaseTy->getPointeeType(); | |||
950 | } | |||
951 | ||||
952 | if (Tmp.isValid()) { | |||
953 | Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
954 | Addr, Tmp.getElementType()); | |||
955 | CGF.Builder.CreateStore(Addr, Tmp); | |||
956 | return MostTopTmp; | |||
957 | } | |||
958 | ||||
959 | Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
960 | Addr, OriginalBaseAddress.getType()); | |||
961 | return OriginalBaseAddress.withPointer(Addr, NotKnownNonNull); | |||
962 | } | |||
963 | ||||
964 | static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) { | |||
965 | const VarDecl *OrigVD = nullptr; | |||
966 | if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) { | |||
967 | const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); | |||
968 | while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) | |||
969 | Base = TempOASE->getBase()->IgnoreParenImpCasts(); | |||
970 | while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) | |||
971 | Base = TempASE->getBase()->IgnoreParenImpCasts(); | |||
972 | DE = cast<DeclRefExpr>(Base); | |||
973 | OrigVD = cast<VarDecl>(DE->getDecl()); | |||
974 | } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) { | |||
975 | const Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); | |||
976 | while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) | |||
977 | Base = TempASE->getBase()->IgnoreParenImpCasts(); | |||
978 | DE = cast<DeclRefExpr>(Base); | |||
979 | OrigVD = cast<VarDecl>(DE->getDecl()); | |||
980 | } | |||
981 | return OrigVD; | |||
982 | } | |||
983 | ||||
984 | Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, | |||
985 | Address PrivateAddr) { | |||
986 | const DeclRefExpr *DE; | |||
987 | if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) { | |||
988 | BaseDecls.emplace_back(OrigVD); | |||
989 | LValue OriginalBaseLValue = CGF.EmitLValue(DE); | |||
990 | LValue BaseLValue = | |||
991 | loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(), | |||
992 | OriginalBaseLValue); | |||
993 | Address SharedAddr = SharedAddresses[N].first.getAddress(CGF); | |||
994 | llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff( | |||
995 | SharedAddr.getElementType(), BaseLValue.getPointer(CGF), | |||
996 | SharedAddr.getPointer()); | |||
997 | llvm::Value *PrivatePointer = | |||
998 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
999 | PrivateAddr.getPointer(), SharedAddr.getType()); | |||
1000 | llvm::Value *Ptr = CGF.Builder.CreateGEP( | |||
1001 | SharedAddr.getElementType(), PrivatePointer, Adjustment); | |||
1002 | return castToBase(CGF, OrigVD->getType(), | |||
1003 | SharedAddresses[N].first.getType(), | |||
1004 | OriginalBaseLValue.getAddress(CGF), Ptr); | |||
1005 | } | |||
1006 | BaseDecls.emplace_back( | |||
1007 | cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl())); | |||
1008 | return PrivateAddr; | |||
1009 | } | |||
1010 | ||||
1011 | bool ReductionCodeGen::usesReductionInitializer(unsigned N) const { | |||
1012 | const OMPDeclareReductionDecl *DRD = | |||
1013 | getReductionInit(ClausesData[N].ReductionOp); | |||
1014 | return DRD && DRD->getInitializer(); | |||
1015 | } | |||
1016 | ||||
1017 | LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) { | |||
1018 | return CGF.EmitLoadOfPointerLValue( | |||
1019 | CGF.GetAddrOfLocalVar(getThreadIDVariable()), | |||
1020 | getThreadIDVariable()->getType()->castAs<PointerType>()); | |||
1021 | } | |||
1022 | ||||
1023 | void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt *S) { | |||
1024 | if (!CGF.HaveInsertPoint()) | |||
1025 | return; | |||
1026 | // 1.2.2 OpenMP Language Terminology | |||
1027 | // Structured block - An executable statement with a single entry at the | |||
1028 | // top and a single exit at the bottom. | |||
1029 | // The point of exit cannot be a branch out of the structured block. | |||
1030 | // longjmp() and throw() must not violate the entry/exit criteria. | |||
1031 | CGF.EHStack.pushTerminate(); | |||
1032 | if (S) | |||
1033 | CGF.incrementProfileCounter(S); | |||
1034 | CodeGen(CGF); | |||
1035 | CGF.EHStack.popTerminate(); | |||
1036 | } | |||
1037 | ||||
1038 | LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue( | |||
1039 | CodeGenFunction &CGF) { | |||
1040 | return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()), | |||
1041 | getThreadIDVariable()->getType(), | |||
1042 | AlignmentSource::Decl); | |||
1043 | } | |||
1044 | ||||
1045 | static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC, | |||
1046 | QualType FieldTy) { | |||
1047 | auto *Field = FieldDecl::Create( | |||
1048 | C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy, | |||
1049 | C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()), | |||
1050 | /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit); | |||
1051 | Field->setAccess(AS_public); | |||
1052 | DC->addDecl(Field); | |||
1053 | return Field; | |||
1054 | } | |||
1055 | ||||
1056 | CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM) | |||
1057 | : CGM(CGM), OMPBuilder(CGM.getModule()) { | |||
1058 | KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8); | |||
1059 | llvm::OpenMPIRBuilderConfig Config(CGM.getLangOpts().OpenMPIsDevice, false, | |||
1060 | hasRequiresUnifiedSharedMemory(), | |||
1061 | CGM.getLangOpts().OpenMPOffloadMandatory); | |||
1062 | // Initialize Types used in OpenMPIRBuilder from OMPKinds.def | |||
1063 | OMPBuilder.initialize(); | |||
1064 | OMPBuilder.setConfig(Config); | |||
1065 | loadOffloadInfoMetadata(); | |||
1066 | } | |||
1067 | ||||
1068 | void CGOpenMPRuntime::clear() { | |||
1069 | InternalVars.clear(); | |||
1070 | // Clean non-target variable declarations possibly used only in debug info. | |||
1071 | for (const auto &Data : EmittedNonTargetVariables) { | |||
1072 | if (!Data.getValue().pointsToAliveValue()) | |||
1073 | continue; | |||
1074 | auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue()); | |||
1075 | if (!GV) | |||
1076 | continue; | |||
1077 | if (!GV->isDeclaration() || GV->getNumUses() > 0) | |||
1078 | continue; | |||
1079 | GV->eraseFromParent(); | |||
1080 | } | |||
1081 | } | |||
1082 | ||||
1083 | std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const { | |||
1084 | return OMPBuilder.createPlatformSpecificName(Parts); | |||
1085 | } | |||
1086 | ||||
1087 | static llvm::Function * | |||
1088 | emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty, | |||
1089 | const Expr *CombinerInitializer, const VarDecl *In, | |||
1090 | const VarDecl *Out, bool IsCombiner) { | |||
1091 | // void .omp_combiner.(Ty *in, Ty *out); | |||
1092 | ASTContext &C = CGM.getContext(); | |||
1093 | QualType PtrTy = C.getPointerType(Ty).withRestrict(); | |||
1094 | FunctionArgList Args; | |||
1095 | ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(), | |||
1096 | /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other); | |||
1097 | ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(), | |||
1098 | /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other); | |||
1099 | Args.push_back(&OmpOutParm); | |||
1100 | Args.push_back(&OmpInParm); | |||
1101 | const CGFunctionInfo &FnInfo = | |||
1102 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
1103 | llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); | |||
1104 | std::string Name = CGM.getOpenMPRuntime().getName( | |||
1105 | {IsCombiner ? "omp_combiner" : "omp_initializer", ""}); | |||
1106 | auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, | |||
1107 | Name, &CGM.getModule()); | |||
1108 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); | |||
1109 | if (CGM.getLangOpts().Optimize) { | |||
1110 | Fn->removeFnAttr(llvm::Attribute::NoInline); | |||
1111 | Fn->removeFnAttr(llvm::Attribute::OptimizeNone); | |||
1112 | Fn->addFnAttr(llvm::Attribute::AlwaysInline); | |||
1113 | } | |||
1114 | CodeGenFunction CGF(CGM); | |||
1115 | // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions. | |||
1116 | // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions. | |||
1117 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(), | |||
1118 | Out->getLocation()); | |||
1119 | CodeGenFunction::OMPPrivateScope Scope(CGF); | |||
1120 | Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm); | |||
1121 | Scope.addPrivate( | |||
1122 | In, CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>()) | |||
1123 | .getAddress(CGF)); | |||
1124 | Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm); | |||
1125 | Scope.addPrivate( | |||
1126 | Out, CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>()) | |||
1127 | .getAddress(CGF)); | |||
1128 | (void)Scope.Privatize(); | |||
1129 | if (!IsCombiner && Out->hasInit() && | |||
1130 | !CGF.isTrivialInitializer(Out->getInit())) { | |||
1131 | CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out), | |||
1132 | Out->getType().getQualifiers(), | |||
1133 | /*IsInitializer=*/true); | |||
1134 | } | |||
1135 | if (CombinerInitializer) | |||
1136 | CGF.EmitIgnoredExpr(CombinerInitializer); | |||
1137 | Scope.ForceCleanup(); | |||
1138 | CGF.FinishFunction(); | |||
1139 | return Fn; | |||
1140 | } | |||
1141 | ||||
1142 | void CGOpenMPRuntime::emitUserDefinedReduction( | |||
1143 | CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) { | |||
1144 | if (UDRMap.count(D) > 0) | |||
1145 | return; | |||
1146 | llvm::Function *Combiner = emitCombinerOrInitializer( | |||
1147 | CGM, D->getType(), D->getCombiner(), | |||
1148 | cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()), | |||
1149 | cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()), | |||
1150 | /*IsCombiner=*/true); | |||
1151 | llvm::Function *Initializer = nullptr; | |||
1152 | if (const Expr *Init = D->getInitializer()) { | |||
1153 | Initializer = emitCombinerOrInitializer( | |||
1154 | CGM, D->getType(), | |||
1155 | D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init | |||
1156 | : nullptr, | |||
1157 | cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()), | |||
1158 | cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()), | |||
1159 | /*IsCombiner=*/false); | |||
1160 | } | |||
1161 | UDRMap.try_emplace(D, Combiner, Initializer); | |||
1162 | if (CGF) { | |||
1163 | auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn); | |||
1164 | Decls.second.push_back(D); | |||
1165 | } | |||
1166 | } | |||
1167 | ||||
1168 | std::pair<llvm::Function *, llvm::Function *> | |||
1169 | CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) { | |||
1170 | auto I = UDRMap.find(D); | |||
1171 | if (I != UDRMap.end()) | |||
1172 | return I->second; | |||
1173 | emitUserDefinedReduction(/*CGF=*/nullptr, D); | |||
1174 | return UDRMap.lookup(D); | |||
1175 | } | |||
1176 | ||||
1177 | namespace { | |||
1178 | // Temporary RAII solution to perform a push/pop stack event on the OpenMP IR | |||
1179 | // Builder if one is present. | |||
1180 | struct PushAndPopStackRAII { | |||
1181 | PushAndPopStackRAII(llvm::OpenMPIRBuilder *OMPBuilder, CodeGenFunction &CGF, | |||
1182 | bool HasCancel, llvm::omp::Directive Kind) | |||
1183 | : OMPBuilder(OMPBuilder) { | |||
1184 | if (!OMPBuilder) | |||
1185 | return; | |||
1186 | ||||
1187 | // The following callback is the crucial part of clangs cleanup process. | |||
1188 | // | |||
1189 | // NOTE: | |||
1190 | // Once the OpenMPIRBuilder is used to create parallel regions (and | |||
1191 | // similar), the cancellation destination (Dest below) is determined via | |||
1192 | // IP. That means if we have variables to finalize we split the block at IP, | |||
1193 | // use the new block (=BB) as destination to build a JumpDest (via | |||
1194 | // getJumpDestInCurrentScope(BB)) which then is fed to | |||
1195 | // EmitBranchThroughCleanup. Furthermore, there will not be the need | |||
1196 | // to push & pop an FinalizationInfo object. | |||
1197 | // The FiniCB will still be needed but at the point where the | |||
1198 | // OpenMPIRBuilder is asked to construct a parallel (or similar) construct. | |||
1199 | auto FiniCB = [&CGF](llvm::OpenMPIRBuilder::InsertPointTy IP) { | |||
1200 | assert(IP.getBlock()->end() == IP.getPoint() &&(static_cast <bool> (IP.getBlock()->end() == IP.getPoint () && "Clang CG should cause non-terminated block!") ? void (0) : __assert_fail ("IP.getBlock()->end() == IP.getPoint() && \"Clang CG should cause non-terminated block!\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1201, __extension__ __PRETTY_FUNCTION__)) | |||
1201 | "Clang CG should cause non-terminated block!")(static_cast <bool> (IP.getBlock()->end() == IP.getPoint () && "Clang CG should cause non-terminated block!") ? void (0) : __assert_fail ("IP.getBlock()->end() == IP.getPoint() && \"Clang CG should cause non-terminated block!\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1201, __extension__ __PRETTY_FUNCTION__)); | |||
1202 | CGBuilderTy::InsertPointGuard IPG(CGF.Builder); | |||
1203 | CGF.Builder.restoreIP(IP); | |||
1204 | CodeGenFunction::JumpDest Dest = | |||
1205 | CGF.getOMPCancelDestination(OMPD_parallel); | |||
1206 | CGF.EmitBranchThroughCleanup(Dest); | |||
1207 | }; | |||
1208 | ||||
1209 | // TODO: Remove this once we emit parallel regions through the | |||
1210 | // OpenMPIRBuilder as it can do this setup internally. | |||
1211 | llvm::OpenMPIRBuilder::FinalizationInfo FI({FiniCB, Kind, HasCancel}); | |||
1212 | OMPBuilder->pushFinalizationCB(std::move(FI)); | |||
1213 | } | |||
1214 | ~PushAndPopStackRAII() { | |||
1215 | if (OMPBuilder) | |||
1216 | OMPBuilder->popFinalizationCB(); | |||
1217 | } | |||
1218 | llvm::OpenMPIRBuilder *OMPBuilder; | |||
1219 | }; | |||
1220 | } // namespace | |||
1221 | ||||
1222 | static llvm::Function *emitParallelOrTeamsOutlinedFunction( | |||
1223 | CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS, | |||
1224 | const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, | |||
1225 | const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) { | |||
1226 | assert(ThreadIDVar->getType()->isPointerType() &&(static_cast <bool> (ThreadIDVar->getType()->isPointerType () && "thread id variable must be of type kmp_int32 *" ) ? void (0) : __assert_fail ("ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 *\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1227, __extension__ __PRETTY_FUNCTION__)) | |||
1227 | "thread id variable must be of type kmp_int32 *")(static_cast <bool> (ThreadIDVar->getType()->isPointerType () && "thread id variable must be of type kmp_int32 *" ) ? void (0) : __assert_fail ("ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 *\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1227, __extension__ __PRETTY_FUNCTION__)); | |||
1228 | CodeGenFunction CGF(CGM, true); | |||
1229 | bool HasCancel = false; | |||
1230 | if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D)) | |||
1231 | HasCancel = OPD->hasCancel(); | |||
1232 | else if (const auto *OPD = dyn_cast<OMPTargetParallelDirective>(&D)) | |||
1233 | HasCancel = OPD->hasCancel(); | |||
1234 | else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D)) | |||
1235 | HasCancel = OPSD->hasCancel(); | |||
1236 | else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D)) | |||
1237 | HasCancel = OPFD->hasCancel(); | |||
1238 | else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D)) | |||
1239 | HasCancel = OPFD->hasCancel(); | |||
1240 | else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D)) | |||
1241 | HasCancel = OPFD->hasCancel(); | |||
1242 | else if (const auto *OPFD = | |||
1243 | dyn_cast<OMPTeamsDistributeParallelForDirective>(&D)) | |||
1244 | HasCancel = OPFD->hasCancel(); | |||
1245 | else if (const auto *OPFD = | |||
1246 | dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D)) | |||
1247 | HasCancel = OPFD->hasCancel(); | |||
1248 | ||||
1249 | // TODO: Temporarily inform the OpenMPIRBuilder, if any, about the new | |||
1250 | // parallel region to make cancellation barriers work properly. | |||
1251 | llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); | |||
1252 | PushAndPopStackRAII PSR(&OMPBuilder, CGF, HasCancel, InnermostKind); | |||
1253 | CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind, | |||
1254 | HasCancel, OutlinedHelperName); | |||
1255 | CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); | |||
1256 | return CGF.GenerateOpenMPCapturedStmtFunction(*CS, D.getBeginLoc()); | |||
1257 | } | |||
1258 | ||||
1259 | std::string CGOpenMPRuntime::getOutlinedHelperName(StringRef Name) const { | |||
1260 | std::string Suffix = getName({"omp_outlined"}); | |||
1261 | return (Name + Suffix).str(); | |||
1262 | } | |||
1263 | ||||
1264 | std::string CGOpenMPRuntime::getOutlinedHelperName(CodeGenFunction &CGF) const { | |||
1265 | return getOutlinedHelperName(CGF.CurFn->getName()); | |||
1266 | } | |||
1267 | ||||
1268 | std::string CGOpenMPRuntime::getReductionFuncName(StringRef Name) const { | |||
1269 | std::string Suffix = getName({"omp", "reduction", "reduction_func"}); | |||
1270 | return (Name + Suffix).str(); | |||
1271 | } | |||
1272 | ||||
1273 | llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction( | |||
1274 | CodeGenFunction &CGF, const OMPExecutableDirective &D, | |||
1275 | const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, | |||
1276 | const RegionCodeGenTy &CodeGen) { | |||
1277 | const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel); | |||
1278 | return emitParallelOrTeamsOutlinedFunction( | |||
1279 | CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(CGF), | |||
1280 | CodeGen); | |||
1281 | } | |||
1282 | ||||
1283 | llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction( | |||
1284 | CodeGenFunction &CGF, const OMPExecutableDirective &D, | |||
1285 | const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, | |||
1286 | const RegionCodeGenTy &CodeGen) { | |||
1287 | const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams); | |||
1288 | return emitParallelOrTeamsOutlinedFunction( | |||
1289 | CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(CGF), | |||
1290 | CodeGen); | |||
1291 | } | |||
1292 | ||||
1293 | llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction( | |||
1294 | const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, | |||
1295 | const VarDecl *PartIDVar, const VarDecl *TaskTVar, | |||
1296 | OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, | |||
1297 | bool Tied, unsigned &NumberOfParts) { | |||
1298 | auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF, | |||
1299 | PrePostActionTy &) { | |||
1300 | llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc()); | |||
1301 | llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc()); | |||
1302 | llvm::Value *TaskArgs[] = { | |||
1303 | UpLoc, ThreadID, | |||
1304 | CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar), | |||
1305 | TaskTVar->getType()->castAs<PointerType>()) | |||
1306 | .getPointer(CGF)}; | |||
1307 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
1308 | CGM.getModule(), OMPRTL___kmpc_omp_task), | |||
1309 | TaskArgs); | |||
1310 | }; | |||
1311 | CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar, | |||
1312 | UntiedCodeGen); | |||
1313 | CodeGen.setAction(Action); | |||
1314 | assert(!ThreadIDVar->getType()->isPointerType() &&(static_cast <bool> (!ThreadIDVar->getType()->isPointerType () && "thread id variable must be of type kmp_int32 for tasks" ) ? void (0) : __assert_fail ("!ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 for tasks\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1315, __extension__ __PRETTY_FUNCTION__)) | |||
1315 | "thread id variable must be of type kmp_int32 for tasks")(static_cast <bool> (!ThreadIDVar->getType()->isPointerType () && "thread id variable must be of type kmp_int32 for tasks" ) ? void (0) : __assert_fail ("!ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 for tasks\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1315, __extension__ __PRETTY_FUNCTION__)); | |||
1316 | const OpenMPDirectiveKind Region = | |||
1317 | isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop | |||
1318 | : OMPD_task; | |||
1319 | const CapturedStmt *CS = D.getCapturedStmt(Region); | |||
1320 | bool HasCancel = false; | |||
1321 | if (const auto *TD = dyn_cast<OMPTaskDirective>(&D)) | |||
1322 | HasCancel = TD->hasCancel(); | |||
1323 | else if (const auto *TD = dyn_cast<OMPTaskLoopDirective>(&D)) | |||
1324 | HasCancel = TD->hasCancel(); | |||
1325 | else if (const auto *TD = dyn_cast<OMPMasterTaskLoopDirective>(&D)) | |||
1326 | HasCancel = TD->hasCancel(); | |||
1327 | else if (const auto *TD = dyn_cast<OMPParallelMasterTaskLoopDirective>(&D)) | |||
1328 | HasCancel = TD->hasCancel(); | |||
1329 | ||||
1330 | CodeGenFunction CGF(CGM, true); | |||
1331 | CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, | |||
1332 | InnermostKind, HasCancel, Action); | |||
1333 | CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); | |||
1334 | llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS); | |||
1335 | if (!Tied) | |||
1336 | NumberOfParts = Action.getNumberOfParts(); | |||
1337 | return Res; | |||
1338 | } | |||
1339 | ||||
1340 | void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF, | |||
1341 | bool AtCurrentPoint) { | |||
1342 | auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); | |||
1343 | assert(!Elem.second.ServiceInsertPt && "Insert point is set already.")(static_cast <bool> (!Elem.second.ServiceInsertPt && "Insert point is set already.") ? void (0) : __assert_fail ( "!Elem.second.ServiceInsertPt && \"Insert point is set already.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1343, __extension__ __PRETTY_FUNCTION__)); | |||
1344 | ||||
1345 | llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty); | |||
1346 | if (AtCurrentPoint) { | |||
1347 | Elem.second.ServiceInsertPt = new llvm::BitCastInst( | |||
1348 | Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock()); | |||
1349 | } else { | |||
1350 | Elem.second.ServiceInsertPt = | |||
1351 | new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt"); | |||
1352 | Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt); | |||
1353 | } | |||
1354 | } | |||
1355 | ||||
1356 | void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) { | |||
1357 | auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); | |||
1358 | if (Elem.second.ServiceInsertPt) { | |||
1359 | llvm::Instruction *Ptr = Elem.second.ServiceInsertPt; | |||
1360 | Elem.second.ServiceInsertPt = nullptr; | |||
1361 | Ptr->eraseFromParent(); | |||
1362 | } | |||
1363 | } | |||
1364 | ||||
1365 | static StringRef getIdentStringFromSourceLocation(CodeGenFunction &CGF, | |||
1366 | SourceLocation Loc, | |||
1367 | SmallString<128> &Buffer) { | |||
1368 | llvm::raw_svector_ostream OS(Buffer); | |||
1369 | // Build debug location | |||
1370 | PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc); | |||
1371 | OS << ";" << PLoc.getFilename() << ";"; | |||
1372 | if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) | |||
1373 | OS << FD->getQualifiedNameAsString(); | |||
1374 | OS << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;"; | |||
1375 | return OS.str(); | |||
1376 | } | |||
1377 | ||||
1378 | llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF, | |||
1379 | SourceLocation Loc, | |||
1380 | unsigned Flags, bool EmitLoc) { | |||
1381 | uint32_t SrcLocStrSize; | |||
1382 | llvm::Constant *SrcLocStr; | |||
1383 | if ((!EmitLoc && CGM.getCodeGenOpts().getDebugInfo() == | |||
1384 | llvm::codegenoptions::NoDebugInfo) || | |||
1385 | Loc.isInvalid()) { | |||
1386 | SrcLocStr = OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize); | |||
1387 | } else { | |||
1388 | std::string FunctionName; | |||
1389 | if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) | |||
1390 | FunctionName = FD->getQualifiedNameAsString(); | |||
1391 | PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc); | |||
1392 | const char *FileName = PLoc.getFilename(); | |||
1393 | unsigned Line = PLoc.getLine(); | |||
1394 | unsigned Column = PLoc.getColumn(); | |||
1395 | SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(FunctionName, FileName, Line, | |||
1396 | Column, SrcLocStrSize); | |||
1397 | } | |||
1398 | unsigned Reserved2Flags = getDefaultLocationReserved2Flags(); | |||
1399 | return OMPBuilder.getOrCreateIdent( | |||
1400 | SrcLocStr, SrcLocStrSize, llvm::omp::IdentFlag(Flags), Reserved2Flags); | |||
1401 | } | |||
1402 | ||||
1403 | llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF, | |||
1404 | SourceLocation Loc) { | |||
1405 | assert(CGF.CurFn && "No function in current CodeGenFunction.")(static_cast <bool> (CGF.CurFn && "No function in current CodeGenFunction." ) ? void (0) : __assert_fail ("CGF.CurFn && \"No function in current CodeGenFunction.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1405, __extension__ __PRETTY_FUNCTION__)); | |||
1406 | // If the OpenMPIRBuilder is used we need to use it for all thread id calls as | |||
1407 | // the clang invariants used below might be broken. | |||
1408 | if (CGM.getLangOpts().OpenMPIRBuilder) { | |||
1409 | SmallString<128> Buffer; | |||
1410 | OMPBuilder.updateToLocation(CGF.Builder.saveIP()); | |||
1411 | uint32_t SrcLocStrSize; | |||
1412 | auto *SrcLocStr = OMPBuilder.getOrCreateSrcLocStr( | |||
1413 | getIdentStringFromSourceLocation(CGF, Loc, Buffer), SrcLocStrSize); | |||
1414 | return OMPBuilder.getOrCreateThreadID( | |||
1415 | OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize)); | |||
1416 | } | |||
1417 | ||||
1418 | llvm::Value *ThreadID = nullptr; | |||
1419 | // Check whether we've already cached a load of the thread id in this | |||
1420 | // function. | |||
1421 | auto I = OpenMPLocThreadIDMap.find(CGF.CurFn); | |||
1422 | if (I != OpenMPLocThreadIDMap.end()) { | |||
1423 | ThreadID = I->second.ThreadID; | |||
1424 | if (ThreadID != nullptr) | |||
1425 | return ThreadID; | |||
1426 | } | |||
1427 | // If exceptions are enabled, do not use parameter to avoid possible crash. | |||
1428 | if (auto *OMPRegionInfo = | |||
1429 | dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { | |||
1430 | if (OMPRegionInfo->getThreadIDVariable()) { | |||
1431 | // Check if this an outlined function with thread id passed as argument. | |||
1432 | LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF); | |||
1433 | llvm::BasicBlock *TopBlock = CGF.AllocaInsertPt->getParent(); | |||
1434 | if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions || | |||
1435 | !CGF.getLangOpts().CXXExceptions || | |||
1436 | CGF.Builder.GetInsertBlock() == TopBlock || | |||
1437 | !isa<llvm::Instruction>(LVal.getPointer(CGF)) || | |||
1438 | cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() == | |||
1439 | TopBlock || | |||
1440 | cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() == | |||
1441 | CGF.Builder.GetInsertBlock()) { | |||
1442 | ThreadID = CGF.EmitLoadOfScalar(LVal, Loc); | |||
1443 | // If value loaded in entry block, cache it and use it everywhere in | |||
1444 | // function. | |||
1445 | if (CGF.Builder.GetInsertBlock() == TopBlock) { | |||
1446 | auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); | |||
1447 | Elem.second.ThreadID = ThreadID; | |||
1448 | } | |||
1449 | return ThreadID; | |||
1450 | } | |||
1451 | } | |||
1452 | } | |||
1453 | ||||
1454 | // This is not an outlined function region - need to call __kmpc_int32 | |||
1455 | // kmpc_global_thread_num(ident_t *loc). | |||
1456 | // Generate thread id value and cache this value for use across the | |||
1457 | // function. | |||
1458 | auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); | |||
1459 | if (!Elem.second.ServiceInsertPt) | |||
1460 | setLocThreadIdInsertPt(CGF); | |||
1461 | CGBuilderTy::InsertPointGuard IPG(CGF.Builder); | |||
1462 | CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt); | |||
1463 | llvm::CallInst *Call = CGF.Builder.CreateCall( | |||
1464 | OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), | |||
1465 | OMPRTL___kmpc_global_thread_num), | |||
1466 | emitUpdateLocation(CGF, Loc)); | |||
1467 | Call->setCallingConv(CGF.getRuntimeCC()); | |||
1468 | Elem.second.ThreadID = Call; | |||
1469 | return Call; | |||
1470 | } | |||
1471 | ||||
1472 | void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) { | |||
1473 | assert(CGF.CurFn && "No function in current CodeGenFunction.")(static_cast <bool> (CGF.CurFn && "No function in current CodeGenFunction." ) ? void (0) : __assert_fail ("CGF.CurFn && \"No function in current CodeGenFunction.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1473, __extension__ __PRETTY_FUNCTION__)); | |||
1474 | if (OpenMPLocThreadIDMap.count(CGF.CurFn)) { | |||
1475 | clearLocThreadIdInsertPt(CGF); | |||
1476 | OpenMPLocThreadIDMap.erase(CGF.CurFn); | |||
1477 | } | |||
1478 | if (FunctionUDRMap.count(CGF.CurFn) > 0) { | |||
1479 | for(const auto *D : FunctionUDRMap[CGF.CurFn]) | |||
1480 | UDRMap.erase(D); | |||
1481 | FunctionUDRMap.erase(CGF.CurFn); | |||
1482 | } | |||
1483 | auto I = FunctionUDMMap.find(CGF.CurFn); | |||
1484 | if (I != FunctionUDMMap.end()) { | |||
1485 | for(const auto *D : I->second) | |||
1486 | UDMMap.erase(D); | |||
1487 | FunctionUDMMap.erase(I); | |||
1488 | } | |||
1489 | LastprivateConditionalToTypes.erase(CGF.CurFn); | |||
1490 | FunctionToUntiedTaskStackMap.erase(CGF.CurFn); | |||
1491 | } | |||
1492 | ||||
1493 | llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() { | |||
1494 | return OMPBuilder.IdentPtr; | |||
1495 | } | |||
1496 | ||||
1497 | llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() { | |||
1498 | if (!Kmpc_MicroTy) { | |||
1499 | // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...) | |||
1500 | llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty), | |||
1501 | llvm::PointerType::getUnqual(CGM.Int32Ty)}; | |||
1502 | Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true); | |||
1503 | } | |||
1504 | return llvm::PointerType::getUnqual(Kmpc_MicroTy); | |||
1505 | } | |||
1506 | ||||
1507 | llvm::FunctionCallee | |||
1508 | CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned, | |||
1509 | bool IsGPUDistribute) { | |||
1510 | assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1511, __extension__ __PRETTY_FUNCTION__)) | |||
1511 | "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1511, __extension__ __PRETTY_FUNCTION__)); | |||
1512 | StringRef Name; | |||
1513 | if (IsGPUDistribute) | |||
1514 | Name = IVSize == 32 ? (IVSigned ? "__kmpc_distribute_static_init_4" | |||
1515 | : "__kmpc_distribute_static_init_4u") | |||
1516 | : (IVSigned ? "__kmpc_distribute_static_init_8" | |||
1517 | : "__kmpc_distribute_static_init_8u"); | |||
1518 | else | |||
1519 | Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4" | |||
1520 | : "__kmpc_for_static_init_4u") | |||
1521 | : (IVSigned ? "__kmpc_for_static_init_8" | |||
1522 | : "__kmpc_for_static_init_8u"); | |||
1523 | ||||
1524 | llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; | |||
1525 | auto *PtrTy = llvm::PointerType::getUnqual(ITy); | |||
1526 | llvm::Type *TypeParams[] = { | |||
1527 | getIdentTyPointerTy(), // loc | |||
1528 | CGM.Int32Ty, // tid | |||
1529 | CGM.Int32Ty, // schedtype | |||
1530 | llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter | |||
1531 | PtrTy, // p_lower | |||
1532 | PtrTy, // p_upper | |||
1533 | PtrTy, // p_stride | |||
1534 | ITy, // incr | |||
1535 | ITy // chunk | |||
1536 | }; | |||
1537 | auto *FnTy = | |||
1538 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); | |||
1539 | return CGM.CreateRuntimeFunction(FnTy, Name); | |||
1540 | } | |||
1541 | ||||
1542 | llvm::FunctionCallee | |||
1543 | CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) { | |||
1544 | assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1545, __extension__ __PRETTY_FUNCTION__)) | |||
1545 | "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1545, __extension__ __PRETTY_FUNCTION__)); | |||
1546 | StringRef Name = | |||
1547 | IVSize == 32 | |||
1548 | ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u") | |||
1549 | : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u"); | |||
1550 | llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; | |||
1551 | llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc | |||
1552 | CGM.Int32Ty, // tid | |||
1553 | CGM.Int32Ty, // schedtype | |||
1554 | ITy, // lower | |||
1555 | ITy, // upper | |||
1556 | ITy, // stride | |||
1557 | ITy // chunk | |||
1558 | }; | |||
1559 | auto *FnTy = | |||
1560 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); | |||
1561 | return CGM.CreateRuntimeFunction(FnTy, Name); | |||
1562 | } | |||
1563 | ||||
1564 | llvm::FunctionCallee | |||
1565 | CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) { | |||
1566 | assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1567, __extension__ __PRETTY_FUNCTION__)) | |||
1567 | "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1567, __extension__ __PRETTY_FUNCTION__)); | |||
1568 | StringRef Name = | |||
1569 | IVSize == 32 | |||
1570 | ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u") | |||
1571 | : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u"); | |||
1572 | llvm::Type *TypeParams[] = { | |||
1573 | getIdentTyPointerTy(), // loc | |||
1574 | CGM.Int32Ty, // tid | |||
1575 | }; | |||
1576 | auto *FnTy = | |||
1577 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); | |||
1578 | return CGM.CreateRuntimeFunction(FnTy, Name); | |||
1579 | } | |||
1580 | ||||
1581 | llvm::FunctionCallee | |||
1582 | CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) { | |||
1583 | assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1584, __extension__ __PRETTY_FUNCTION__)) | |||
1584 | "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1584, __extension__ __PRETTY_FUNCTION__)); | |||
1585 | StringRef Name = | |||
1586 | IVSize == 32 | |||
1587 | ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u") | |||
1588 | : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u"); | |||
1589 | llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; | |||
1590 | auto *PtrTy = llvm::PointerType::getUnqual(ITy); | |||
1591 | llvm::Type *TypeParams[] = { | |||
1592 | getIdentTyPointerTy(), // loc | |||
1593 | CGM.Int32Ty, // tid | |||
1594 | llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter | |||
1595 | PtrTy, // p_lower | |||
1596 | PtrTy, // p_upper | |||
1597 | PtrTy // p_stride | |||
1598 | }; | |||
1599 | auto *FnTy = | |||
1600 | llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); | |||
1601 | return CGM.CreateRuntimeFunction(FnTy, Name); | |||
1602 | } | |||
1603 | ||||
1604 | /// Obtain information that uniquely identifies a target entry. This | |||
1605 | /// consists of the file and device IDs as well as line number associated with | |||
1606 | /// the relevant entry source location. | |||
1607 | static llvm::TargetRegionEntryInfo | |||
1608 | getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc, | |||
1609 | StringRef ParentName = "") { | |||
1610 | SourceManager &SM = C.getSourceManager(); | |||
1611 | ||||
1612 | // The loc should be always valid and have a file ID (the user cannot use | |||
1613 | // #pragma directives in macros) | |||
1614 | ||||
1615 | assert(Loc.isValid() && "Source location is expected to be always valid.")(static_cast <bool> (Loc.isValid() && "Source location is expected to be always valid." ) ? void (0) : __assert_fail ("Loc.isValid() && \"Source location is expected to be always valid.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1615, __extension__ __PRETTY_FUNCTION__)); | |||
1616 | ||||
1617 | PresumedLoc PLoc = SM.getPresumedLoc(Loc); | |||
1618 | assert(PLoc.isValid() && "Source location is expected to be always valid.")(static_cast <bool> (PLoc.isValid() && "Source location is expected to be always valid." ) ? void (0) : __assert_fail ("PLoc.isValid() && \"Source location is expected to be always valid.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1618, __extension__ __PRETTY_FUNCTION__)); | |||
1619 | ||||
1620 | llvm::sys::fs::UniqueID ID; | |||
1621 | if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { | |||
1622 | PLoc = SM.getPresumedLoc(Loc, /*UseLineDirectives=*/false); | |||
1623 | assert(PLoc.isValid() && "Source location is expected to be always valid.")(static_cast <bool> (PLoc.isValid() && "Source location is expected to be always valid." ) ? void (0) : __assert_fail ("PLoc.isValid() && \"Source location is expected to be always valid.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1623, __extension__ __PRETTY_FUNCTION__)); | |||
1624 | if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) | |||
1625 | SM.getDiagnostics().Report(diag::err_cannot_open_file) | |||
1626 | << PLoc.getFilename() << EC.message(); | |||
1627 | } | |||
1628 | ||||
1629 | return llvm::TargetRegionEntryInfo(ParentName, ID.getDevice(), ID.getFile(), | |||
1630 | PLoc.getLine()); | |||
1631 | } | |||
1632 | ||||
1633 | Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) { | |||
1634 | if (CGM.getLangOpts().OpenMPSimd) | |||
1635 | return Address::invalid(); | |||
1636 | std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = | |||
1637 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); | |||
1638 | if (Res && (*Res == OMPDeclareTargetDeclAttr::MT_Link || | |||
1639 | ((*Res == OMPDeclareTargetDeclAttr::MT_To || | |||
1640 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && | |||
1641 | HasRequiresUnifiedSharedMemory))) { | |||
1642 | SmallString<64> PtrName; | |||
1643 | { | |||
1644 | llvm::raw_svector_ostream OS(PtrName); | |||
1645 | OS << CGM.getMangledName(GlobalDecl(VD)); | |||
1646 | if (!VD->isExternallyVisible()) { | |||
1647 | auto EntryInfo = getTargetEntryUniqueInfo( | |||
1648 | CGM.getContext(), VD->getCanonicalDecl()->getBeginLoc()); | |||
1649 | OS << llvm::format("_%x", EntryInfo.FileID); | |||
1650 | } | |||
1651 | OS << "_decl_tgt_ref_ptr"; | |||
1652 | } | |||
1653 | llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName); | |||
1654 | QualType PtrTy = CGM.getContext().getPointerType(VD->getType()); | |||
1655 | llvm::Type *LlvmPtrTy = CGM.getTypes().ConvertTypeForMem(PtrTy); | |||
1656 | if (!Ptr) { | |||
1657 | Ptr = OMPBuilder.getOrCreateInternalVariable(LlvmPtrTy, PtrName); | |||
1658 | ||||
1659 | auto *GV = cast<llvm::GlobalVariable>(Ptr); | |||
1660 | GV->setLinkage(llvm::GlobalValue::WeakAnyLinkage); | |||
1661 | ||||
1662 | if (!CGM.getLangOpts().OpenMPIsDevice) | |||
1663 | GV->setInitializer(CGM.GetAddrOfGlobal(VD)); | |||
1664 | registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr)); | |||
1665 | } | |||
1666 | return Address(Ptr, LlvmPtrTy, CGM.getContext().getDeclAlign(VD)); | |||
1667 | } | |||
1668 | return Address::invalid(); | |||
1669 | } | |||
1670 | ||||
1671 | llvm::Constant * | |||
1672 | CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) { | |||
1673 | assert(!CGM.getLangOpts().OpenMPUseTLS ||(static_cast <bool> (!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()) ? void ( 0) : __assert_fail ("!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1674, __extension__ __PRETTY_FUNCTION__)) | |||
1674 | !CGM.getContext().getTargetInfo().isTLSSupported())(static_cast <bool> (!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()) ? void ( 0) : __assert_fail ("!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1674, __extension__ __PRETTY_FUNCTION__)); | |||
1675 | // Lookup the entry, lazily creating it if necessary. | |||
1676 | std::string Suffix = getName({"cache", ""}); | |||
1677 | return OMPBuilder.getOrCreateInternalVariable( | |||
1678 | CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix).str()); | |||
1679 | } | |||
1680 | ||||
1681 | Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF, | |||
1682 | const VarDecl *VD, | |||
1683 | Address VDAddr, | |||
1684 | SourceLocation Loc) { | |||
1685 | if (CGM.getLangOpts().OpenMPUseTLS && | |||
1686 | CGM.getContext().getTargetInfo().isTLSSupported()) | |||
1687 | return VDAddr; | |||
1688 | ||||
1689 | llvm::Type *VarTy = VDAddr.getElementType(); | |||
1690 | llvm::Value *Args[] = { | |||
1691 | emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
1692 | CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.Int8PtrTy), | |||
1693 | CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)), | |||
1694 | getOrCreateThreadPrivateCache(VD)}; | |||
1695 | return Address( | |||
1696 | CGF.EmitRuntimeCall( | |||
1697 | OMPBuilder.getOrCreateRuntimeFunction( | |||
1698 | CGM.getModule(), OMPRTL___kmpc_threadprivate_cached), | |||
1699 | Args), | |||
1700 | CGF.Int8Ty, VDAddr.getAlignment()); | |||
1701 | } | |||
1702 | ||||
1703 | void CGOpenMPRuntime::emitThreadPrivateVarInit( | |||
1704 | CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor, | |||
1705 | llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) { | |||
1706 | // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime | |||
1707 | // library. | |||
1708 | llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc); | |||
1709 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
1710 | CGM.getModule(), OMPRTL___kmpc_global_thread_num), | |||
1711 | OMPLoc); | |||
1712 | // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor) | |||
1713 | // to register constructor/destructor for variable. | |||
1714 | llvm::Value *Args[] = { | |||
1715 | OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy), | |||
1716 | Ctor, CopyCtor, Dtor}; | |||
1717 | CGF.EmitRuntimeCall( | |||
1718 | OMPBuilder.getOrCreateRuntimeFunction( | |||
1719 | CGM.getModule(), OMPRTL___kmpc_threadprivate_register), | |||
1720 | Args); | |||
1721 | } | |||
1722 | ||||
1723 | llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition( | |||
1724 | const VarDecl *VD, Address VDAddr, SourceLocation Loc, | |||
1725 | bool PerformInit, CodeGenFunction *CGF) { | |||
1726 | if (CGM.getLangOpts().OpenMPUseTLS && | |||
1727 | CGM.getContext().getTargetInfo().isTLSSupported()) | |||
1728 | return nullptr; | |||
1729 | ||||
1730 | VD = VD->getDefinition(CGM.getContext()); | |||
1731 | if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) { | |||
1732 | QualType ASTTy = VD->getType(); | |||
1733 | ||||
1734 | llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr; | |||
1735 | const Expr *Init = VD->getAnyInitializer(); | |||
1736 | if (CGM.getLangOpts().CPlusPlus && PerformInit) { | |||
1737 | // Generate function that re-emits the declaration's initializer into the | |||
1738 | // threadprivate copy of the variable VD | |||
1739 | CodeGenFunction CtorCGF(CGM); | |||
1740 | FunctionArgList Args; | |||
1741 | ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc, | |||
1742 | /*Id=*/nullptr, CGM.getContext().VoidPtrTy, | |||
1743 | ImplicitParamDecl::Other); | |||
1744 | Args.push_back(&Dst); | |||
1745 | ||||
1746 | const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( | |||
1747 | CGM.getContext().VoidPtrTy, Args); | |||
1748 | llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); | |||
1749 | std::string Name = getName({"__kmpc_global_ctor_", ""}); | |||
1750 | llvm::Function *Fn = | |||
1751 | CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc); | |||
1752 | CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI, | |||
1753 | Args, Loc, Loc); | |||
1754 | llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar( | |||
1755 | CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false, | |||
1756 | CGM.getContext().VoidPtrTy, Dst.getLocation()); | |||
1757 | Address Arg(ArgVal, CtorCGF.Int8Ty, VDAddr.getAlignment()); | |||
1758 | Arg = CtorCGF.Builder.CreateElementBitCast( | |||
1759 | Arg, CtorCGF.ConvertTypeForMem(ASTTy)); | |||
1760 | CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(), | |||
1761 | /*IsInitializer=*/true); | |||
1762 | ArgVal = CtorCGF.EmitLoadOfScalar( | |||
1763 | CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false, | |||
1764 | CGM.getContext().VoidPtrTy, Dst.getLocation()); | |||
1765 | CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue); | |||
1766 | CtorCGF.FinishFunction(); | |||
1767 | Ctor = Fn; | |||
1768 | } | |||
1769 | if (VD->getType().isDestructedType() != QualType::DK_none) { | |||
1770 | // Generate function that emits destructor call for the threadprivate copy | |||
1771 | // of the variable VD | |||
1772 | CodeGenFunction DtorCGF(CGM); | |||
1773 | FunctionArgList Args; | |||
1774 | ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc, | |||
1775 | /*Id=*/nullptr, CGM.getContext().VoidPtrTy, | |||
1776 | ImplicitParamDecl::Other); | |||
1777 | Args.push_back(&Dst); | |||
1778 | ||||
1779 | const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( | |||
1780 | CGM.getContext().VoidTy, Args); | |||
1781 | llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); | |||
1782 | std::string Name = getName({"__kmpc_global_dtor_", ""}); | |||
1783 | llvm::Function *Fn = | |||
1784 | CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc); | |||
1785 | auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF); | |||
1786 | DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args, | |||
1787 | Loc, Loc); | |||
1788 | // Create a scope with an artificial location for the body of this function. | |||
1789 | auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF); | |||
1790 | llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar( | |||
1791 | DtorCGF.GetAddrOfLocalVar(&Dst), | |||
1792 | /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation()); | |||
1793 | DtorCGF.emitDestroy( | |||
1794 | Address(ArgVal, DtorCGF.Int8Ty, VDAddr.getAlignment()), ASTTy, | |||
1795 | DtorCGF.getDestroyer(ASTTy.isDestructedType()), | |||
1796 | DtorCGF.needsEHCleanup(ASTTy.isDestructedType())); | |||
1797 | DtorCGF.FinishFunction(); | |||
1798 | Dtor = Fn; | |||
1799 | } | |||
1800 | // Do not emit init function if it is not required. | |||
1801 | if (!Ctor && !Dtor) | |||
1802 | return nullptr; | |||
1803 | ||||
1804 | llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; | |||
1805 | auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs, | |||
1806 | /*isVarArg=*/false) | |||
1807 | ->getPointerTo(); | |||
1808 | // Copying constructor for the threadprivate variable. | |||
1809 | // Must be NULL - reserved by runtime, but currently it requires that this | |||
1810 | // parameter is always NULL. Otherwise it fires assertion. | |||
1811 | CopyCtor = llvm::Constant::getNullValue(CopyCtorTy); | |||
1812 | if (Ctor == nullptr) { | |||
1813 | auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy, | |||
1814 | /*isVarArg=*/false) | |||
1815 | ->getPointerTo(); | |||
1816 | Ctor = llvm::Constant::getNullValue(CtorTy); | |||
1817 | } | |||
1818 | if (Dtor == nullptr) { | |||
1819 | auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, | |||
1820 | /*isVarArg=*/false) | |||
1821 | ->getPointerTo(); | |||
1822 | Dtor = llvm::Constant::getNullValue(DtorTy); | |||
1823 | } | |||
1824 | if (!CGF) { | |||
1825 | auto *InitFunctionTy = | |||
1826 | llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false); | |||
1827 | std::string Name = getName({"__omp_threadprivate_init_", ""}); | |||
1828 | llvm::Function *InitFunction = CGM.CreateGlobalInitOrCleanUpFunction( | |||
1829 | InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction()); | |||
1830 | CodeGenFunction InitCGF(CGM); | |||
1831 | FunctionArgList ArgList; | |||
1832 | InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction, | |||
1833 | CGM.getTypes().arrangeNullaryFunction(), ArgList, | |||
1834 | Loc, Loc); | |||
1835 | emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc); | |||
1836 | InitCGF.FinishFunction(); | |||
1837 | return InitFunction; | |||
1838 | } | |||
1839 | emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc); | |||
1840 | } | |||
1841 | return nullptr; | |||
1842 | } | |||
1843 | ||||
1844 | bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD, | |||
1845 | llvm::GlobalVariable *Addr, | |||
1846 | bool PerformInit) { | |||
1847 | if (CGM.getLangOpts().OMPTargetTriples.empty() && | |||
1848 | !CGM.getLangOpts().OpenMPIsDevice) | |||
1849 | return false; | |||
1850 | std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = | |||
1851 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); | |||
1852 | if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link || | |||
1853 | ((*Res == OMPDeclareTargetDeclAttr::MT_To || | |||
1854 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && | |||
1855 | HasRequiresUnifiedSharedMemory)) | |||
1856 | return CGM.getLangOpts().OpenMPIsDevice; | |||
1857 | VD = VD->getDefinition(CGM.getContext()); | |||
1858 | assert(VD && "Unknown VarDecl")(static_cast <bool> (VD && "Unknown VarDecl") ? void (0) : __assert_fail ("VD && \"Unknown VarDecl\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1858, __extension__ __PRETTY_FUNCTION__)); | |||
1859 | ||||
1860 | if (!DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second) | |||
1861 | return CGM.getLangOpts().OpenMPIsDevice; | |||
1862 | ||||
1863 | QualType ASTTy = VD->getType(); | |||
1864 | SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc(); | |||
1865 | ||||
1866 | // Produce the unique prefix to identify the new target regions. We use | |||
1867 | // the source location of the variable declaration which we know to not | |||
1868 | // conflict with any target region. | |||
1869 | auto EntryInfo = | |||
1870 | getTargetEntryUniqueInfo(CGM.getContext(), Loc, VD->getName()); | |||
1871 | SmallString<128> Buffer, Out; | |||
1872 | OMPBuilder.OffloadInfoManager.getTargetRegionEntryFnName(Buffer, EntryInfo); | |||
1873 | ||||
1874 | const Expr *Init = VD->getAnyInitializer(); | |||
1875 | if (CGM.getLangOpts().CPlusPlus && PerformInit) { | |||
1876 | llvm::Constant *Ctor; | |||
1877 | llvm::Constant *ID; | |||
1878 | if (CGM.getLangOpts().OpenMPIsDevice) { | |||
1879 | // Generate function that re-emits the declaration's initializer into | |||
1880 | // the threadprivate copy of the variable VD | |||
1881 | CodeGenFunction CtorCGF(CGM); | |||
1882 | ||||
1883 | const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); | |||
1884 | llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); | |||
1885 | llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction( | |||
1886 | FTy, Twine(Buffer, "_ctor"), FI, Loc, false, | |||
1887 | llvm::GlobalValue::WeakODRLinkage); | |||
1888 | Fn->setVisibility(llvm::GlobalValue::ProtectedVisibility); | |||
1889 | if (CGM.getTriple().isAMDGCN()) | |||
1890 | Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL); | |||
1891 | auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF); | |||
1892 | CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, | |||
1893 | FunctionArgList(), Loc, Loc); | |||
1894 | auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF); | |||
1895 | llvm::Constant *AddrInAS0 = Addr; | |||
1896 | if (Addr->getAddressSpace() != 0) | |||
1897 | AddrInAS0 = llvm::ConstantExpr::getAddrSpaceCast( | |||
1898 | Addr, llvm::PointerType::getWithSamePointeeType( | |||
1899 | cast<llvm::PointerType>(Addr->getType()), 0)); | |||
1900 | CtorCGF.EmitAnyExprToMem(Init, | |||
1901 | Address(AddrInAS0, Addr->getValueType(), | |||
1902 | CGM.getContext().getDeclAlign(VD)), | |||
1903 | Init->getType().getQualifiers(), | |||
1904 | /*IsInitializer=*/true); | |||
1905 | CtorCGF.FinishFunction(); | |||
1906 | Ctor = Fn; | |||
1907 | ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); | |||
1908 | } else { | |||
1909 | Ctor = new llvm::GlobalVariable( | |||
1910 | CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, | |||
1911 | llvm::GlobalValue::PrivateLinkage, | |||
1912 | llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor")); | |||
1913 | ID = Ctor; | |||
1914 | } | |||
1915 | ||||
1916 | // Register the information for the entry associated with the constructor. | |||
1917 | Out.clear(); | |||
1918 | auto CtorEntryInfo = EntryInfo; | |||
1919 | CtorEntryInfo.ParentName = Twine(Buffer, "_ctor").toStringRef(Out); | |||
1920 | OMPBuilder.OffloadInfoManager.registerTargetRegionEntryInfo( | |||
1921 | CtorEntryInfo, Ctor, ID, | |||
1922 | llvm::OffloadEntriesInfoManager::OMPTargetRegionEntryCtor); | |||
1923 | } | |||
1924 | if (VD->getType().isDestructedType() != QualType::DK_none) { | |||
1925 | llvm::Constant *Dtor; | |||
1926 | llvm::Constant *ID; | |||
1927 | if (CGM.getLangOpts().OpenMPIsDevice) { | |||
1928 | // Generate function that emits destructor call for the threadprivate | |||
1929 | // copy of the variable VD | |||
1930 | CodeGenFunction DtorCGF(CGM); | |||
1931 | ||||
1932 | const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); | |||
1933 | llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); | |||
1934 | llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction( | |||
1935 | FTy, Twine(Buffer, "_dtor"), FI, Loc, false, | |||
1936 | llvm::GlobalValue::WeakODRLinkage); | |||
1937 | Fn->setVisibility(llvm::GlobalValue::ProtectedVisibility); | |||
1938 | if (CGM.getTriple().isAMDGCN()) | |||
1939 | Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL); | |||
1940 | auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF); | |||
1941 | DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, | |||
1942 | FunctionArgList(), Loc, Loc); | |||
1943 | // Create a scope with an artificial location for the body of this | |||
1944 | // function. | |||
1945 | auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF); | |||
1946 | llvm::Constant *AddrInAS0 = Addr; | |||
1947 | if (Addr->getAddressSpace() != 0) | |||
1948 | AddrInAS0 = llvm::ConstantExpr::getAddrSpaceCast( | |||
1949 | Addr, llvm::PointerType::getWithSamePointeeType( | |||
1950 | cast<llvm::PointerType>(Addr->getType()), 0)); | |||
1951 | DtorCGF.emitDestroy(Address(AddrInAS0, Addr->getValueType(), | |||
1952 | CGM.getContext().getDeclAlign(VD)), | |||
1953 | ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()), | |||
1954 | DtorCGF.needsEHCleanup(ASTTy.isDestructedType())); | |||
1955 | DtorCGF.FinishFunction(); | |||
1956 | Dtor = Fn; | |||
1957 | ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); | |||
1958 | } else { | |||
1959 | Dtor = new llvm::GlobalVariable( | |||
1960 | CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, | |||
1961 | llvm::GlobalValue::PrivateLinkage, | |||
1962 | llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor")); | |||
1963 | ID = Dtor; | |||
1964 | } | |||
1965 | // Register the information for the entry associated with the destructor. | |||
1966 | Out.clear(); | |||
1967 | auto DtorEntryInfo = EntryInfo; | |||
1968 | DtorEntryInfo.ParentName = Twine(Buffer, "_dtor").toStringRef(Out); | |||
1969 | OMPBuilder.OffloadInfoManager.registerTargetRegionEntryInfo( | |||
1970 | DtorEntryInfo, Dtor, ID, | |||
1971 | llvm::OffloadEntriesInfoManager::OMPTargetRegionEntryDtor); | |||
1972 | } | |||
1973 | return CGM.getLangOpts().OpenMPIsDevice; | |||
1974 | } | |||
1975 | ||||
1976 | Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, | |||
1977 | QualType VarType, | |||
1978 | StringRef Name) { | |||
1979 | std::string Suffix = getName({"artificial", ""}); | |||
1980 | llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType); | |||
1981 | llvm::GlobalVariable *GAddr = OMPBuilder.getOrCreateInternalVariable( | |||
1982 | VarLVType, Twine(Name).concat(Suffix).str()); | |||
1983 | if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPUseTLS && | |||
1984 | CGM.getTarget().isTLSSupported()) { | |||
1985 | GAddr->setThreadLocal(/*Val=*/true); | |||
1986 | return Address(GAddr, GAddr->getValueType(), | |||
1987 | CGM.getContext().getTypeAlignInChars(VarType)); | |||
1988 | } | |||
1989 | std::string CacheSuffix = getName({"cache", ""}); | |||
1990 | llvm::Value *Args[] = { | |||
1991 | emitUpdateLocation(CGF, SourceLocation()), | |||
1992 | getThreadID(CGF, SourceLocation()), | |||
1993 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy), | |||
1994 | CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy, | |||
1995 | /*isSigned=*/false), | |||
1996 | OMPBuilder.getOrCreateInternalVariable( | |||
1997 | CGM.VoidPtrPtrTy, | |||
1998 | Twine(Name).concat(Suffix).concat(CacheSuffix).str())}; | |||
1999 | return Address( | |||
2000 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2001 | CGF.EmitRuntimeCall( | |||
2002 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2003 | CGM.getModule(), OMPRTL___kmpc_threadprivate_cached), | |||
2004 | Args), | |||
2005 | VarLVType->getPointerTo(/*AddrSpace=*/0)), | |||
2006 | VarLVType, CGM.getContext().getTypeAlignInChars(VarType)); | |||
2007 | } | |||
2008 | ||||
2009 | void CGOpenMPRuntime::emitIfClause(CodeGenFunction &CGF, const Expr *Cond, | |||
2010 | const RegionCodeGenTy &ThenGen, | |||
2011 | const RegionCodeGenTy &ElseGen) { | |||
2012 | CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange()); | |||
2013 | ||||
2014 | // If the condition constant folds and can be elided, try to avoid emitting | |||
2015 | // the condition and the dead arm of the if/else. | |||
2016 | bool CondConstant; | |||
2017 | if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) { | |||
2018 | if (CondConstant) | |||
2019 | ThenGen(CGF); | |||
2020 | else | |||
2021 | ElseGen(CGF); | |||
2022 | return; | |||
2023 | } | |||
2024 | ||||
2025 | // Otherwise, the condition did not fold, or we couldn't elide it. Just | |||
2026 | // emit the conditional branch. | |||
2027 | llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then"); | |||
2028 | llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else"); | |||
2029 | llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end"); | |||
2030 | CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0); | |||
2031 | ||||
2032 | // Emit the 'then' code. | |||
2033 | CGF.EmitBlock(ThenBlock); | |||
2034 | ThenGen(CGF); | |||
2035 | CGF.EmitBranch(ContBlock); | |||
2036 | // Emit the 'else' code if present. | |||
2037 | // There is no need to emit line number for unconditional branch. | |||
2038 | (void)ApplyDebugLocation::CreateEmpty(CGF); | |||
2039 | CGF.EmitBlock(ElseBlock); | |||
2040 | ElseGen(CGF); | |||
2041 | // There is no need to emit line number for unconditional branch. | |||
2042 | (void)ApplyDebugLocation::CreateEmpty(CGF); | |||
2043 | CGF.EmitBranch(ContBlock); | |||
2044 | // Emit the continuation block for code after the if. | |||
2045 | CGF.EmitBlock(ContBlock, /*IsFinished=*/true); | |||
2046 | } | |||
2047 | ||||
2048 | void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
2049 | llvm::Function *OutlinedFn, | |||
2050 | ArrayRef<llvm::Value *> CapturedVars, | |||
2051 | const Expr *IfCond, | |||
2052 | llvm::Value *NumThreads) { | |||
2053 | if (!CGF.HaveInsertPoint()) | |||
2054 | return; | |||
2055 | llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc); | |||
2056 | auto &M = CGM.getModule(); | |||
2057 | auto &&ThenGen = [&M, OutlinedFn, CapturedVars, RTLoc, | |||
2058 | this](CodeGenFunction &CGF, PrePostActionTy &) { | |||
2059 | // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn); | |||
2060 | CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); | |||
2061 | llvm::Value *Args[] = { | |||
2062 | RTLoc, | |||
2063 | CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars | |||
2064 | CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())}; | |||
2065 | llvm::SmallVector<llvm::Value *, 16> RealArgs; | |||
2066 | RealArgs.append(std::begin(Args), std::end(Args)); | |||
2067 | RealArgs.append(CapturedVars.begin(), CapturedVars.end()); | |||
2068 | ||||
2069 | llvm::FunctionCallee RTLFn = | |||
2070 | OMPBuilder.getOrCreateRuntimeFunction(M, OMPRTL___kmpc_fork_call); | |||
2071 | CGF.EmitRuntimeCall(RTLFn, RealArgs); | |||
2072 | }; | |||
2073 | auto &&ElseGen = [&M, OutlinedFn, CapturedVars, RTLoc, Loc, | |||
2074 | this](CodeGenFunction &CGF, PrePostActionTy &) { | |||
2075 | CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); | |||
2076 | llvm::Value *ThreadID = RT.getThreadID(CGF, Loc); | |||
2077 | // Build calls: | |||
2078 | // __kmpc_serialized_parallel(&Loc, GTid); | |||
2079 | llvm::Value *Args[] = {RTLoc, ThreadID}; | |||
2080 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2081 | M, OMPRTL___kmpc_serialized_parallel), | |||
2082 | Args); | |||
2083 | ||||
2084 | // OutlinedFn(>id, &zero_bound, CapturedStruct); | |||
2085 | Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc); | |||
2086 | Address ZeroAddrBound = | |||
2087 | CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, | |||
2088 | /*Name=*/".bound.zero.addr"); | |||
2089 | CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddrBound); | |||
2090 | llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; | |||
2091 | // ThreadId for serialized parallels is 0. | |||
2092 | OutlinedFnArgs.push_back(ThreadIDAddr.getPointer()); | |||
2093 | OutlinedFnArgs.push_back(ZeroAddrBound.getPointer()); | |||
2094 | OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); | |||
2095 | ||||
2096 | // Ensure we do not inline the function. This is trivially true for the ones | |||
2097 | // passed to __kmpc_fork_call but the ones called in serialized regions | |||
2098 | // could be inlined. This is not a perfect but it is closer to the invariant | |||
2099 | // we want, namely, every data environment starts with a new function. | |||
2100 | // TODO: We should pass the if condition to the runtime function and do the | |||
2101 | // handling there. Much cleaner code. | |||
2102 | OutlinedFn->removeFnAttr(llvm::Attribute::AlwaysInline); | |||
2103 | OutlinedFn->addFnAttr(llvm::Attribute::NoInline); | |||
2104 | RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs); | |||
2105 | ||||
2106 | // __kmpc_end_serialized_parallel(&Loc, GTid); | |||
2107 | llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID}; | |||
2108 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2109 | M, OMPRTL___kmpc_end_serialized_parallel), | |||
2110 | EndArgs); | |||
2111 | }; | |||
2112 | if (IfCond) { | |||
2113 | emitIfClause(CGF, IfCond, ThenGen, ElseGen); | |||
2114 | } else { | |||
2115 | RegionCodeGenTy ThenRCG(ThenGen); | |||
2116 | ThenRCG(CGF); | |||
2117 | } | |||
2118 | } | |||
2119 | ||||
2120 | // If we're inside an (outlined) parallel region, use the region info's | |||
2121 | // thread-ID variable (it is passed in a first argument of the outlined function | |||
2122 | // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in | |||
2123 | // regular serial code region, get thread ID by calling kmp_int32 | |||
2124 | // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and | |||
2125 | // return the address of that temp. | |||
2126 | Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF, | |||
2127 | SourceLocation Loc) { | |||
2128 | if (auto *OMPRegionInfo = | |||
2129 | dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) | |||
2130 | if (OMPRegionInfo->getThreadIDVariable()) | |||
2131 | return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress(CGF); | |||
2132 | ||||
2133 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
2134 | QualType Int32Ty = | |||
2135 | CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true); | |||
2136 | Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp."); | |||
2137 | CGF.EmitStoreOfScalar(ThreadID, | |||
2138 | CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty)); | |||
2139 | ||||
2140 | return ThreadIDTemp; | |||
2141 | } | |||
2142 | ||||
2143 | llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) { | |||
2144 | std::string Prefix = Twine("gomp_critical_user_", CriticalName).str(); | |||
2145 | std::string Name = getName({Prefix, "var"}); | |||
2146 | return OMPBuilder.getOrCreateInternalVariable(KmpCriticalNameTy, Name); | |||
2147 | } | |||
2148 | ||||
2149 | namespace { | |||
2150 | /// Common pre(post)-action for different OpenMP constructs. | |||
2151 | class CommonActionTy final : public PrePostActionTy { | |||
2152 | llvm::FunctionCallee EnterCallee; | |||
2153 | ArrayRef<llvm::Value *> EnterArgs; | |||
2154 | llvm::FunctionCallee ExitCallee; | |||
2155 | ArrayRef<llvm::Value *> ExitArgs; | |||
2156 | bool Conditional; | |||
2157 | llvm::BasicBlock *ContBlock = nullptr; | |||
2158 | ||||
2159 | public: | |||
2160 | CommonActionTy(llvm::FunctionCallee EnterCallee, | |||
2161 | ArrayRef<llvm::Value *> EnterArgs, | |||
2162 | llvm::FunctionCallee ExitCallee, | |||
2163 | ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false) | |||
2164 | : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee), | |||
2165 | ExitArgs(ExitArgs), Conditional(Conditional) {} | |||
2166 | void Enter(CodeGenFunction &CGF) override { | |||
2167 | llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs); | |||
2168 | if (Conditional) { | |||
2169 | llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes); | |||
2170 | auto *ThenBlock = CGF.createBasicBlock("omp_if.then"); | |||
2171 | ContBlock = CGF.createBasicBlock("omp_if.end"); | |||
2172 | // Generate the branch (If-stmt) | |||
2173 | CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock); | |||
2174 | CGF.EmitBlock(ThenBlock); | |||
2175 | } | |||
2176 | } | |||
2177 | void Done(CodeGenFunction &CGF) { | |||
2178 | // Emit the rest of blocks/branches | |||
2179 | CGF.EmitBranch(ContBlock); | |||
2180 | CGF.EmitBlock(ContBlock, true); | |||
2181 | } | |||
2182 | void Exit(CodeGenFunction &CGF) override { | |||
2183 | CGF.EmitRuntimeCall(ExitCallee, ExitArgs); | |||
2184 | } | |||
2185 | }; | |||
2186 | } // anonymous namespace | |||
2187 | ||||
2188 | void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF, | |||
2189 | StringRef CriticalName, | |||
2190 | const RegionCodeGenTy &CriticalOpGen, | |||
2191 | SourceLocation Loc, const Expr *Hint) { | |||
2192 | // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]); | |||
2193 | // CriticalOpGen(); | |||
2194 | // __kmpc_end_critical(ident_t *, gtid, Lock); | |||
2195 | // Prepare arguments and build a call to __kmpc_critical | |||
2196 | if (!CGF.HaveInsertPoint()) | |||
2197 | return; | |||
2198 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2199 | getCriticalRegionLock(CriticalName)}; | |||
2200 | llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), | |||
2201 | std::end(Args)); | |||
2202 | if (Hint
| |||
2203 | EnterArgs.push_back(CGF.Builder.CreateIntCast( | |||
2204 | CGF.EmitScalarExpr(Hint), CGM.Int32Ty, /*isSigned=*/false)); | |||
2205 | } | |||
2206 | CommonActionTy Action( | |||
2207 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2208 | CGM.getModule(), | |||
2209 | Hint
| |||
2210 | EnterArgs, | |||
2211 | OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), | |||
2212 | OMPRTL___kmpc_end_critical), | |||
2213 | Args); | |||
2214 | CriticalOpGen.setAction(Action); | |||
2215 | emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen); | |||
| ||||
2216 | } | |||
2217 | ||||
2218 | void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF, | |||
2219 | const RegionCodeGenTy &MasterOpGen, | |||
2220 | SourceLocation Loc) { | |||
2221 | if (!CGF.HaveInsertPoint()) | |||
2222 | return; | |||
2223 | // if(__kmpc_master(ident_t *, gtid)) { | |||
2224 | // MasterOpGen(); | |||
2225 | // __kmpc_end_master(ident_t *, gtid); | |||
2226 | // } | |||
2227 | // Prepare arguments and build a call to __kmpc_master | |||
2228 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2229 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2230 | CGM.getModule(), OMPRTL___kmpc_master), | |||
2231 | Args, | |||
2232 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2233 | CGM.getModule(), OMPRTL___kmpc_end_master), | |||
2234 | Args, | |||
2235 | /*Conditional=*/true); | |||
2236 | MasterOpGen.setAction(Action); | |||
2237 | emitInlinedDirective(CGF, OMPD_master, MasterOpGen); | |||
2238 | Action.Done(CGF); | |||
2239 | } | |||
2240 | ||||
2241 | void CGOpenMPRuntime::emitMaskedRegion(CodeGenFunction &CGF, | |||
2242 | const RegionCodeGenTy &MaskedOpGen, | |||
2243 | SourceLocation Loc, const Expr *Filter) { | |||
2244 | if (!CGF.HaveInsertPoint()) | |||
2245 | return; | |||
2246 | // if(__kmpc_masked(ident_t *, gtid, filter)) { | |||
2247 | // MaskedOpGen(); | |||
2248 | // __kmpc_end_masked(iden_t *, gtid); | |||
2249 | // } | |||
2250 | // Prepare arguments and build a call to __kmpc_masked | |||
2251 | llvm::Value *FilterVal = Filter | |||
2252 | ? CGF.EmitScalarExpr(Filter, CGF.Int32Ty) | |||
2253 | : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0); | |||
2254 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2255 | FilterVal}; | |||
2256 | llvm::Value *ArgsEnd[] = {emitUpdateLocation(CGF, Loc), | |||
2257 | getThreadID(CGF, Loc)}; | |||
2258 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2259 | CGM.getModule(), OMPRTL___kmpc_masked), | |||
2260 | Args, | |||
2261 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2262 | CGM.getModule(), OMPRTL___kmpc_end_masked), | |||
2263 | ArgsEnd, | |||
2264 | /*Conditional=*/true); | |||
2265 | MaskedOpGen.setAction(Action); | |||
2266 | emitInlinedDirective(CGF, OMPD_masked, MaskedOpGen); | |||
2267 | Action.Done(CGF); | |||
2268 | } | |||
2269 | ||||
2270 | void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF, | |||
2271 | SourceLocation Loc) { | |||
2272 | if (!CGF.HaveInsertPoint()) | |||
2273 | return; | |||
2274 | if (CGF.CGM.getLangOpts().OpenMPIRBuilder) { | |||
2275 | OMPBuilder.createTaskyield(CGF.Builder); | |||
2276 | } else { | |||
2277 | // Build call __kmpc_omp_taskyield(loc, thread_id, 0); | |||
2278 | llvm::Value *Args[] = { | |||
2279 | emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2280 | llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)}; | |||
2281 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2282 | CGM.getModule(), OMPRTL___kmpc_omp_taskyield), | |||
2283 | Args); | |||
2284 | } | |||
2285 | ||||
2286 | if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) | |||
2287 | Region->emitUntiedSwitch(CGF); | |||
2288 | } | |||
2289 | ||||
2290 | void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF, | |||
2291 | const RegionCodeGenTy &TaskgroupOpGen, | |||
2292 | SourceLocation Loc) { | |||
2293 | if (!CGF.HaveInsertPoint()) | |||
2294 | return; | |||
2295 | // __kmpc_taskgroup(ident_t *, gtid); | |||
2296 | // TaskgroupOpGen(); | |||
2297 | // __kmpc_end_taskgroup(ident_t *, gtid); | |||
2298 | // Prepare arguments and build a call to __kmpc_taskgroup | |||
2299 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2300 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2301 | CGM.getModule(), OMPRTL___kmpc_taskgroup), | |||
2302 | Args, | |||
2303 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2304 | CGM.getModule(), OMPRTL___kmpc_end_taskgroup), | |||
2305 | Args); | |||
2306 | TaskgroupOpGen.setAction(Action); | |||
2307 | emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen); | |||
2308 | } | |||
2309 | ||||
2310 | /// Given an array of pointers to variables, project the address of a | |||
2311 | /// given variable. | |||
2312 | static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array, | |||
2313 | unsigned Index, const VarDecl *Var) { | |||
2314 | // Pull out the pointer to the variable. | |||
2315 | Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index); | |||
2316 | llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr); | |||
2317 | ||||
2318 | llvm::Type *ElemTy = CGF.ConvertTypeForMem(Var->getType()); | |||
2319 | return Address( | |||
2320 | CGF.Builder.CreateBitCast( | |||
2321 | Ptr, ElemTy->getPointerTo(Ptr->getType()->getPointerAddressSpace())), | |||
2322 | ElemTy, CGF.getContext().getDeclAlign(Var)); | |||
2323 | } | |||
2324 | ||||
2325 | static llvm::Value *emitCopyprivateCopyFunction( | |||
2326 | CodeGenModule &CGM, llvm::Type *ArgsElemType, | |||
2327 | ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, | |||
2328 | ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps, | |||
2329 | SourceLocation Loc) { | |||
2330 | ASTContext &C = CGM.getContext(); | |||
2331 | // void copy_func(void *LHSArg, void *RHSArg); | |||
2332 | FunctionArgList Args; | |||
2333 | ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
2334 | ImplicitParamDecl::Other); | |||
2335 | ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
2336 | ImplicitParamDecl::Other); | |||
2337 | Args.push_back(&LHSArg); | |||
2338 | Args.push_back(&RHSArg); | |||
2339 | const auto &CGFI = | |||
2340 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
2341 | std::string Name = | |||
2342 | CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"}); | |||
2343 | auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI), | |||
2344 | llvm::GlobalValue::InternalLinkage, Name, | |||
2345 | &CGM.getModule()); | |||
2346 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); | |||
2347 | Fn->setDoesNotRecurse(); | |||
2348 | CodeGenFunction CGF(CGM); | |||
2349 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); | |||
2350 | // Dest = (void*[n])(LHSArg); | |||
2351 | // Src = (void*[n])(RHSArg); | |||
2352 | Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2353 | CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)), | |||
2354 | ArgsElemType->getPointerTo()), | |||
2355 | ArgsElemType, CGF.getPointerAlign()); | |||
2356 | Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2357 | CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)), | |||
2358 | ArgsElemType->getPointerTo()), | |||
2359 | ArgsElemType, CGF.getPointerAlign()); | |||
2360 | // *(Type0*)Dst[0] = *(Type0*)Src[0]; | |||
2361 | // *(Type1*)Dst[1] = *(Type1*)Src[1]; | |||
2362 | // ... | |||
2363 | // *(Typen*)Dst[n] = *(Typen*)Src[n]; | |||
2364 | for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) { | |||
2365 | const auto *DestVar = | |||
2366 | cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()); | |||
2367 | Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar); | |||
2368 | ||||
2369 | const auto *SrcVar = | |||
2370 | cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()); | |||
2371 | Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar); | |||
2372 | ||||
2373 | const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl(); | |||
2374 | QualType Type = VD->getType(); | |||
2375 | CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]); | |||
2376 | } | |||
2377 | CGF.FinishFunction(); | |||
2378 | return Fn; | |||
2379 | } | |||
2380 | ||||
2381 | void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF, | |||
2382 | const RegionCodeGenTy &SingleOpGen, | |||
2383 | SourceLocation Loc, | |||
2384 | ArrayRef<const Expr *> CopyprivateVars, | |||
2385 | ArrayRef<const Expr *> SrcExprs, | |||
2386 | ArrayRef<const Expr *> DstExprs, | |||
2387 | ArrayRef<const Expr *> AssignmentOps) { | |||
2388 | if (!CGF.HaveInsertPoint()) | |||
2389 | return; | |||
2390 | assert(CopyprivateVars.size() == SrcExprs.size() &&(static_cast <bool> (CopyprivateVars.size() == SrcExprs .size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()) ? void (0) : __assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2392, __extension__ __PRETTY_FUNCTION__)) | |||
2391 | CopyprivateVars.size() == DstExprs.size() &&(static_cast <bool> (CopyprivateVars.size() == SrcExprs .size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()) ? void (0) : __assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2392, __extension__ __PRETTY_FUNCTION__)) | |||
2392 | CopyprivateVars.size() == AssignmentOps.size())(static_cast <bool> (CopyprivateVars.size() == SrcExprs .size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()) ? void (0) : __assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2392, __extension__ __PRETTY_FUNCTION__)); | |||
2393 | ASTContext &C = CGM.getContext(); | |||
2394 | // int32 did_it = 0; | |||
2395 | // if(__kmpc_single(ident_t *, gtid)) { | |||
2396 | // SingleOpGen(); | |||
2397 | // __kmpc_end_single(ident_t *, gtid); | |||
2398 | // did_it = 1; | |||
2399 | // } | |||
2400 | // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, | |||
2401 | // <copy_func>, did_it); | |||
2402 | ||||
2403 | Address DidIt = Address::invalid(); | |||
2404 | if (!CopyprivateVars.empty()) { | |||
2405 | // int32 did_it = 0; | |||
2406 | QualType KmpInt32Ty = | |||
2407 | C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); | |||
2408 | DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it"); | |||
2409 | CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt); | |||
2410 | } | |||
2411 | // Prepare arguments and build a call to __kmpc_single | |||
2412 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2413 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2414 | CGM.getModule(), OMPRTL___kmpc_single), | |||
2415 | Args, | |||
2416 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2417 | CGM.getModule(), OMPRTL___kmpc_end_single), | |||
2418 | Args, | |||
2419 | /*Conditional=*/true); | |||
2420 | SingleOpGen.setAction(Action); | |||
2421 | emitInlinedDirective(CGF, OMPD_single, SingleOpGen); | |||
2422 | if (DidIt.isValid()) { | |||
2423 | // did_it = 1; | |||
2424 | CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt); | |||
2425 | } | |||
2426 | Action.Done(CGF); | |||
2427 | // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, | |||
2428 | // <copy_func>, did_it); | |||
2429 | if (DidIt.isValid()) { | |||
2430 | llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size()); | |||
2431 | QualType CopyprivateArrayTy = C.getConstantArrayType( | |||
2432 | C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal, | |||
2433 | /*IndexTypeQuals=*/0); | |||
2434 | // Create a list of all private variables for copyprivate. | |||
2435 | Address CopyprivateList = | |||
2436 | CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list"); | |||
2437 | for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) { | |||
2438 | Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I); | |||
2439 | CGF.Builder.CreateStore( | |||
2440 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2441 | CGF.EmitLValue(CopyprivateVars[I]).getPointer(CGF), | |||
2442 | CGF.VoidPtrTy), | |||
2443 | Elem); | |||
2444 | } | |||
2445 | // Build function that copies private values from single region to all other | |||
2446 | // threads in the corresponding parallel region. | |||
2447 | llvm::Value *CpyFn = emitCopyprivateCopyFunction( | |||
2448 | CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy), CopyprivateVars, | |||
2449 | SrcExprs, DstExprs, AssignmentOps, Loc); | |||
2450 | llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy); | |||
2451 | Address CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2452 | CopyprivateList, CGF.VoidPtrTy, CGF.Int8Ty); | |||
2453 | llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt); | |||
2454 | llvm::Value *Args[] = { | |||
2455 | emitUpdateLocation(CGF, Loc), // ident_t *<loc> | |||
2456 | getThreadID(CGF, Loc), // i32 <gtid> | |||
2457 | BufSize, // size_t <buf_size> | |||
2458 | CL.getPointer(), // void *<copyprivate list> | |||
2459 | CpyFn, // void (*) (void *, void *) <copy_func> | |||
2460 | DidItVal // i32 did_it | |||
2461 | }; | |||
2462 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2463 | CGM.getModule(), OMPRTL___kmpc_copyprivate), | |||
2464 | Args); | |||
2465 | } | |||
2466 | } | |||
2467 | ||||
2468 | void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF, | |||
2469 | const RegionCodeGenTy &OrderedOpGen, | |||
2470 | SourceLocation Loc, bool IsThreads) { | |||
2471 | if (!CGF.HaveInsertPoint()) | |||
2472 | return; | |||
2473 | // __kmpc_ordered(ident_t *, gtid); | |||
2474 | // OrderedOpGen(); | |||
2475 | // __kmpc_end_ordered(ident_t *, gtid); | |||
2476 | // Prepare arguments and build a call to __kmpc_ordered | |||
2477 | if (IsThreads) { | |||
2478 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2479 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2480 | CGM.getModule(), OMPRTL___kmpc_ordered), | |||
2481 | Args, | |||
2482 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2483 | CGM.getModule(), OMPRTL___kmpc_end_ordered), | |||
2484 | Args); | |||
2485 | OrderedOpGen.setAction(Action); | |||
2486 | emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen); | |||
2487 | return; | |||
2488 | } | |||
2489 | emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen); | |||
2490 | } | |||
2491 | ||||
2492 | unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) { | |||
2493 | unsigned Flags; | |||
2494 | if (Kind == OMPD_for) | |||
2495 | Flags = OMP_IDENT_BARRIER_IMPL_FOR; | |||
2496 | else if (Kind == OMPD_sections) | |||
2497 | Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS; | |||
2498 | else if (Kind == OMPD_single) | |||
2499 | Flags = OMP_IDENT_BARRIER_IMPL_SINGLE; | |||
2500 | else if (Kind == OMPD_barrier) | |||
2501 | Flags = OMP_IDENT_BARRIER_EXPL; | |||
2502 | else | |||
2503 | Flags = OMP_IDENT_BARRIER_IMPL; | |||
2504 | return Flags; | |||
2505 | } | |||
2506 | ||||
2507 | void CGOpenMPRuntime::getDefaultScheduleAndChunk( | |||
2508 | CodeGenFunction &CGF, const OMPLoopDirective &S, | |||
2509 | OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const { | |||
2510 | // Check if the loop directive is actually a doacross loop directive. In this | |||
2511 | // case choose static, 1 schedule. | |||
2512 | if (llvm::any_of( | |||
2513 | S.getClausesOfKind<OMPOrderedClause>(), | |||
2514 | [](const OMPOrderedClause *C) { return C->getNumForLoops(); })) { | |||
2515 | ScheduleKind = OMPC_SCHEDULE_static; | |||
2516 | // Chunk size is 1 in this case. | |||
2517 | llvm::APInt ChunkSize(32, 1); | |||
2518 | ChunkExpr = IntegerLiteral::Create( | |||
2519 | CGF.getContext(), ChunkSize, | |||
2520 | CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0), | |||
2521 | SourceLocation()); | |||
2522 | } | |||
2523 | } | |||
2524 | ||||
2525 | void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
2526 | OpenMPDirectiveKind Kind, bool EmitChecks, | |||
2527 | bool ForceSimpleCall) { | |||
2528 | // Check if we should use the OMPBuilder | |||
2529 | auto *OMPRegionInfo = | |||
2530 | dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo); | |||
2531 | if (CGF.CGM.getLangOpts().OpenMPIRBuilder) { | |||
2532 | CGF.Builder.restoreIP(OMPBuilder.createBarrier( | |||
2533 | CGF.Builder, Kind, ForceSimpleCall, EmitChecks)); | |||
2534 | return; | |||
2535 | } | |||
2536 | ||||
2537 | if (!CGF.HaveInsertPoint()) | |||
2538 | return; | |||
2539 | // Build call __kmpc_cancel_barrier(loc, thread_id); | |||
2540 | // Build call __kmpc_barrier(loc, thread_id); | |||
2541 | unsigned Flags = getDefaultFlagsForBarriers(Kind); | |||
2542 | // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc, | |||
2543 | // thread_id); | |||
2544 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags), | |||
2545 | getThreadID(CGF, Loc)}; | |||
2546 | if (OMPRegionInfo) { | |||
2547 | if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) { | |||
2548 | llvm::Value *Result = CGF.EmitRuntimeCall( | |||
2549 | OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), | |||
2550 | OMPRTL___kmpc_cancel_barrier), | |||
2551 | Args); | |||
2552 | if (EmitChecks) { | |||
2553 | // if (__kmpc_cancel_barrier()) { | |||
2554 | // exit from construct; | |||
2555 | // } | |||
2556 | llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit"); | |||
2557 | llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue"); | |||
2558 | llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result); | |||
2559 | CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB); | |||
2560 | CGF.EmitBlock(ExitBB); | |||
2561 | // exit from construct; | |||
2562 | CodeGenFunction::JumpDest CancelDestination = | |||
2563 | CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind()); | |||
2564 | CGF.EmitBranchThroughCleanup(CancelDestination); | |||
2565 | CGF.EmitBlock(ContBB, /*IsFinished=*/true); | |||
2566 | } | |||
2567 | return; | |||
2568 | } | |||
2569 | } | |||
2570 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2571 | CGM.getModule(), OMPRTL___kmpc_barrier), | |||
2572 | Args); | |||
2573 | } | |||
2574 | ||||
2575 | void CGOpenMPRuntime::emitErrorCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
2576 | Expr *ME, bool IsFatal) { | |||
2577 | llvm::Value *MVL = | |||
2578 | ME ? CGF.EmitStringLiteralLValue(cast<StringLiteral>(ME)).getPointer(CGF) | |||
2579 | : llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
2580 | // Build call void __kmpc_error(ident_t *loc, int severity, const char | |||
2581 | // *message) | |||
2582 | llvm::Value *Args[] = { | |||
2583 | emitUpdateLocation(CGF, Loc, /*Flags=*/0, /*GenLoc=*/true), | |||
2584 | llvm::ConstantInt::get(CGM.Int32Ty, IsFatal ? 2 : 1), | |||
2585 | CGF.Builder.CreatePointerCast(MVL, CGM.Int8PtrTy)}; | |||
2586 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2587 | CGM.getModule(), OMPRTL___kmpc_error), | |||
2588 | Args); | |||
2589 | } | |||
2590 | ||||
2591 | /// Map the OpenMP loop schedule to the runtime enumeration. | |||
2592 | static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind, | |||
2593 | bool Chunked, bool Ordered) { | |||
2594 | switch (ScheduleKind) { | |||
2595 | case OMPC_SCHEDULE_static: | |||
2596 | return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked) | |||
2597 | : (Ordered ? OMP_ord_static : OMP_sch_static); | |||
2598 | case OMPC_SCHEDULE_dynamic: | |||
2599 | return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked; | |||
2600 | case OMPC_SCHEDULE_guided: | |||
2601 | return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked; | |||
2602 | case OMPC_SCHEDULE_runtime: | |||
2603 | return Ordered ? OMP_ord_runtime : OMP_sch_runtime; | |||
2604 | case OMPC_SCHEDULE_auto: | |||
2605 | return Ordered ? OMP_ord_auto : OMP_sch_auto; | |||
2606 | case OMPC_SCHEDULE_unknown: | |||
2607 | assert(!Chunked && "chunk was specified but schedule kind not known")(static_cast <bool> (!Chunked && "chunk was specified but schedule kind not known" ) ? void (0) : __assert_fail ("!Chunked && \"chunk was specified but schedule kind not known\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2607, __extension__ __PRETTY_FUNCTION__)); | |||
2608 | return Ordered ? OMP_ord_static : OMP_sch_static; | |||
2609 | } | |||
2610 | llvm_unreachable("Unexpected runtime schedule")::llvm::llvm_unreachable_internal("Unexpected runtime schedule" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2610); | |||
2611 | } | |||
2612 | ||||
2613 | /// Map the OpenMP distribute schedule to the runtime enumeration. | |||
2614 | static OpenMPSchedType | |||
2615 | getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) { | |||
2616 | // only static is allowed for dist_schedule | |||
2617 | return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static; | |||
2618 | } | |||
2619 | ||||
2620 | bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, | |||
2621 | bool Chunked) const { | |||
2622 | OpenMPSchedType Schedule = | |||
2623 | getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false); | |||
2624 | return Schedule == OMP_sch_static; | |||
2625 | } | |||
2626 | ||||
2627 | bool CGOpenMPRuntime::isStaticNonchunked( | |||
2628 | OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const { | |||
2629 | OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked); | |||
2630 | return Schedule == OMP_dist_sch_static; | |||
2631 | } | |||
2632 | ||||
2633 | bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, | |||
2634 | bool Chunked) const { | |||
2635 | OpenMPSchedType Schedule = | |||
2636 | getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false); | |||
2637 | return Schedule == OMP_sch_static_chunked; | |||
2638 | } | |||
2639 | ||||
2640 | bool CGOpenMPRuntime::isStaticChunked( | |||
2641 | OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const { | |||
2642 | OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked); | |||
2643 | return Schedule == OMP_dist_sch_static_chunked; | |||
2644 | } | |||
2645 | ||||
2646 | bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const { | |||
2647 | OpenMPSchedType Schedule = | |||
2648 | getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false); | |||
2649 | assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here")(static_cast <bool> (Schedule != OMP_sch_static_chunked && "cannot be chunked here") ? void (0) : __assert_fail ("Schedule != OMP_sch_static_chunked && \"cannot be chunked here\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2649, __extension__ __PRETTY_FUNCTION__)); | |||
2650 | return Schedule != OMP_sch_static; | |||
2651 | } | |||
2652 | ||||
2653 | static int addMonoNonMonoModifier(CodeGenModule &CGM, OpenMPSchedType Schedule, | |||
2654 | OpenMPScheduleClauseModifier M1, | |||
2655 | OpenMPScheduleClauseModifier M2) { | |||
2656 | int Modifier = 0; | |||
2657 | switch (M1) { | |||
2658 | case OMPC_SCHEDULE_MODIFIER_monotonic: | |||
2659 | Modifier = OMP_sch_modifier_monotonic; | |||
2660 | break; | |||
2661 | case OMPC_SCHEDULE_MODIFIER_nonmonotonic: | |||
2662 | Modifier = OMP_sch_modifier_nonmonotonic; | |||
2663 | break; | |||
2664 | case OMPC_SCHEDULE_MODIFIER_simd: | |||
2665 | if (Schedule == OMP_sch_static_chunked) | |||
2666 | Schedule = OMP_sch_static_balanced_chunked; | |||
2667 | break; | |||
2668 | case OMPC_SCHEDULE_MODIFIER_last: | |||
2669 | case OMPC_SCHEDULE_MODIFIER_unknown: | |||
2670 | break; | |||
2671 | } | |||
2672 | switch (M2) { | |||
2673 | case OMPC_SCHEDULE_MODIFIER_monotonic: | |||
2674 | Modifier = OMP_sch_modifier_monotonic; | |||
2675 | break; | |||
2676 | case OMPC_SCHEDULE_MODIFIER_nonmonotonic: | |||
2677 | Modifier = OMP_sch_modifier_nonmonotonic; | |||
2678 | break; | |||
2679 | case OMPC_SCHEDULE_MODIFIER_simd: | |||
2680 | if (Schedule == OMP_sch_static_chunked) | |||
2681 | Schedule = OMP_sch_static_balanced_chunked; | |||
2682 | break; | |||
2683 | case OMPC_SCHEDULE_MODIFIER_last: | |||
2684 | case OMPC_SCHEDULE_MODIFIER_unknown: | |||
2685 | break; | |||
2686 | } | |||
2687 | // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Desription. | |||
2688 | // If the static schedule kind is specified or if the ordered clause is | |||
2689 | // specified, and if the nonmonotonic modifier is not specified, the effect is | |||
2690 | // as if the monotonic modifier is specified. Otherwise, unless the monotonic | |||
2691 | // modifier is specified, the effect is as if the nonmonotonic modifier is | |||
2692 | // specified. | |||
2693 | if (CGM.getLangOpts().OpenMP >= 50 && Modifier == 0) { | |||
2694 | if (!(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static || | |||
2695 | Schedule == OMP_sch_static_balanced_chunked || | |||
2696 | Schedule == OMP_ord_static_chunked || Schedule == OMP_ord_static || | |||
2697 | Schedule == OMP_dist_sch_static_chunked || | |||
2698 | Schedule == OMP_dist_sch_static)) | |||
2699 | Modifier = OMP_sch_modifier_nonmonotonic; | |||
2700 | } | |||
2701 | return Schedule | Modifier; | |||
2702 | } | |||
2703 | ||||
2704 | void CGOpenMPRuntime::emitForDispatchInit( | |||
2705 | CodeGenFunction &CGF, SourceLocation Loc, | |||
2706 | const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, | |||
2707 | bool Ordered, const DispatchRTInput &DispatchValues) { | |||
2708 | if (!CGF.HaveInsertPoint()) | |||
2709 | return; | |||
2710 | OpenMPSchedType Schedule = getRuntimeSchedule( | |||
2711 | ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered); | |||
2712 | assert(Ordered ||(static_cast <bool> (Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)) ? void (0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2715, __extension__ __PRETTY_FUNCTION__)) | |||
2713 | (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&(static_cast <bool> (Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)) ? void (0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2715, __extension__ __PRETTY_FUNCTION__)) | |||
2714 | Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&(static_cast <bool> (Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)) ? void (0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2715, __extension__ __PRETTY_FUNCTION__)) | |||
2715 | Schedule != OMP_sch_static_balanced_chunked))(static_cast <bool> (Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)) ? void (0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2715, __extension__ __PRETTY_FUNCTION__)); | |||
2716 | // Call __kmpc_dispatch_init( | |||
2717 | // ident_t *loc, kmp_int32 tid, kmp_int32 schedule, | |||
2718 | // kmp_int[32|64] lower, kmp_int[32|64] upper, | |||
2719 | // kmp_int[32|64] stride, kmp_int[32|64] chunk); | |||
2720 | ||||
2721 | // If the Chunk was not specified in the clause - use default value 1. | |||
2722 | llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk | |||
2723 | : CGF.Builder.getIntN(IVSize, 1); | |||
2724 | llvm::Value *Args[] = { | |||
2725 | emitUpdateLocation(CGF, Loc), | |||
2726 | getThreadID(CGF, Loc), | |||
2727 | CGF.Builder.getInt32(addMonoNonMonoModifier( | |||
2728 | CGM, Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type | |||
2729 | DispatchValues.LB, // Lower | |||
2730 | DispatchValues.UB, // Upper | |||
2731 | CGF.Builder.getIntN(IVSize, 1), // Stride | |||
2732 | Chunk // Chunk | |||
2733 | }; | |||
2734 | CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args); | |||
2735 | } | |||
2736 | ||||
2737 | static void emitForStaticInitCall( | |||
2738 | CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId, | |||
2739 | llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule, | |||
2740 | OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, | |||
2741 | const CGOpenMPRuntime::StaticRTInput &Values) { | |||
2742 | if (!CGF.HaveInsertPoint()) | |||
2743 | return; | |||
2744 | ||||
2745 | assert(!Values.Ordered)(static_cast <bool> (!Values.Ordered) ? void (0) : __assert_fail ("!Values.Ordered", "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2745, __extension__ __PRETTY_FUNCTION__)); | |||
2746 | assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2750, __extension__ __PRETTY_FUNCTION__)) | |||
2747 | Schedule == OMP_sch_static_balanced_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2750, __extension__ __PRETTY_FUNCTION__)) | |||
2748 | Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2750, __extension__ __PRETTY_FUNCTION__)) | |||
2749 | Schedule == OMP_dist_sch_static ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2750, __extension__ __PRETTY_FUNCTION__)) | |||
2750 | Schedule == OMP_dist_sch_static_chunked)(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2750, __extension__ __PRETTY_FUNCTION__)); | |||
2751 | ||||
2752 | // Call __kmpc_for_static_init( | |||
2753 | // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype, | |||
2754 | // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower, | |||
2755 | // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride, | |||
2756 | // kmp_int[32|64] incr, kmp_int[32|64] chunk); | |||
2757 | llvm::Value *Chunk = Values.Chunk; | |||
2758 | if (Chunk == nullptr) { | |||
2759 | assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||(static_cast <bool> ((Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && "expected static non-chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2761, __extension__ __PRETTY_FUNCTION__)) | |||
2760 | Schedule == OMP_dist_sch_static) &&(static_cast <bool> ((Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && "expected static non-chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2761, __extension__ __PRETTY_FUNCTION__)) | |||
2761 | "expected static non-chunked schedule")(static_cast <bool> ((Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && "expected static non-chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2761, __extension__ __PRETTY_FUNCTION__)); | |||
2762 | // If the Chunk was not specified in the clause - use default value 1. | |||
2763 | Chunk = CGF.Builder.getIntN(Values.IVSize, 1); | |||
2764 | } else { | |||
2765 | assert((Schedule == OMP_sch_static_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2769, __extension__ __PRETTY_FUNCTION__)) | |||
2766 | Schedule == OMP_sch_static_balanced_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2769, __extension__ __PRETTY_FUNCTION__)) | |||
2767 | Schedule == OMP_ord_static_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2769, __extension__ __PRETTY_FUNCTION__)) | |||
2768 | Schedule == OMP_dist_sch_static_chunked) &&(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2769, __extension__ __PRETTY_FUNCTION__)) | |||
2769 | "expected static chunked schedule")(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2769, __extension__ __PRETTY_FUNCTION__)); | |||
2770 | } | |||
2771 | llvm::Value *Args[] = { | |||
2772 | UpdateLocation, | |||
2773 | ThreadId, | |||
2774 | CGF.Builder.getInt32(addMonoNonMonoModifier(CGF.CGM, Schedule, M1, | |||
2775 | M2)), // Schedule type | |||
2776 | Values.IL.getPointer(), // &isLastIter | |||
2777 | Values.LB.getPointer(), // &LB | |||
2778 | Values.UB.getPointer(), // &UB | |||
2779 | Values.ST.getPointer(), // &Stride | |||
2780 | CGF.Builder.getIntN(Values.IVSize, 1), // Incr | |||
2781 | Chunk // Chunk | |||
2782 | }; | |||
2783 | CGF.EmitRuntimeCall(ForStaticInitFunction, Args); | |||
2784 | } | |||
2785 | ||||
2786 | void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF, | |||
2787 | SourceLocation Loc, | |||
2788 | OpenMPDirectiveKind DKind, | |||
2789 | const OpenMPScheduleTy &ScheduleKind, | |||
2790 | const StaticRTInput &Values) { | |||
2791 | OpenMPSchedType ScheduleNum = getRuntimeSchedule( | |||
2792 | ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered); | |||
2793 | assert(isOpenMPWorksharingDirective(DKind) &&(static_cast <bool> (isOpenMPWorksharingDirective(DKind ) && "Expected loop-based or sections-based directive." ) ? void (0) : __assert_fail ("isOpenMPWorksharingDirective(DKind) && \"Expected loop-based or sections-based directive.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2794, __extension__ __PRETTY_FUNCTION__)) | |||
2794 | "Expected loop-based or sections-based directive.")(static_cast <bool> (isOpenMPWorksharingDirective(DKind ) && "Expected loop-based or sections-based directive." ) ? void (0) : __assert_fail ("isOpenMPWorksharingDirective(DKind) && \"Expected loop-based or sections-based directive.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2794, __extension__ __PRETTY_FUNCTION__)); | |||
2795 | llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc, | |||
2796 | isOpenMPLoopDirective(DKind) | |||
2797 | ? OMP_IDENT_WORK_LOOP | |||
2798 | : OMP_IDENT_WORK_SECTIONS); | |||
2799 | llvm::Value *ThreadId = getThreadID(CGF, Loc); | |||
2800 | llvm::FunctionCallee StaticInitFunction = | |||
2801 | createForStaticInitFunction(Values.IVSize, Values.IVSigned, false); | |||
2802 | auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc); | |||
2803 | emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction, | |||
2804 | ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values); | |||
2805 | } | |||
2806 | ||||
2807 | void CGOpenMPRuntime::emitDistributeStaticInit( | |||
2808 | CodeGenFunction &CGF, SourceLocation Loc, | |||
2809 | OpenMPDistScheduleClauseKind SchedKind, | |||
2810 | const CGOpenMPRuntime::StaticRTInput &Values) { | |||
2811 | OpenMPSchedType ScheduleNum = | |||
2812 | getRuntimeSchedule(SchedKind, Values.Chunk != nullptr); | |||
2813 | llvm::Value *UpdatedLocation = | |||
2814 | emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE); | |||
2815 | llvm::Value *ThreadId = getThreadID(CGF, Loc); | |||
2816 | llvm::FunctionCallee StaticInitFunction; | |||
2817 | bool isGPUDistribute = | |||
2818 | CGM.getLangOpts().OpenMPIsDevice && | |||
2819 | (CGM.getTriple().isAMDGCN() || CGM.getTriple().isNVPTX()); | |||
2820 | StaticInitFunction = createForStaticInitFunction( | |||
2821 | Values.IVSize, Values.IVSigned, isGPUDistribute); | |||
2822 | ||||
2823 | emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction, | |||
2824 | ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown, | |||
2825 | OMPC_SCHEDULE_MODIFIER_unknown, Values); | |||
2826 | } | |||
2827 | ||||
2828 | void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF, | |||
2829 | SourceLocation Loc, | |||
2830 | OpenMPDirectiveKind DKind) { | |||
2831 | if (!CGF.HaveInsertPoint()) | |||
2832 | return; | |||
2833 | // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid); | |||
2834 | llvm::Value *Args[] = { | |||
2835 | emitUpdateLocation(CGF, Loc, | |||
2836 | isOpenMPDistributeDirective(DKind) | |||
2837 | ? OMP_IDENT_WORK_DISTRIBUTE | |||
2838 | : isOpenMPLoopDirective(DKind) | |||
2839 | ? OMP_IDENT_WORK_LOOP | |||
2840 | : OMP_IDENT_WORK_SECTIONS), | |||
2841 | getThreadID(CGF, Loc)}; | |||
2842 | auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc); | |||
2843 | if (isOpenMPDistributeDirective(DKind) && CGM.getLangOpts().OpenMPIsDevice && | |||
2844 | (CGM.getTriple().isAMDGCN() || CGM.getTriple().isNVPTX())) | |||
2845 | CGF.EmitRuntimeCall( | |||
2846 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2847 | CGM.getModule(), OMPRTL___kmpc_distribute_static_fini), | |||
2848 | Args); | |||
2849 | else | |||
2850 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2851 | CGM.getModule(), OMPRTL___kmpc_for_static_fini), | |||
2852 | Args); | |||
2853 | } | |||
2854 | ||||
2855 | void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF, | |||
2856 | SourceLocation Loc, | |||
2857 | unsigned IVSize, | |||
2858 | bool IVSigned) { | |||
2859 | if (!CGF.HaveInsertPoint()) | |||
2860 | return; | |||
2861 | // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid); | |||
2862 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2863 | CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args); | |||
2864 | } | |||
2865 | ||||
2866 | llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF, | |||
2867 | SourceLocation Loc, unsigned IVSize, | |||
2868 | bool IVSigned, Address IL, | |||
2869 | Address LB, Address UB, | |||
2870 | Address ST) { | |||
2871 | // Call __kmpc_dispatch_next( | |||
2872 | // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, | |||
2873 | // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, | |||
2874 | // kmp_int[32|64] *p_stride); | |||
2875 | llvm::Value *Args[] = { | |||
2876 | emitUpdateLocation(CGF, Loc), | |||
2877 | getThreadID(CGF, Loc), | |||
2878 | IL.getPointer(), // &isLastIter | |||
2879 | LB.getPointer(), // &Lower | |||
2880 | UB.getPointer(), // &Upper | |||
2881 | ST.getPointer() // &Stride | |||
2882 | }; | |||
2883 | llvm::Value *Call = | |||
2884 | CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args); | |||
2885 | return CGF.EmitScalarConversion( | |||
2886 | Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1), | |||
2887 | CGF.getContext().BoolTy, Loc); | |||
2888 | } | |||
2889 | ||||
2890 | void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF, | |||
2891 | llvm::Value *NumThreads, | |||
2892 | SourceLocation Loc) { | |||
2893 | if (!CGF.HaveInsertPoint()) | |||
2894 | return; | |||
2895 | // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads) | |||
2896 | llvm::Value *Args[] = { | |||
2897 | emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2898 | CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)}; | |||
2899 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2900 | CGM.getModule(), OMPRTL___kmpc_push_num_threads), | |||
2901 | Args); | |||
2902 | } | |||
2903 | ||||
2904 | void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF, | |||
2905 | ProcBindKind ProcBind, | |||
2906 | SourceLocation Loc) { | |||
2907 | if (!CGF.HaveInsertPoint()) | |||
2908 | return; | |||
2909 | assert(ProcBind != OMP_PROC_BIND_unknown && "Unsupported proc_bind value.")(static_cast <bool> (ProcBind != OMP_PROC_BIND_unknown && "Unsupported proc_bind value.") ? void (0) : __assert_fail ( "ProcBind != OMP_PROC_BIND_unknown && \"Unsupported proc_bind value.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2909, __extension__ __PRETTY_FUNCTION__)); | |||
2910 | // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind) | |||
2911 | llvm::Value *Args[] = { | |||
2912 | emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2913 | llvm::ConstantInt::get(CGM.IntTy, unsigned(ProcBind), /*isSigned=*/true)}; | |||
2914 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2915 | CGM.getModule(), OMPRTL___kmpc_push_proc_bind), | |||
2916 | Args); | |||
2917 | } | |||
2918 | ||||
2919 | void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>, | |||
2920 | SourceLocation Loc, llvm::AtomicOrdering AO) { | |||
2921 | if (CGF.CGM.getLangOpts().OpenMPIRBuilder) { | |||
2922 | OMPBuilder.createFlush(CGF.Builder); | |||
2923 | } else { | |||
2924 | if (!CGF.HaveInsertPoint()) | |||
2925 | return; | |||
2926 | // Build call void __kmpc_flush(ident_t *loc) | |||
2927 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2928 | CGM.getModule(), OMPRTL___kmpc_flush), | |||
2929 | emitUpdateLocation(CGF, Loc)); | |||
2930 | } | |||
2931 | } | |||
2932 | ||||
2933 | namespace { | |||
2934 | /// Indexes of fields for type kmp_task_t. | |||
2935 | enum KmpTaskTFields { | |||
2936 | /// List of shared variables. | |||
2937 | KmpTaskTShareds, | |||
2938 | /// Task routine. | |||
2939 | KmpTaskTRoutine, | |||
2940 | /// Partition id for the untied tasks. | |||
2941 | KmpTaskTPartId, | |||
2942 | /// Function with call of destructors for private variables. | |||
2943 | Data1, | |||
2944 | /// Task priority. | |||
2945 | Data2, | |||
2946 | /// (Taskloops only) Lower bound. | |||
2947 | KmpTaskTLowerBound, | |||
2948 | /// (Taskloops only) Upper bound. | |||
2949 | KmpTaskTUpperBound, | |||
2950 | /// (Taskloops only) Stride. | |||
2951 | KmpTaskTStride, | |||
2952 | /// (Taskloops only) Is last iteration flag. | |||
2953 | KmpTaskTLastIter, | |||
2954 | /// (Taskloops only) Reduction data. | |||
2955 | KmpTaskTReductions, | |||
2956 | }; | |||
2957 | } // anonymous namespace | |||
2958 | ||||
2959 | void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() { | |||
2960 | // If we are in simd mode or there are no entries, we don't need to do | |||
2961 | // anything. | |||
2962 | if (CGM.getLangOpts().OpenMPSimd || OMPBuilder.OffloadInfoManager.empty()) | |||
2963 | return; | |||
2964 | ||||
2965 | llvm::OpenMPIRBuilder::EmitMetadataErrorReportFunctionTy &&ErrorReportFn = | |||
2966 | [this](llvm::OpenMPIRBuilder::EmitMetadataErrorKind Kind, | |||
2967 | const llvm::TargetRegionEntryInfo &EntryInfo) -> void { | |||
2968 | SourceLocation Loc; | |||
2969 | if (Kind != llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_LINK_ERROR) { | |||
2970 | for (auto I = CGM.getContext().getSourceManager().fileinfo_begin(), | |||
2971 | E = CGM.getContext().getSourceManager().fileinfo_end(); | |||
2972 | I != E; ++I) { | |||
2973 | if (I->getFirst()->getUniqueID().getDevice() == EntryInfo.DeviceID && | |||
2974 | I->getFirst()->getUniqueID().getFile() == EntryInfo.FileID) { | |||
2975 | Loc = CGM.getContext().getSourceManager().translateFileLineCol( | |||
2976 | I->getFirst(), EntryInfo.Line, 1); | |||
2977 | break; | |||
2978 | } | |||
2979 | } | |||
2980 | } | |||
2981 | switch (Kind) { | |||
2982 | case llvm::OpenMPIRBuilder::EMIT_MD_TARGET_REGION_ERROR: { | |||
2983 | unsigned DiagID = CGM.getDiags().getCustomDiagID( | |||
2984 | DiagnosticsEngine::Error, "Offloading entry for target region in " | |||
2985 | "%0 is incorrect: either the " | |||
2986 | "address or the ID is invalid."); | |||
2987 | CGM.getDiags().Report(Loc, DiagID) << EntryInfo.ParentName; | |||
2988 | } break; | |||
2989 | case llvm::OpenMPIRBuilder::EMIT_MD_DECLARE_TARGET_ERROR: { | |||
2990 | unsigned DiagID = CGM.getDiags().getCustomDiagID( | |||
2991 | DiagnosticsEngine::Error, "Offloading entry for declare target " | |||
2992 | "variable %0 is incorrect: the " | |||
2993 | "address is invalid."); | |||
2994 | CGM.getDiags().Report(Loc, DiagID) << EntryInfo.ParentName; | |||
2995 | } break; | |||
2996 | case llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_LINK_ERROR: { | |||
2997 | unsigned DiagID = CGM.getDiags().getCustomDiagID( | |||
2998 | DiagnosticsEngine::Error, | |||
2999 | "Offloading entry for declare target variable is incorrect: the " | |||
3000 | "address is invalid."); | |||
3001 | CGM.getDiags().Report(DiagID); | |||
3002 | } break; | |||
3003 | } | |||
3004 | }; | |||
3005 | ||||
3006 | OMPBuilder.createOffloadEntriesAndInfoMetadata(ErrorReportFn); | |||
3007 | } | |||
3008 | ||||
3009 | /// Loads all the offload entries information from the host IR | |||
3010 | /// metadata. | |||
3011 | void CGOpenMPRuntime::loadOffloadInfoMetadata() { | |||
3012 | // If we are in target mode, load the metadata from the host IR. This code has | |||
3013 | // to match the metadaata creation in createOffloadEntriesAndInfoMetadata(). | |||
3014 | ||||
3015 | if (!CGM.getLangOpts().OpenMPIsDevice) | |||
3016 | return; | |||
3017 | ||||
3018 | if (CGM.getLangOpts().OMPHostIRFile.empty()) | |||
3019 | return; | |||
3020 | ||||
3021 | auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile); | |||
3022 | if (auto EC = Buf.getError()) { | |||
3023 | CGM.getDiags().Report(diag::err_cannot_open_file) | |||
3024 | << CGM.getLangOpts().OMPHostIRFile << EC.message(); | |||
3025 | return; | |||
3026 | } | |||
3027 | ||||
3028 | llvm::LLVMContext C; | |||
3029 | auto ME = expectedToErrorOrAndEmitErrors( | |||
3030 | C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C)); | |||
3031 | ||||
3032 | if (auto EC = ME.getError()) { | |||
3033 | unsigned DiagID = CGM.getDiags().getCustomDiagID( | |||
3034 | DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'"); | |||
3035 | CGM.getDiags().Report(DiagID) | |||
3036 | << CGM.getLangOpts().OMPHostIRFile << EC.message(); | |||
3037 | return; | |||
3038 | } | |||
3039 | ||||
3040 | OMPBuilder.loadOffloadInfoMetadata(*ME.get()); | |||
3041 | } | |||
3042 | ||||
3043 | void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) { | |||
3044 | if (!KmpRoutineEntryPtrTy) { | |||
3045 | // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type. | |||
3046 | ASTContext &C = CGM.getContext(); | |||
3047 | QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy}; | |||
3048 | FunctionProtoType::ExtProtoInfo EPI; | |||
3049 | KmpRoutineEntryPtrQTy = C.getPointerType( | |||
3050 | C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI)); | |||
3051 | KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy); | |||
3052 | } | |||
3053 | } | |||
3054 | ||||
3055 | namespace { | |||
3056 | struct PrivateHelpersTy { | |||
3057 | PrivateHelpersTy(const Expr *OriginalRef, const VarDecl *Original, | |||
3058 | const VarDecl *PrivateCopy, const VarDecl *PrivateElemInit) | |||
3059 | : OriginalRef(OriginalRef), Original(Original), PrivateCopy(PrivateCopy), | |||
3060 | PrivateElemInit(PrivateElemInit) {} | |||
3061 | PrivateHelpersTy(const VarDecl *Original) : Original(Original) {} | |||
3062 | const Expr *OriginalRef = nullptr; | |||
3063 | const VarDecl *Original = nullptr; | |||
3064 | const VarDecl *PrivateCopy = nullptr; | |||
3065 | const VarDecl *PrivateElemInit = nullptr; | |||
3066 | bool isLocalPrivate() const { | |||
3067 | return !OriginalRef && !PrivateCopy && !PrivateElemInit; | |||
3068 | } | |||
3069 | }; | |||
3070 | typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy; | |||
3071 | } // anonymous namespace | |||
3072 | ||||
3073 | static bool isAllocatableDecl(const VarDecl *VD) { | |||
3074 | const VarDecl *CVD = VD->getCanonicalDecl(); | |||
3075 | if (!CVD->hasAttr<OMPAllocateDeclAttr>()) | |||
3076 | return false; | |||
3077 | const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>(); | |||
3078 | // Use the default allocation. | |||
3079 | return !(AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc && | |||
3080 | !AA->getAllocator()); | |||
3081 | } | |||
3082 | ||||
3083 | static RecordDecl * | |||
3084 | createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) { | |||
3085 | if (!Privates.empty()) { | |||
3086 | ASTContext &C = CGM.getContext(); | |||
3087 | // Build struct .kmp_privates_t. { | |||
3088 | // /* private vars */ | |||
3089 | // }; | |||
3090 | RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t"); | |||
3091 | RD->startDefinition(); | |||
3092 | for (const auto &Pair : Privates) { | |||
3093 | const VarDecl *VD = Pair.second.Original; | |||
3094 | QualType Type = VD->getType().getNonReferenceType(); | |||
3095 | // If the private variable is a local variable with lvalue ref type, | |||
3096 | // allocate the pointer instead of the pointee type. | |||
3097 | if (Pair.second.isLocalPrivate()) { | |||
3098 | if (VD->getType()->isLValueReferenceType()) | |||
3099 | Type = C.getPointerType(Type); | |||
3100 | if (isAllocatableDecl(VD)) | |||
3101 | Type = C.getPointerType(Type); | |||
3102 | } | |||
3103 | FieldDecl *FD = addFieldToRecordDecl(C, RD, Type); | |||
3104 | if (VD->hasAttrs()) { | |||
3105 | for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()), | |||
3106 | E(VD->getAttrs().end()); | |||
3107 | I != E; ++I) | |||
3108 | FD->addAttr(*I); | |||
3109 | } | |||
3110 | } | |||
3111 | RD->completeDefinition(); | |||
3112 | return RD; | |||
3113 | } | |||
3114 | return nullptr; | |||
3115 | } | |||
3116 | ||||
3117 | static RecordDecl * | |||
3118 | createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind, | |||
3119 | QualType KmpInt32Ty, | |||
3120 | QualType KmpRoutineEntryPointerQTy) { | |||
3121 | ASTContext &C = CGM.getContext(); | |||
3122 | // Build struct kmp_task_t { | |||
3123 | // void * shareds; | |||
3124 | // kmp_routine_entry_t routine; | |||
3125 | // kmp_int32 part_id; | |||
3126 | // kmp_cmplrdata_t data1; | |||
3127 | // kmp_cmplrdata_t data2; | |||
3128 | // For taskloops additional fields: | |||
3129 | // kmp_uint64 lb; | |||
3130 | // kmp_uint64 ub; | |||
3131 | // kmp_int64 st; | |||
3132 | // kmp_int32 liter; | |||
3133 | // void * reductions; | |||
3134 | // }; | |||
3135 | RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union); | |||
3136 | UD->startDefinition(); | |||
3137 | addFieldToRecordDecl(C, UD, KmpInt32Ty); | |||
3138 | addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy); | |||
3139 | UD->completeDefinition(); | |||
3140 | QualType KmpCmplrdataTy = C.getRecordType(UD); | |||
3141 | RecordDecl *RD = C.buildImplicitRecord("kmp_task_t"); | |||
3142 | RD->startDefinition(); | |||
3143 | addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
3144 | addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy); | |||
3145 | addFieldToRecordDecl(C, RD, KmpInt32Ty); | |||
3146 | addFieldToRecordDecl(C, RD, KmpCmplrdataTy); | |||
3147 | addFieldToRecordDecl(C, RD, KmpCmplrdataTy); | |||
3148 | if (isOpenMPTaskLoopDirective(Kind)) { | |||
3149 | QualType KmpUInt64Ty = | |||
3150 | CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); | |||
3151 | QualType KmpInt64Ty = | |||
3152 | CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); | |||
3153 | addFieldToRecordDecl(C, RD, KmpUInt64Ty); | |||
3154 | addFieldToRecordDecl(C, RD, KmpUInt64Ty); | |||
3155 | addFieldToRecordDecl(C, RD, KmpInt64Ty); | |||
3156 | addFieldToRecordDecl(C, RD, KmpInt32Ty); | |||
3157 | addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
3158 | } | |||
3159 | RD->completeDefinition(); | |||
3160 | return RD; | |||
3161 | } | |||
3162 | ||||
3163 | static RecordDecl * | |||
3164 | createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy, | |||
3165 | ArrayRef<PrivateDataTy> Privates) { | |||
3166 | ASTContext &C = CGM.getContext(); | |||
3167 | // Build struct kmp_task_t_with_privates { | |||
3168 | // kmp_task_t task_data; | |||
3169 | // .kmp_privates_t. privates; | |||
3170 | // }; | |||
3171 | RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates"); | |||
3172 | RD->startDefinition(); | |||
3173 | addFieldToRecordDecl(C, RD, KmpTaskTQTy); | |||
3174 | if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) | |||
3175 | addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD)); | |||
3176 | RD->completeDefinition(); | |||
3177 | return RD; | |||
3178 | } | |||
3179 | ||||
3180 | /// Emit a proxy function which accepts kmp_task_t as the second | |||
3181 | /// argument. | |||
3182 | /// \code | |||
3183 | /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { | |||
3184 | /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt, | |||
3185 | /// For taskloops: | |||
3186 | /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter, | |||
3187 | /// tt->reductions, tt->shareds); | |||
3188 | /// return 0; | |||
3189 | /// } | |||
3190 | /// \endcode | |||
3191 | static llvm::Function * | |||
3192 | emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc, | |||
3193 | OpenMPDirectiveKind Kind, QualType KmpInt32Ty, | |||
3194 | QualType KmpTaskTWithPrivatesPtrQTy, | |||
3195 | QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy, | |||
3196 | QualType SharedsPtrTy, llvm::Function *TaskFunction, | |||
3197 | llvm::Value *TaskPrivatesMap) { | |||
3198 | ASTContext &C = CGM.getContext(); | |||
3199 | FunctionArgList Args; | |||
3200 | ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty, | |||
3201 | ImplicitParamDecl::Other); | |||
3202 | ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3203 | KmpTaskTWithPrivatesPtrQTy.withRestrict(), | |||
3204 | ImplicitParamDecl::Other); | |||
3205 | Args.push_back(&GtidArg); | |||
3206 | Args.push_back(&TaskTypeArg); | |||
3207 | const auto &TaskEntryFnInfo = | |||
3208 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args); | |||
3209 | llvm::FunctionType *TaskEntryTy = | |||
3210 | CGM.getTypes().GetFunctionType(TaskEntryFnInfo); | |||
3211 | std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""}); | |||
3212 | auto *TaskEntry = llvm::Function::Create( | |||
3213 | TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); | |||
3214 | CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo); | |||
3215 | TaskEntry->setDoesNotRecurse(); | |||
3216 | CodeGenFunction CGF(CGM); | |||
3217 | CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args, | |||
3218 | Loc, Loc); | |||
3219 | ||||
3220 | // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map, | |||
3221 | // tt, | |||
3222 | // For taskloops: | |||
3223 | // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter, | |||
3224 | // tt->task_data.shareds); | |||
3225 | llvm::Value *GtidParam = CGF.EmitLoadOfScalar( | |||
3226 | CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc); | |||
3227 | LValue TDBase = CGF.EmitLoadOfPointerLValue( | |||
3228 | CGF.GetAddrOfLocalVar(&TaskTypeArg), | |||
3229 | KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); | |||
3230 | const auto *KmpTaskTWithPrivatesQTyRD = | |||
3231 | cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl()); | |||
3232 | LValue Base = | |||
3233 | CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3234 | const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl()); | |||
3235 | auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId); | |||
3236 | LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI); | |||
3237 | llvm::Value *PartidParam = PartIdLVal.getPointer(CGF); | |||
3238 | ||||
3239 | auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds); | |||
3240 | LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI); | |||
3241 | llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3242 | CGF.EmitLoadOfScalar(SharedsLVal, Loc), | |||
3243 | CGF.ConvertTypeForMem(SharedsPtrTy)); | |||
3244 | ||||
3245 | auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1); | |||
3246 | llvm::Value *PrivatesParam; | |||
3247 | if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) { | |||
3248 | LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI); | |||
3249 | PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3250 | PrivatesLVal.getPointer(CGF), CGF.VoidPtrTy); | |||
3251 | } else { | |||
3252 | PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
3253 | } | |||
3254 | ||||
3255 | llvm::Value *CommonArgs[] = { | |||
3256 | GtidParam, PartidParam, PrivatesParam, TaskPrivatesMap, | |||
3257 | CGF.Builder | |||
3258 | .CreatePointerBitCastOrAddrSpaceCast(TDBase.getAddress(CGF), | |||
3259 | CGF.VoidPtrTy, CGF.Int8Ty) | |||
3260 | .getPointer()}; | |||
3261 | SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs), | |||
3262 | std::end(CommonArgs)); | |||
3263 | if (isOpenMPTaskLoopDirective(Kind)) { | |||
3264 | auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound); | |||
3265 | LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI); | |||
3266 | llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc); | |||
3267 | auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound); | |||
3268 | LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI); | |||
3269 | llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc); | |||
3270 | auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride); | |||
3271 | LValue StLVal = CGF.EmitLValueForField(Base, *StFI); | |||
3272 | llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc); | |||
3273 | auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter); | |||
3274 | LValue LILVal = CGF.EmitLValueForField(Base, *LIFI); | |||
3275 | llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc); | |||
3276 | auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions); | |||
3277 | LValue RLVal = CGF.EmitLValueForField(Base, *RFI); | |||
3278 | llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc); | |||
3279 | CallArgs.push_back(LBParam); | |||
3280 | CallArgs.push_back(UBParam); | |||
3281 | CallArgs.push_back(StParam); | |||
3282 | CallArgs.push_back(LIParam); | |||
3283 | CallArgs.push_back(RParam); | |||
3284 | } | |||
3285 | CallArgs.push_back(SharedsParam); | |||
3286 | ||||
3287 | CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction, | |||
3288 | CallArgs); | |||
3289 | CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)), | |||
3290 | CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty)); | |||
3291 | CGF.FinishFunction(); | |||
3292 | return TaskEntry; | |||
3293 | } | |||
3294 | ||||
3295 | static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM, | |||
3296 | SourceLocation Loc, | |||
3297 | QualType KmpInt32Ty, | |||
3298 | QualType KmpTaskTWithPrivatesPtrQTy, | |||
3299 | QualType KmpTaskTWithPrivatesQTy) { | |||
3300 | ASTContext &C = CGM.getContext(); | |||
3301 | FunctionArgList Args; | |||
3302 | ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty, | |||
3303 | ImplicitParamDecl::Other); | |||
3304 | ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3305 | KmpTaskTWithPrivatesPtrQTy.withRestrict(), | |||
3306 | ImplicitParamDecl::Other); | |||
3307 | Args.push_back(&GtidArg); | |||
3308 | Args.push_back(&TaskTypeArg); | |||
3309 | const auto &DestructorFnInfo = | |||
3310 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args); | |||
3311 | llvm::FunctionType *DestructorFnTy = | |||
3312 | CGM.getTypes().GetFunctionType(DestructorFnInfo); | |||
3313 | std::string Name = | |||
3314 | CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""}); | |||
3315 | auto *DestructorFn = | |||
3316 | llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage, | |||
3317 | Name, &CGM.getModule()); | |||
3318 | CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn, | |||
3319 | DestructorFnInfo); | |||
3320 | DestructorFn->setDoesNotRecurse(); | |||
3321 | CodeGenFunction CGF(CGM); | |||
3322 | CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo, | |||
3323 | Args, Loc, Loc); | |||
3324 | ||||
3325 | LValue Base = CGF.EmitLoadOfPointerLValue( | |||
3326 | CGF.GetAddrOfLocalVar(&TaskTypeArg), | |||
3327 | KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); | |||
3328 | const auto *KmpTaskTWithPrivatesQTyRD = | |||
3329 | cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl()); | |||
3330 | auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3331 | Base = CGF.EmitLValueForField(Base, *FI); | |||
3332 | for (const auto *Field : | |||
3333 | cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) { | |||
3334 | if (QualType::DestructionKind DtorKind = | |||
3335 | Field->getType().isDestructedType()) { | |||
3336 | LValue FieldLValue = CGF.EmitLValueForField(Base, Field); | |||
3337 | CGF.pushDestroy(DtorKind, FieldLValue.getAddress(CGF), Field->getType()); | |||
3338 | } | |||
3339 | } | |||
3340 | CGF.FinishFunction(); | |||
3341 | return DestructorFn; | |||
3342 | } | |||
3343 | ||||
3344 | /// Emit a privates mapping function for correct handling of private and | |||
3345 | /// firstprivate variables. | |||
3346 | /// \code | |||
3347 | /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1> | |||
3348 | /// **noalias priv1,..., <tyn> **noalias privn) { | |||
3349 | /// *priv1 = &.privates.priv1; | |||
3350 | /// ...; | |||
3351 | /// *privn = &.privates.privn; | |||
3352 | /// } | |||
3353 | /// \endcode | |||
3354 | static llvm::Value * | |||
3355 | emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc, | |||
3356 | const OMPTaskDataTy &Data, QualType PrivatesQTy, | |||
3357 | ArrayRef<PrivateDataTy> Privates) { | |||
3358 | ASTContext &C = CGM.getContext(); | |||
3359 | FunctionArgList Args; | |||
3360 | ImplicitParamDecl TaskPrivatesArg( | |||
3361 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3362 | C.getPointerType(PrivatesQTy).withConst().withRestrict(), | |||
3363 | ImplicitParamDecl::Other); | |||
3364 | Args.push_back(&TaskPrivatesArg); | |||
3365 | llvm::DenseMap<CanonicalDeclPtr<const VarDecl>, unsigned> PrivateVarsPos; | |||
3366 | unsigned Counter = 1; | |||
3367 | for (const Expr *E : Data.PrivateVars) { | |||
3368 | Args.push_back(ImplicitParamDecl::Create( | |||
3369 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3370 | C.getPointerType(C.getPointerType(E->getType())) | |||
3371 | .withConst() | |||
3372 | .withRestrict(), | |||
3373 | ImplicitParamDecl::Other)); | |||
3374 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3375 | PrivateVarsPos[VD] = Counter; | |||
3376 | ++Counter; | |||
3377 | } | |||
3378 | for (const Expr *E : Data.FirstprivateVars) { | |||
3379 | Args.push_back(ImplicitParamDecl::Create( | |||
3380 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3381 | C.getPointerType(C.getPointerType(E->getType())) | |||
3382 | .withConst() | |||
3383 | .withRestrict(), | |||
3384 | ImplicitParamDecl::Other)); | |||
3385 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3386 | PrivateVarsPos[VD] = Counter; | |||
3387 | ++Counter; | |||
3388 | } | |||
3389 | for (const Expr *E : Data.LastprivateVars) { | |||
3390 | Args.push_back(ImplicitParamDecl::Create( | |||
3391 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3392 | C.getPointerType(C.getPointerType(E->getType())) | |||
3393 | .withConst() | |||
3394 | .withRestrict(), | |||
3395 | ImplicitParamDecl::Other)); | |||
3396 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3397 | PrivateVarsPos[VD] = Counter; | |||
3398 | ++Counter; | |||
3399 | } | |||
3400 | for (const VarDecl *VD : Data.PrivateLocals) { | |||
3401 | QualType Ty = VD->getType().getNonReferenceType(); | |||
3402 | if (VD->getType()->isLValueReferenceType()) | |||
3403 | Ty = C.getPointerType(Ty); | |||
3404 | if (isAllocatableDecl(VD)) | |||
3405 | Ty = C.getPointerType(Ty); | |||
3406 | Args.push_back(ImplicitParamDecl::Create( | |||
3407 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3408 | C.getPointerType(C.getPointerType(Ty)).withConst().withRestrict(), | |||
3409 | ImplicitParamDecl::Other)); | |||
3410 | PrivateVarsPos[VD] = Counter; | |||
3411 | ++Counter; | |||
3412 | } | |||
3413 | const auto &TaskPrivatesMapFnInfo = | |||
3414 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
3415 | llvm::FunctionType *TaskPrivatesMapTy = | |||
3416 | CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo); | |||
3417 | std::string Name = | |||
3418 | CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""}); | |||
3419 | auto *TaskPrivatesMap = llvm::Function::Create( | |||
3420 | TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name, | |||
3421 | &CGM.getModule()); | |||
3422 | CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap, | |||
3423 | TaskPrivatesMapFnInfo); | |||
3424 | if (CGM.getLangOpts().Optimize) { | |||
3425 | TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline); | |||
3426 | TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone); | |||
3427 | TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline); | |||
3428 | } | |||
3429 | CodeGenFunction CGF(CGM); | |||
3430 | CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap, | |||
3431 | TaskPrivatesMapFnInfo, Args, Loc, Loc); | |||
3432 | ||||
3433 | // *privi = &.privates.privi; | |||
3434 | LValue Base = CGF.EmitLoadOfPointerLValue( | |||
3435 | CGF.GetAddrOfLocalVar(&TaskPrivatesArg), | |||
3436 | TaskPrivatesArg.getType()->castAs<PointerType>()); | |||
3437 | const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl()); | |||
3438 | Counter = 0; | |||
3439 | for (const FieldDecl *Field : PrivatesQTyRD->fields()) { | |||
3440 | LValue FieldLVal = CGF.EmitLValueForField(Base, Field); | |||
3441 | const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]]; | |||
3442 | LValue RefLVal = | |||
3443 | CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType()); | |||
3444 | LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue( | |||
3445 | RefLVal.getAddress(CGF), RefLVal.getType()->castAs<PointerType>()); | |||
3446 | CGF.EmitStoreOfScalar(FieldLVal.getPointer(CGF), RefLoadLVal); | |||
3447 | ++Counter; | |||
3448 | } | |||
3449 | CGF.FinishFunction(); | |||
3450 | return TaskPrivatesMap; | |||
3451 | } | |||
3452 | ||||
3453 | /// Emit initialization for private variables in task-based directives. | |||
3454 | static void emitPrivatesInit(CodeGenFunction &CGF, | |||
3455 | const OMPExecutableDirective &D, | |||
3456 | Address KmpTaskSharedsPtr, LValue TDBase, | |||
3457 | const RecordDecl *KmpTaskTWithPrivatesQTyRD, | |||
3458 | QualType SharedsTy, QualType SharedsPtrTy, | |||
3459 | const OMPTaskDataTy &Data, | |||
3460 | ArrayRef<PrivateDataTy> Privates, bool ForDup) { | |||
3461 | ASTContext &C = CGF.getContext(); | |||
3462 | auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3463 | LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI); | |||
3464 | OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind()) | |||
3465 | ? OMPD_taskloop | |||
3466 | : OMPD_task; | |||
3467 | const CapturedStmt &CS = *D.getCapturedStmt(Kind); | |||
3468 | CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS); | |||
3469 | LValue SrcBase; | |||
3470 | bool IsTargetTask = | |||
3471 | isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) || | |||
3472 | isOpenMPTargetExecutionDirective(D.getDirectiveKind()); | |||
3473 | // For target-based directives skip 4 firstprivate arrays BasePointersArray, | |||
3474 | // PointersArray, SizesArray, and MappersArray. The original variables for | |||
3475 | // these arrays are not captured and we get their addresses explicitly. | |||
3476 | if ((!IsTargetTask && !Data.FirstprivateVars.empty() && ForDup) || | |||
3477 | (IsTargetTask && KmpTaskSharedsPtr.isValid())) { | |||
3478 | SrcBase = CGF.MakeAddrLValue( | |||
3479 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3480 | KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy), | |||
3481 | CGF.ConvertTypeForMem(SharedsTy)), | |||
3482 | SharedsTy); | |||
3483 | } | |||
3484 | FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin(); | |||
3485 | for (const PrivateDataTy &Pair : Privates) { | |||
3486 | // Do not initialize private locals. | |||
3487 | if (Pair.second.isLocalPrivate()) { | |||
3488 | ++FI; | |||
3489 | continue; | |||
3490 | } | |||
3491 | const VarDecl *VD = Pair.second.PrivateCopy; | |||
3492 | const Expr *Init = VD->getAnyInitializer(); | |||
3493 | if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) && | |||
3494 | !CGF.isTrivialInitializer(Init)))) { | |||
3495 | LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI); | |||
3496 | if (const VarDecl *Elem = Pair.second.PrivateElemInit) { | |||
3497 | const VarDecl *OriginalVD = Pair.second.Original; | |||
3498 | // Check if the variable is the target-based BasePointersArray, | |||
3499 | // PointersArray, SizesArray, or MappersArray. | |||
3500 | LValue SharedRefLValue; | |||
3501 | QualType Type = PrivateLValue.getType(); | |||
3502 | const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD); | |||
3503 | if (IsTargetTask && !SharedField) { | |||
3504 | assert(isa<ImplicitParamDecl>(OriginalVD) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3511, __extension__ __PRETTY_FUNCTION__)) | |||
3505 | isa<CapturedDecl>(OriginalVD->getDeclContext()) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3511, __extension__ __PRETTY_FUNCTION__)) | |||
3506 | cast<CapturedDecl>(OriginalVD->getDeclContext())(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3511, __extension__ __PRETTY_FUNCTION__)) | |||
3507 | ->getNumParams() == 0 &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3511, __extension__ __PRETTY_FUNCTION__)) | |||
3508 | isa<TranslationUnitDecl>((static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3511, __extension__ __PRETTY_FUNCTION__)) | |||
3509 | cast<CapturedDecl>(OriginalVD->getDeclContext())(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3511, __extension__ __PRETTY_FUNCTION__)) | |||
3510 | ->getDeclContext()) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3511, __extension__ __PRETTY_FUNCTION__)) | |||
3511 | "Expected artificial target data variable.")(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3511, __extension__ __PRETTY_FUNCTION__)); | |||
3512 | SharedRefLValue = | |||
3513 | CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type); | |||
3514 | } else if (ForDup) { | |||
3515 | SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField); | |||
3516 | SharedRefLValue = CGF.MakeAddrLValue( | |||
3517 | SharedRefLValue.getAddress(CGF).withAlignment( | |||
3518 | C.getDeclAlign(OriginalVD)), | |||
3519 | SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl), | |||
3520 | SharedRefLValue.getTBAAInfo()); | |||
3521 | } else if (CGF.LambdaCaptureFields.count( | |||
3522 | Pair.second.Original->getCanonicalDecl()) > 0 || | |||
3523 | isa_and_nonnull<BlockDecl>(CGF.CurCodeDecl)) { | |||
3524 | SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef); | |||
3525 | } else { | |||
3526 | // Processing for implicitly captured variables. | |||
3527 | InlinedOpenMPRegionRAII Region( | |||
3528 | CGF, [](CodeGenFunction &, PrePostActionTy &) {}, OMPD_unknown, | |||
3529 | /*HasCancel=*/false, /*NoInheritance=*/true); | |||
3530 | SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef); | |||
3531 | } | |||
3532 | if (Type->isArrayType()) { | |||
3533 | // Initialize firstprivate array. | |||
3534 | if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) { | |||
3535 | // Perform simple memcpy. | |||
3536 | CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type); | |||
3537 | } else { | |||
3538 | // Initialize firstprivate array using element-by-element | |||
3539 | // initialization. | |||
3540 | CGF.EmitOMPAggregateAssign( | |||
3541 | PrivateLValue.getAddress(CGF), SharedRefLValue.getAddress(CGF), | |||
3542 | Type, | |||
3543 | [&CGF, Elem, Init, &CapturesInfo](Address DestElement, | |||
3544 | Address SrcElement) { | |||
3545 | // Clean up any temporaries needed by the initialization. | |||
3546 | CodeGenFunction::OMPPrivateScope InitScope(CGF); | |||
3547 | InitScope.addPrivate(Elem, SrcElement); | |||
3548 | (void)InitScope.Privatize(); | |||
3549 | // Emit initialization for single element. | |||
3550 | CodeGenFunction::CGCapturedStmtRAII CapInfoRAII( | |||
3551 | CGF, &CapturesInfo); | |||
3552 | CGF.EmitAnyExprToMem(Init, DestElement, | |||
3553 | Init->getType().getQualifiers(), | |||
3554 | /*IsInitializer=*/false); | |||
3555 | }); | |||
3556 | } | |||
3557 | } else { | |||
3558 | CodeGenFunction::OMPPrivateScope InitScope(CGF); | |||
3559 | InitScope.addPrivate(Elem, SharedRefLValue.getAddress(CGF)); | |||
3560 | (void)InitScope.Privatize(); | |||
3561 | CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo); | |||
3562 | CGF.EmitExprAsInit(Init, VD, PrivateLValue, | |||
3563 | /*capturedByInit=*/false); | |||
3564 | } | |||
3565 | } else { | |||
3566 | CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false); | |||
3567 | } | |||
3568 | } | |||
3569 | ++FI; | |||
3570 | } | |||
3571 | } | |||
3572 | ||||
3573 | /// Check if duplication function is required for taskloops. | |||
3574 | static bool checkInitIsRequired(CodeGenFunction &CGF, | |||
3575 | ArrayRef<PrivateDataTy> Privates) { | |||
3576 | bool InitRequired = false; | |||
3577 | for (const PrivateDataTy &Pair : Privates) { | |||
3578 | if (Pair.second.isLocalPrivate()) | |||
3579 | continue; | |||
3580 | const VarDecl *VD = Pair.second.PrivateCopy; | |||
3581 | const Expr *Init = VD->getAnyInitializer(); | |||
3582 | InitRequired = InitRequired || (isa_and_nonnull<CXXConstructExpr>(Init) && | |||
3583 | !CGF.isTrivialInitializer(Init)); | |||
3584 | if (InitRequired) | |||
3585 | break; | |||
3586 | } | |||
3587 | return InitRequired; | |||
3588 | } | |||
3589 | ||||
3590 | ||||
3591 | /// Emit task_dup function (for initialization of | |||
3592 | /// private/firstprivate/lastprivate vars and last_iter flag) | |||
3593 | /// \code | |||
3594 | /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int | |||
3595 | /// lastpriv) { | |||
3596 | /// // setup lastprivate flag | |||
3597 | /// task_dst->last = lastpriv; | |||
3598 | /// // could be constructor calls here... | |||
3599 | /// } | |||
3600 | /// \endcode | |||
3601 | static llvm::Value * | |||
3602 | emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc, | |||
3603 | const OMPExecutableDirective &D, | |||
3604 | QualType KmpTaskTWithPrivatesPtrQTy, | |||
3605 | const RecordDecl *KmpTaskTWithPrivatesQTyRD, | |||
3606 | const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy, | |||
3607 | QualType SharedsPtrTy, const OMPTaskDataTy &Data, | |||
3608 | ArrayRef<PrivateDataTy> Privates, bool WithLastIter) { | |||
3609 | ASTContext &C = CGM.getContext(); | |||
3610 | FunctionArgList Args; | |||
3611 | ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3612 | KmpTaskTWithPrivatesPtrQTy, | |||
3613 | ImplicitParamDecl::Other); | |||
3614 | ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3615 | KmpTaskTWithPrivatesPtrQTy, | |||
3616 | ImplicitParamDecl::Other); | |||
3617 | ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy, | |||
3618 | ImplicitParamDecl::Other); | |||
3619 | Args.push_back(&DstArg); | |||
3620 | Args.push_back(&SrcArg); | |||
3621 | Args.push_back(&LastprivArg); | |||
3622 | const auto &TaskDupFnInfo = | |||
3623 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
3624 | llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo); | |||
3625 | std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""}); | |||
3626 | auto *TaskDup = llvm::Function::Create( | |||
3627 | TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); | |||
3628 | CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo); | |||
3629 | TaskDup->setDoesNotRecurse(); | |||
3630 | CodeGenFunction CGF(CGM); | |||
3631 | CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc, | |||
3632 | Loc); | |||
3633 | ||||
3634 | LValue TDBase = CGF.EmitLoadOfPointerLValue( | |||
3635 | CGF.GetAddrOfLocalVar(&DstArg), | |||
3636 | KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); | |||
3637 | // task_dst->liter = lastpriv; | |||
3638 | if (WithLastIter) { | |||
3639 | auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter); | |||
3640 | LValue Base = CGF.EmitLValueForField( | |||
3641 | TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3642 | LValue LILVal = CGF.EmitLValueForField(Base, *LIFI); | |||
3643 | llvm::Value *Lastpriv = CGF.EmitLoadOfScalar( | |||
3644 | CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc); | |||
3645 | CGF.EmitStoreOfScalar(Lastpriv, LILVal); | |||
3646 | } | |||
3647 | ||||
3648 | // Emit initial values for private copies (if any). | |||
3649 | assert(!Privates.empty())(static_cast <bool> (!Privates.empty()) ? void (0) : __assert_fail ("!Privates.empty()", "clang/lib/CodeGen/CGOpenMPRuntime.cpp" , 3649, __extension__ __PRETTY_FUNCTION__)); | |||
3650 | Address KmpTaskSharedsPtr = Address::invalid(); | |||
3651 | if (!Data.FirstprivateVars.empty()) { | |||
3652 | LValue TDBase = CGF.EmitLoadOfPointerLValue( | |||
3653 | CGF.GetAddrOfLocalVar(&SrcArg), | |||
3654 | KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); | |||
3655 | LValue Base = CGF.EmitLValueForField( | |||
3656 | TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3657 | KmpTaskSharedsPtr = Address( | |||
3658 | CGF.EmitLoadOfScalar(CGF.EmitLValueForField( | |||
3659 | Base, *std::next(KmpTaskTQTyRD->field_begin(), | |||
3660 | KmpTaskTShareds)), | |||
3661 | Loc), | |||
3662 | CGF.Int8Ty, CGM.getNaturalTypeAlignment(SharedsTy)); | |||
3663 | } | |||
3664 | emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD, | |||
3665 | SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true); | |||
3666 | CGF.FinishFunction(); | |||
3667 | return TaskDup; | |||
3668 | } | |||
3669 | ||||
3670 | /// Checks if destructor function is required to be generated. | |||
3671 | /// \return true if cleanups are required, false otherwise. | |||
3672 | static bool | |||
3673 | checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD, | |||
3674 | ArrayRef<PrivateDataTy> Privates) { | |||
3675 | for (const PrivateDataTy &P : Privates) { | |||
3676 | if (P.second.isLocalPrivate()) | |||
3677 | continue; | |||
3678 | QualType Ty = P.second.Original->getType().getNonReferenceType(); | |||
3679 | if (Ty.isDestructedType()) | |||
3680 | return true; | |||
3681 | } | |||
3682 | return false; | |||
3683 | } | |||
3684 | ||||
3685 | namespace { | |||
3686 | /// Loop generator for OpenMP iterator expression. | |||
3687 | class OMPIteratorGeneratorScope final | |||
3688 | : public CodeGenFunction::OMPPrivateScope { | |||
3689 | CodeGenFunction &CGF; | |||
3690 | const OMPIteratorExpr *E = nullptr; | |||
3691 | SmallVector<CodeGenFunction::JumpDest, 4> ContDests; | |||
3692 | SmallVector<CodeGenFunction::JumpDest, 4> ExitDests; | |||
3693 | OMPIteratorGeneratorScope() = delete; | |||
3694 | OMPIteratorGeneratorScope(OMPIteratorGeneratorScope &) = delete; | |||
3695 | ||||
3696 | public: | |||
3697 | OMPIteratorGeneratorScope(CodeGenFunction &CGF, const OMPIteratorExpr *E) | |||
3698 | : CodeGenFunction::OMPPrivateScope(CGF), CGF(CGF), E(E) { | |||
3699 | if (!E) | |||
3700 | return; | |||
3701 | SmallVector<llvm::Value *, 4> Uppers; | |||
3702 | for (unsigned I = 0, End = E->numOfIterators(); I < End; ++I) { | |||
3703 | Uppers.push_back(CGF.EmitScalarExpr(E->getHelper(I).Upper)); | |||
3704 | const auto *VD = cast<VarDecl>(E->getIteratorDecl(I)); | |||
3705 | addPrivate(VD, CGF.CreateMemTemp(VD->getType(), VD->getName())); | |||
3706 | const OMPIteratorHelperData &HelperData = E->getHelper(I); | |||
3707 | addPrivate( | |||
3708 | HelperData.CounterVD, | |||
3709 | CGF.CreateMemTemp(HelperData.CounterVD->getType(), "counter.addr")); | |||
3710 | } | |||
3711 | Privatize(); | |||
3712 | ||||
3713 | for (unsigned I = 0, End = E->numOfIterators(); I < End; ++I) { | |||
3714 | const OMPIteratorHelperData &HelperData = E->getHelper(I); | |||
3715 | LValue CLVal = | |||
3716 | CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(HelperData.CounterVD), | |||
3717 | HelperData.CounterVD->getType()); | |||
3718 | // Counter = 0; | |||
3719 | CGF.EmitStoreOfScalar( | |||
3720 | llvm::ConstantInt::get(CLVal.getAddress(CGF).getElementType(), 0), | |||
3721 | CLVal); | |||
3722 | CodeGenFunction::JumpDest &ContDest = | |||
3723 | ContDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.cont")); | |||
3724 | CodeGenFunction::JumpDest &ExitDest = | |||
3725 | ExitDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.exit")); | |||
3726 | // N = <number-of_iterations>; | |||
3727 | llvm::Value *N = Uppers[I]; | |||
3728 | // cont: | |||
3729 | // if (Counter < N) goto body; else goto exit; | |||
3730 | CGF.EmitBlock(ContDest.getBlock()); | |||
3731 | auto *CVal = | |||
3732 | CGF.EmitLoadOfScalar(CLVal, HelperData.CounterVD->getLocation()); | |||
3733 | llvm::Value *Cmp = | |||
3734 | HelperData.CounterVD->getType()->isSignedIntegerOrEnumerationType() | |||
3735 | ? CGF.Builder.CreateICmpSLT(CVal, N) | |||
3736 | : CGF.Builder.CreateICmpULT(CVal, N); | |||
3737 | llvm::BasicBlock *BodyBB = CGF.createBasicBlock("iter.body"); | |||
3738 | CGF.Builder.CreateCondBr(Cmp, BodyBB, ExitDest.getBlock()); | |||
3739 | // body: | |||
3740 | CGF.EmitBlock(BodyBB); | |||
3741 | // Iteri = Begini + Counter * Stepi; | |||
3742 | CGF.EmitIgnoredExpr(HelperData.Update); | |||
3743 | } | |||
3744 | } | |||
3745 | ~OMPIteratorGeneratorScope() { | |||
3746 | if (!E) | |||
3747 | return; | |||
3748 | for (unsigned I = E->numOfIterators(); I > 0; --I) { | |||
3749 | // Counter = Counter + 1; | |||
3750 | const OMPIteratorHelperData &HelperData = E->getHelper(I - 1); | |||
3751 | CGF.EmitIgnoredExpr(HelperData.CounterUpdate); | |||
3752 | // goto cont; | |||
3753 | CGF.EmitBranchThroughCleanup(ContDests[I - 1]); | |||
3754 | // exit: | |||
3755 | CGF.EmitBlock(ExitDests[I - 1].getBlock(), /*IsFinished=*/I == 1); | |||
3756 | } | |||
3757 | } | |||
3758 | }; | |||
3759 | } // namespace | |||
3760 | ||||
3761 | static std::pair<llvm::Value *, llvm::Value *> | |||
3762 | getPointerAndSize(CodeGenFunction &CGF, const Expr *E) { | |||
3763 | const auto *OASE = dyn_cast<OMPArrayShapingExpr>(E); | |||
3764 | llvm::Value *Addr; | |||
3765 | if (OASE) { | |||
3766 | const Expr *Base = OASE->getBase(); | |||
3767 | Addr = CGF.EmitScalarExpr(Base); | |||
3768 | } else { | |||
3769 | Addr = CGF.EmitLValue(E).getPointer(CGF); | |||
3770 | } | |||
3771 | llvm::Value *SizeVal; | |||
3772 | QualType Ty = E->getType(); | |||
3773 | if (OASE) { | |||
3774 | SizeVal = CGF.getTypeSize(OASE->getBase()->getType()->getPointeeType()); | |||
3775 | for (const Expr *SE : OASE->getDimensions()) { | |||
3776 | llvm::Value *Sz = CGF.EmitScalarExpr(SE); | |||
3777 | Sz = CGF.EmitScalarConversion( | |||
3778 | Sz, SE->getType(), CGF.getContext().getSizeType(), SE->getExprLoc()); | |||
3779 | SizeVal = CGF.Builder.CreateNUWMul(SizeVal, Sz); | |||
3780 | } | |||
3781 | } else if (const auto *ASE = | |||
3782 | dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) { | |||
3783 | LValue UpAddrLVal = | |||
3784 | CGF.EmitOMPArraySectionExpr(ASE, /*IsLowerBound=*/false); | |||
3785 | Address UpAddrAddress = UpAddrLVal.getAddress(CGF); | |||
3786 | llvm::Value *UpAddr = CGF.Builder.CreateConstGEP1_32( | |||
3787 | UpAddrAddress.getElementType(), UpAddrAddress.getPointer(), /*Idx0=*/1); | |||
3788 | llvm::Value *LowIntPtr = CGF.Builder.CreatePtrToInt(Addr, CGF.SizeTy); | |||
3789 | llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGF.SizeTy); | |||
3790 | SizeVal = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr); | |||
3791 | } else { | |||
3792 | SizeVal = CGF.getTypeSize(Ty); | |||
3793 | } | |||
3794 | return std::make_pair(Addr, SizeVal); | |||
3795 | } | |||
3796 | ||||
3797 | /// Builds kmp_depend_info, if it is not built yet, and builds flags type. | |||
3798 | static void getKmpAffinityType(ASTContext &C, QualType &KmpTaskAffinityInfoTy) { | |||
3799 | QualType FlagsTy = C.getIntTypeForBitwidth(32, /*Signed=*/false); | |||
3800 | if (KmpTaskAffinityInfoTy.isNull()) { | |||
3801 | RecordDecl *KmpAffinityInfoRD = | |||
3802 | C.buildImplicitRecord("kmp_task_affinity_info_t"); | |||
3803 | KmpAffinityInfoRD->startDefinition(); | |||
3804 | addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getIntPtrType()); | |||
3805 | addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getSizeType()); | |||
3806 | addFieldToRecordDecl(C, KmpAffinityInfoRD, FlagsTy); | |||
3807 | KmpAffinityInfoRD->completeDefinition(); | |||
3808 | KmpTaskAffinityInfoTy = C.getRecordType(KmpAffinityInfoRD); | |||
3809 | } | |||
3810 | } | |||
3811 | ||||
3812 | CGOpenMPRuntime::TaskResultTy | |||
3813 | CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, | |||
3814 | const OMPExecutableDirective &D, | |||
3815 | llvm::Function *TaskFunction, QualType SharedsTy, | |||
3816 | Address Shareds, const OMPTaskDataTy &Data) { | |||
3817 | ASTContext &C = CGM.getContext(); | |||
3818 | llvm::SmallVector<PrivateDataTy, 4> Privates; | |||
3819 | // Aggregate privates and sort them by the alignment. | |||
3820 | const auto *I = Data.PrivateCopies.begin(); | |||
3821 | for (const Expr *E : Data.PrivateVars) { | |||
3822 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3823 | Privates.emplace_back( | |||
3824 | C.getDeclAlign(VD), | |||
3825 | PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), | |||
3826 | /*PrivateElemInit=*/nullptr)); | |||
3827 | ++I; | |||
3828 | } | |||
3829 | I = Data.FirstprivateCopies.begin(); | |||
3830 | const auto *IElemInitRef = Data.FirstprivateInits.begin(); | |||
3831 | for (const Expr *E : Data.FirstprivateVars) { | |||
3832 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3833 | Privates.emplace_back( | |||
3834 | C.getDeclAlign(VD), | |||
3835 | PrivateHelpersTy( | |||
3836 | E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), | |||
3837 | cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))); | |||
3838 | ++I; | |||
3839 | ++IElemInitRef; | |||
3840 | } | |||
3841 | I = Data.LastprivateCopies.begin(); | |||
3842 | for (const Expr *E : Data.LastprivateVars) { | |||
3843 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3844 | Privates.emplace_back( | |||
3845 | C.getDeclAlign(VD), | |||
3846 | PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), | |||
3847 | /*PrivateElemInit=*/nullptr)); | |||
3848 | ++I; | |||
3849 | } | |||
3850 | for (const VarDecl *VD : Data.PrivateLocals) { | |||
3851 | if (isAllocatableDecl(VD)) | |||
3852 | Privates.emplace_back(CGM.getPointerAlign(), PrivateHelpersTy(VD)); | |||
3853 | else | |||
3854 | Privates.emplace_back(C.getDeclAlign(VD), PrivateHelpersTy(VD)); | |||
3855 | } | |||
3856 | llvm::stable_sort(Privates, | |||
3857 | [](const PrivateDataTy &L, const PrivateDataTy &R) { | |||
3858 | return L.first > R.first; | |||
3859 | }); | |||
3860 | QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); | |||
3861 | // Build type kmp_routine_entry_t (if not built yet). | |||
3862 | emitKmpRoutineEntryT(KmpInt32Ty); | |||
3863 | // Build type kmp_task_t (if not built yet). | |||
3864 | if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) { | |||
3865 | if (SavedKmpTaskloopTQTy.isNull()) { | |||
3866 | SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl( | |||
3867 | CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy)); | |||
3868 | } | |||
3869 | KmpTaskTQTy = SavedKmpTaskloopTQTy; | |||
3870 | } else { | |||
3871 | assert((D.getDirectiveKind() == OMPD_task ||(static_cast <bool> ((D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && "Expected taskloop, task or target directive") ? void (0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3874, __extension__ __PRETTY_FUNCTION__)) | |||
3872 | isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||(static_cast <bool> ((D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && "Expected taskloop, task or target directive") ? void (0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3874, __extension__ __PRETTY_FUNCTION__)) | |||
3873 | isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&(static_cast <bool> ((D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && "Expected taskloop, task or target directive") ? void (0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3874, __extension__ __PRETTY_FUNCTION__)) | |||
3874 | "Expected taskloop, task or target directive")(static_cast <bool> ((D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && "Expected taskloop, task or target directive") ? void (0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3874, __extension__ __PRETTY_FUNCTION__)); | |||
3875 | if (SavedKmpTaskTQTy.isNull()) { | |||
3876 | SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl( | |||
3877 | CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy)); | |||
3878 | } | |||
3879 | KmpTaskTQTy = SavedKmpTaskTQTy; | |||
3880 | } | |||
3881 | const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl()); | |||
3882 | // Build particular struct kmp_task_t for the given task. | |||
3883 | const RecordDecl *KmpTaskTWithPrivatesQTyRD = | |||
3884 | createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates); | |||
3885 | QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD); | |||
3886 | QualType KmpTaskTWithPrivatesPtrQTy = | |||
3887 | C.getPointerType(KmpTaskTWithPrivatesQTy); | |||
3888 | llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy); | |||
3889 | llvm::Type *KmpTaskTWithPrivatesPtrTy = | |||
3890 | KmpTaskTWithPrivatesTy->getPointerTo(); | |||
3891 | llvm::Value *KmpTaskTWithPrivatesTySize = | |||
3892 | CGF.getTypeSize(KmpTaskTWithPrivatesQTy); | |||
3893 | QualType SharedsPtrTy = C.getPointerType(SharedsTy); | |||
3894 | ||||
3895 | // Emit initial values for private copies (if any). | |||
3896 | llvm::Value *TaskPrivatesMap = nullptr; | |||
3897 | llvm::Type *TaskPrivatesMapTy = | |||
3898 | std::next(TaskFunction->arg_begin(), 3)->getType(); | |||
3899 | if (!Privates.empty()) { | |||
3900 | auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3901 | TaskPrivatesMap = | |||
3902 | emitTaskPrivateMappingFunction(CGM, Loc, Data, FI->getType(), Privates); | |||
3903 | TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3904 | TaskPrivatesMap, TaskPrivatesMapTy); | |||
3905 | } else { | |||
3906 | TaskPrivatesMap = llvm::ConstantPointerNull::get( | |||
3907 | cast<llvm::PointerType>(TaskPrivatesMapTy)); | |||
3908 | } | |||
3909 | // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid, | |||
3910 | // kmp_task_t *tt); | |||
3911 | llvm::Function *TaskEntry = emitProxyTaskFunction( | |||
3912 | CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, | |||
3913 | KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction, | |||
3914 | TaskPrivatesMap); | |||
3915 | ||||
3916 | // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid, | |||
3917 | // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, | |||
3918 | // kmp_routine_entry_t *task_entry); | |||
3919 | // Task flags. Format is taken from | |||
3920 | // https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h, | |||
3921 | // description of kmp_tasking_flags struct. | |||
3922 | enum { | |||
3923 | TiedFlag = 0x1, | |||
3924 | FinalFlag = 0x2, | |||
3925 | DestructorsFlag = 0x8, | |||
3926 | PriorityFlag = 0x20, | |||
3927 | DetachableFlag = 0x40, | |||
3928 | }; | |||
3929 | unsigned Flags = Data.Tied ? TiedFlag : 0; | |||
3930 | bool NeedsCleanup = false; | |||
3931 | if (!Privates.empty()) { | |||
3932 | NeedsCleanup = | |||
3933 | checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD, Privates); | |||
3934 | if (NeedsCleanup) | |||
3935 | Flags = Flags | DestructorsFlag; | |||
3936 | } | |||
3937 | if (Data.Priority.getInt()) | |||
3938 | Flags = Flags | PriorityFlag; | |||
3939 | if (D.hasClausesOfKind<OMPDetachClause>()) | |||
3940 | Flags = Flags | DetachableFlag; | |||
3941 | llvm::Value *TaskFlags = | |||
3942 | Data.Final.getPointer() | |||
3943 | ? CGF.Builder.CreateSelect(Data.Final.getPointer(), | |||
3944 | CGF.Builder.getInt32(FinalFlag), | |||
3945 | CGF.Builder.getInt32(/*C=*/0)) | |||
3946 | : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0); | |||
3947 | TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags)); | |||
3948 | llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy)); | |||
3949 | SmallVector<llvm::Value *, 8> AllocArgs = {emitUpdateLocation(CGF, Loc), | |||
3950 | getThreadID(CGF, Loc), TaskFlags, KmpTaskTWithPrivatesTySize, | |||
3951 | SharedsSize, CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3952 | TaskEntry, KmpRoutineEntryPtrTy)}; | |||
3953 | llvm::Value *NewTask; | |||
3954 | if (D.hasClausesOfKind<OMPNowaitClause>()) { | |||
3955 | // Check if we have any device clause associated with the directive. | |||
3956 | const Expr *Device = nullptr; | |||
3957 | if (auto *C = D.getSingleClause<OMPDeviceClause>()) | |||
3958 | Device = C->getDevice(); | |||
3959 | // Emit device ID if any otherwise use default value. | |||
3960 | llvm::Value *DeviceID; | |||
3961 | if (Device) | |||
3962 | DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), | |||
3963 | CGF.Int64Ty, /*isSigned=*/true); | |||
3964 | else | |||
3965 | DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); | |||
3966 | AllocArgs.push_back(DeviceID); | |||
3967 | NewTask = CGF.EmitRuntimeCall( | |||
3968 | OMPBuilder.getOrCreateRuntimeFunction( | |||
3969 | CGM.getModule(), OMPRTL___kmpc_omp_target_task_alloc), | |||
3970 | AllocArgs); | |||
3971 | } else { | |||
3972 | NewTask = | |||
3973 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
3974 | CGM.getModule(), OMPRTL___kmpc_omp_task_alloc), | |||
3975 | AllocArgs); | |||
3976 | } | |||
3977 | // Emit detach clause initialization. | |||
3978 | // evt = (typeof(evt))__kmpc_task_allow_completion_event(loc, tid, | |||
3979 | // task_descriptor); | |||
3980 | if (const auto *DC = D.getSingleClause<OMPDetachClause>()) { | |||
3981 | const Expr *Evt = DC->getEventHandler()->IgnoreParenImpCasts(); | |||
3982 | LValue EvtLVal = CGF.EmitLValue(Evt); | |||
3983 | ||||
3984 | // Build kmp_event_t *__kmpc_task_allow_completion_event(ident_t *loc_ref, | |||
3985 | // int gtid, kmp_task_t *task); | |||
3986 | llvm::Value *Loc = emitUpdateLocation(CGF, DC->getBeginLoc()); | |||
3987 | llvm::Value *Tid = getThreadID(CGF, DC->getBeginLoc()); | |||
3988 | Tid = CGF.Builder.CreateIntCast(Tid, CGF.IntTy, /*isSigned=*/false); | |||
3989 | llvm::Value *EvtVal = CGF.EmitRuntimeCall( | |||
3990 | OMPBuilder.getOrCreateRuntimeFunction( | |||
3991 | CGM.getModule(), OMPRTL___kmpc_task_allow_completion_event), | |||
3992 | {Loc, Tid, NewTask}); | |||
3993 | EvtVal = CGF.EmitScalarConversion(EvtVal, C.VoidPtrTy, Evt->getType(), | |||
3994 | Evt->getExprLoc()); | |||
3995 | CGF.EmitStoreOfScalar(EvtVal, EvtLVal); | |||
3996 | } | |||
3997 | // Process affinity clauses. | |||
3998 | if (D.hasClausesOfKind<OMPAffinityClause>()) { | |||
3999 | // Process list of affinity data. | |||
4000 | ASTContext &C = CGM.getContext(); | |||
4001 | Address AffinitiesArray = Address::invalid(); | |||
4002 | // Calculate number of elements to form the array of affinity data. | |||
4003 | llvm::Value *NumOfElements = nullptr; | |||
4004 | unsigned NumAffinities = 0; | |||
4005 | for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) { | |||
4006 | if (const Expr *Modifier = C->getModifier()) { | |||
4007 | const auto *IE = cast<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts()); | |||
4008 | for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) { | |||
4009 | llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper); | |||
4010 | Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false); | |||
4011 | NumOfElements = | |||
4012 | NumOfElements ? CGF.Builder.CreateNUWMul(NumOfElements, Sz) : Sz; | |||
4013 | } | |||
4014 | } else { | |||
4015 | NumAffinities += C->varlist_size(); | |||
4016 | } | |||
4017 | } | |||
4018 | getKmpAffinityType(CGM.getContext(), KmpTaskAffinityInfoTy); | |||
4019 | // Fields ids in kmp_task_affinity_info record. | |||
4020 | enum RTLAffinityInfoFieldsTy { BaseAddr, Len, Flags }; | |||
4021 | ||||
4022 | QualType KmpTaskAffinityInfoArrayTy; | |||
4023 | if (NumOfElements) { | |||
4024 | NumOfElements = CGF.Builder.CreateNUWAdd( | |||
4025 | llvm::ConstantInt::get(CGF.SizeTy, NumAffinities), NumOfElements); | |||
4026 | auto *OVE = new (C) OpaqueValueExpr( | |||
4027 | Loc, | |||
4028 | C.getIntTypeForBitwidth(C.getTypeSize(C.getSizeType()), /*Signed=*/0), | |||
4029 | VK_PRValue); | |||
4030 | CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE, | |||
4031 | RValue::get(NumOfElements)); | |||
4032 | KmpTaskAffinityInfoArrayTy = | |||
4033 | C.getVariableArrayType(KmpTaskAffinityInfoTy, OVE, ArrayType::Normal, | |||
4034 | /*IndexTypeQuals=*/0, SourceRange(Loc, Loc)); | |||
4035 | // Properly emit variable-sized array. | |||
4036 | auto *PD = ImplicitParamDecl::Create(C, KmpTaskAffinityInfoArrayTy, | |||
4037 | ImplicitParamDecl::Other); | |||
4038 | CGF.EmitVarDecl(*PD); | |||
4039 | AffinitiesArray = CGF.GetAddrOfLocalVar(PD); | |||
4040 | NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty, | |||
4041 | /*isSigned=*/false); | |||
4042 | } else { | |||
4043 | KmpTaskAffinityInfoArrayTy = C.getConstantArrayType( | |||
4044 | KmpTaskAffinityInfoTy, | |||
4045 | llvm::APInt(C.getTypeSize(C.getSizeType()), NumAffinities), nullptr, | |||
4046 | ArrayType::Normal, /*IndexTypeQuals=*/0); | |||
4047 | AffinitiesArray = | |||
4048 | CGF.CreateMemTemp(KmpTaskAffinityInfoArrayTy, ".affs.arr.addr"); | |||
4049 | AffinitiesArray = CGF.Builder.CreateConstArrayGEP(AffinitiesArray, 0); | |||
4050 | NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumAffinities, | |||
4051 | /*isSigned=*/false); | |||
4052 | } | |||
4053 | ||||
4054 | const auto *KmpAffinityInfoRD = KmpTaskAffinityInfoTy->getAsRecordDecl(); | |||
4055 | // Fill array by elements without iterators. | |||
4056 | unsigned Pos = 0; | |||
4057 | bool HasIterator = false; | |||
4058 | for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) { | |||
4059 | if (C->getModifier()) { | |||
4060 | HasIterator = true; | |||
4061 | continue; | |||
4062 | } | |||
4063 | for (const Expr *E : C->varlists()) { | |||
4064 | llvm::Value *Addr; | |||
4065 | llvm::Value *Size; | |||
4066 | std::tie(Addr, Size) = getPointerAndSize(CGF, E); | |||
4067 | LValue Base = | |||
4068 | CGF.MakeAddrLValue(CGF.Builder.CreateConstGEP(AffinitiesArray, Pos), | |||
4069 | KmpTaskAffinityInfoTy); | |||
4070 | // affs[i].base_addr = &<Affinities[i].second>; | |||
4071 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4072 | Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr)); | |||
4073 | CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy), | |||
4074 | BaseAddrLVal); | |||
4075 | // affs[i].len = sizeof(<Affinities[i].second>); | |||
4076 | LValue LenLVal = CGF.EmitLValueForField( | |||
4077 | Base, *std::next(KmpAffinityInfoRD->field_begin(), Len)); | |||
4078 | CGF.EmitStoreOfScalar(Size, LenLVal); | |||
4079 | ++Pos; | |||
4080 | } | |||
4081 | } | |||
4082 | LValue PosLVal; | |||
4083 | if (HasIterator) { | |||
4084 | PosLVal = CGF.MakeAddrLValue( | |||
4085 | CGF.CreateMemTemp(C.getSizeType(), "affs.counter.addr"), | |||
4086 | C.getSizeType()); | |||
4087 | CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal); | |||
4088 | } | |||
4089 | // Process elements with iterators. | |||
4090 | for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) { | |||
4091 | const Expr *Modifier = C->getModifier(); | |||
4092 | if (!Modifier) | |||
4093 | continue; | |||
4094 | OMPIteratorGeneratorScope IteratorScope( | |||
4095 | CGF, cast_or_null<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts())); | |||
4096 | for (const Expr *E : C->varlists()) { | |||
4097 | llvm::Value *Addr; | |||
4098 | llvm::Value *Size; | |||
4099 | std::tie(Addr, Size) = getPointerAndSize(CGF, E); | |||
4100 | llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc()); | |||
4101 | LValue Base = CGF.MakeAddrLValue( | |||
4102 | CGF.Builder.CreateGEP(AffinitiesArray, Idx), KmpTaskAffinityInfoTy); | |||
4103 | // affs[i].base_addr = &<Affinities[i].second>; | |||
4104 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4105 | Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr)); | |||
4106 | CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy), | |||
4107 | BaseAddrLVal); | |||
4108 | // affs[i].len = sizeof(<Affinities[i].second>); | |||
4109 | LValue LenLVal = CGF.EmitLValueForField( | |||
4110 | Base, *std::next(KmpAffinityInfoRD->field_begin(), Len)); | |||
4111 | CGF.EmitStoreOfScalar(Size, LenLVal); | |||
4112 | Idx = CGF.Builder.CreateNUWAdd( | |||
4113 | Idx, llvm::ConstantInt::get(Idx->getType(), 1)); | |||
4114 | CGF.EmitStoreOfScalar(Idx, PosLVal); | |||
4115 | } | |||
4116 | } | |||
4117 | // Call to kmp_int32 __kmpc_omp_reg_task_with_affinity(ident_t *loc_ref, | |||
4118 | // kmp_int32 gtid, kmp_task_t *new_task, kmp_int32 | |||
4119 | // naffins, kmp_task_affinity_info_t *affin_list); | |||
4120 | llvm::Value *LocRef = emitUpdateLocation(CGF, Loc); | |||
4121 | llvm::Value *GTid = getThreadID(CGF, Loc); | |||
4122 | llvm::Value *AffinListPtr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4123 | AffinitiesArray.getPointer(), CGM.VoidPtrTy); | |||
4124 | // FIXME: Emit the function and ignore its result for now unless the | |||
4125 | // runtime function is properly implemented. | |||
4126 | (void)CGF.EmitRuntimeCall( | |||
4127 | OMPBuilder.getOrCreateRuntimeFunction( | |||
4128 | CGM.getModule(), OMPRTL___kmpc_omp_reg_task_with_affinity), | |||
4129 | {LocRef, GTid, NewTask, NumOfElements, AffinListPtr}); | |||
4130 | } | |||
4131 | llvm::Value *NewTaskNewTaskTTy = | |||
4132 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4133 | NewTask, KmpTaskTWithPrivatesPtrTy); | |||
4134 | LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy, | |||
4135 | KmpTaskTWithPrivatesQTy); | |||
4136 | LValue TDBase = | |||
4137 | CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
4138 | // Fill the data in the resulting kmp_task_t record. | |||
4139 | // Copy shareds if there are any. | |||
4140 | Address KmpTaskSharedsPtr = Address::invalid(); | |||
4141 | if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) { | |||
4142 | KmpTaskSharedsPtr = Address( | |||
4143 | CGF.EmitLoadOfScalar( | |||
4144 | CGF.EmitLValueForField( | |||
4145 | TDBase, | |||
4146 | *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)), | |||
4147 | Loc), | |||
4148 | CGF.Int8Ty, CGM.getNaturalTypeAlignment(SharedsTy)); | |||
4149 | LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy); | |||
4150 | LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy); | |||
4151 | CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap); | |||
4152 | } | |||
4153 | // Emit initial values for private copies (if any). | |||
4154 | TaskResultTy Result; | |||
4155 | if (!Privates.empty()) { | |||
4156 | emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD, | |||
4157 | SharedsTy, SharedsPtrTy, Data, Privates, | |||
4158 | /*ForDup=*/false); | |||
4159 | if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) && | |||
4160 | (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) { | |||
4161 | Result.TaskDupFn = emitTaskDupFunction( | |||
4162 | CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD, | |||
4163 | KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates, | |||
4164 | /*WithLastIter=*/!Data.LastprivateVars.empty()); | |||
4165 | } | |||
4166 | } | |||
4167 | // Fields of union "kmp_cmplrdata_t" for destructors and priority. | |||
4168 | enum { Priority = 0, Destructors = 1 }; | |||
4169 | // Provide pointer to function with destructors for privates. | |||
4170 | auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1); | |||
4171 | const RecordDecl *KmpCmplrdataUD = | |||
4172 | (*FI)->getType()->getAsUnionType()->getDecl(); | |||
4173 | if (NeedsCleanup) { | |||
4174 | llvm::Value *DestructorFn = emitDestructorsFunction( | |||
4175 | CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, | |||
4176 | KmpTaskTWithPrivatesQTy); | |||
4177 | LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI); | |||
4178 | LValue DestructorsLV = CGF.EmitLValueForField( | |||
4179 | Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors)); | |||
4180 | CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4181 | DestructorFn, KmpRoutineEntryPtrTy), | |||
4182 | DestructorsLV); | |||
4183 | } | |||
4184 | // Set priority. | |||
4185 | if (Data.Priority.getInt()) { | |||
4186 | LValue Data2LV = CGF.EmitLValueForField( | |||
4187 | TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2)); | |||
4188 | LValue PriorityLV = CGF.EmitLValueForField( | |||
4189 | Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority)); | |||
4190 | CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV); | |||
4191 | } | |||
4192 | Result.NewTask = NewTask; | |||
4193 | Result.TaskEntry = TaskEntry; | |||
4194 | Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy; | |||
4195 | Result.TDBase = TDBase; | |||
4196 | Result.KmpTaskTQTyRD = KmpTaskTQTyRD; | |||
4197 | return Result; | |||
4198 | } | |||
4199 | ||||
4200 | /// Translates internal dependency kind into the runtime kind. | |||
4201 | static RTLDependenceKindTy translateDependencyKind(OpenMPDependClauseKind K) { | |||
4202 | RTLDependenceKindTy DepKind; | |||
4203 | switch (K) { | |||
4204 | case OMPC_DEPEND_in: | |||
4205 | DepKind = RTLDependenceKindTy::DepIn; | |||
4206 | break; | |||
4207 | // Out and InOut dependencies must use the same code. | |||
4208 | case OMPC_DEPEND_out: | |||
4209 | case OMPC_DEPEND_inout: | |||
4210 | DepKind = RTLDependenceKindTy::DepInOut; | |||
4211 | break; | |||
4212 | case OMPC_DEPEND_mutexinoutset: | |||
4213 | DepKind = RTLDependenceKindTy::DepMutexInOutSet; | |||
4214 | break; | |||
4215 | case OMPC_DEPEND_inoutset: | |||
4216 | DepKind = RTLDependenceKindTy::DepInOutSet; | |||
4217 | break; | |||
4218 | case OMPC_DEPEND_outallmemory: | |||
4219 | DepKind = RTLDependenceKindTy::DepOmpAllMem; | |||
4220 | break; | |||
4221 | case OMPC_DEPEND_source: | |||
4222 | case OMPC_DEPEND_sink: | |||
4223 | case OMPC_DEPEND_depobj: | |||
4224 | case OMPC_DEPEND_inoutallmemory: | |||
4225 | case OMPC_DEPEND_unknown: | |||
4226 | llvm_unreachable("Unknown task dependence type")::llvm::llvm_unreachable_internal("Unknown task dependence type" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4226); | |||
4227 | } | |||
4228 | return DepKind; | |||
4229 | } | |||
4230 | ||||
4231 | /// Builds kmp_depend_info, if it is not built yet, and builds flags type. | |||
4232 | static void getDependTypes(ASTContext &C, QualType &KmpDependInfoTy, | |||
4233 | QualType &FlagsTy) { | |||
4234 | FlagsTy = C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false); | |||
4235 | if (KmpDependInfoTy.isNull()) { | |||
4236 | RecordDecl *KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info"); | |||
4237 | KmpDependInfoRD->startDefinition(); | |||
4238 | addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType()); | |||
4239 | addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType()); | |||
4240 | addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy); | |||
4241 | KmpDependInfoRD->completeDefinition(); | |||
4242 | KmpDependInfoTy = C.getRecordType(KmpDependInfoRD); | |||
4243 | } | |||
4244 | } | |||
4245 | ||||
4246 | std::pair<llvm::Value *, LValue> | |||
4247 | CGOpenMPRuntime::getDepobjElements(CodeGenFunction &CGF, LValue DepobjLVal, | |||
4248 | SourceLocation Loc) { | |||
4249 | ASTContext &C = CGM.getContext(); | |||
4250 | QualType FlagsTy; | |||
4251 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4252 | RecordDecl *KmpDependInfoRD = | |||
4253 | cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); | |||
4254 | QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy); | |||
4255 | LValue Base = CGF.EmitLoadOfPointerLValue( | |||
4256 | CGF.Builder.CreateElementBitCast( | |||
4257 | DepobjLVal.getAddress(CGF), | |||
4258 | CGF.ConvertTypeForMem(KmpDependInfoPtrTy)), | |||
4259 | KmpDependInfoPtrTy->castAs<PointerType>()); | |||
4260 | Address DepObjAddr = CGF.Builder.CreateGEP( | |||
4261 | Base.getAddress(CGF), | |||
4262 | llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true)); | |||
4263 | LValue NumDepsBase = CGF.MakeAddrLValue( | |||
4264 | DepObjAddr, KmpDependInfoTy, Base.getBaseInfo(), Base.getTBAAInfo()); | |||
4265 | // NumDeps = deps[i].base_addr; | |||
4266 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4267 | NumDepsBase, | |||
4268 | *std::next(KmpDependInfoRD->field_begin(), | |||
4269 | static_cast<unsigned int>(RTLDependInfoFields::BaseAddr))); | |||
4270 | llvm::Value *NumDeps = CGF.EmitLoadOfScalar(BaseAddrLVal, Loc); | |||
4271 | return std::make_pair(NumDeps, Base); | |||
4272 | } | |||
4273 | ||||
4274 | static void emitDependData(CodeGenFunction &CGF, QualType &KmpDependInfoTy, | |||
4275 | llvm::PointerUnion<unsigned *, LValue *> Pos, | |||
4276 | const OMPTaskDataTy::DependData &Data, | |||
4277 | Address DependenciesArray) { | |||
4278 | CodeGenModule &CGM = CGF.CGM; | |||
4279 | ASTContext &C = CGM.getContext(); | |||
4280 | QualType FlagsTy; | |||
4281 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4282 | RecordDecl *KmpDependInfoRD = | |||
4283 | cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); | |||
4284 | llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy); | |||
4285 | ||||
4286 | OMPIteratorGeneratorScope IteratorScope( | |||
4287 | CGF, cast_or_null<OMPIteratorExpr>( | |||
4288 | Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts() | |||
4289 | : nullptr)); | |||
4290 | for (const Expr *E : Data.DepExprs) { | |||
4291 | llvm::Value *Addr; | |||
4292 | llvm::Value *Size; | |||
4293 | ||||
4294 | // The expression will be a nullptr in the 'omp_all_memory' case. | |||
4295 | if (E) { | |||
4296 | std::tie(Addr, Size) = getPointerAndSize(CGF, E); | |||
4297 | Addr = CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy); | |||
4298 | } else { | |||
4299 | Addr = llvm::ConstantInt::get(CGF.IntPtrTy, 0); | |||
4300 | Size = llvm::ConstantInt::get(CGF.SizeTy, 0); | |||
4301 | } | |||
4302 | LValue Base; | |||
4303 | if (unsigned *P = Pos.dyn_cast<unsigned *>()) { | |||
4304 | Base = CGF.MakeAddrLValue( | |||
4305 | CGF.Builder.CreateConstGEP(DependenciesArray, *P), KmpDependInfoTy); | |||
4306 | } else { | |||
4307 | assert(E && "Expected a non-null expression")(static_cast <bool> (E && "Expected a non-null expression" ) ? void (0) : __assert_fail ("E && \"Expected a non-null expression\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4307, __extension__ __PRETTY_FUNCTION__)); | |||
4308 | LValue &PosLVal = *Pos.get<LValue *>(); | |||
4309 | llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc()); | |||
4310 | Base = CGF.MakeAddrLValue( | |||
4311 | CGF.Builder.CreateGEP(DependenciesArray, Idx), KmpDependInfoTy); | |||
4312 | } | |||
4313 | // deps[i].base_addr = &<Dependencies[i].second>; | |||
4314 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4315 | Base, | |||
4316 | *std::next(KmpDependInfoRD->field_begin(), | |||
4317 | static_cast<unsigned int>(RTLDependInfoFields::BaseAddr))); | |||
4318 | CGF.EmitStoreOfScalar(Addr, BaseAddrLVal); | |||
4319 | // deps[i].len = sizeof(<Dependencies[i].second>); | |||
4320 | LValue LenLVal = CGF.EmitLValueForField( | |||
4321 | Base, *std::next(KmpDependInfoRD->field_begin(), | |||
4322 | static_cast<unsigned int>(RTLDependInfoFields::Len))); | |||
4323 | CGF.EmitStoreOfScalar(Size, LenLVal); | |||
4324 | // deps[i].flags = <Dependencies[i].first>; | |||
4325 | RTLDependenceKindTy DepKind = translateDependencyKind(Data.DepKind); | |||
4326 | LValue FlagsLVal = CGF.EmitLValueForField( | |||
4327 | Base, | |||
4328 | *std::next(KmpDependInfoRD->field_begin(), | |||
4329 | static_cast<unsigned int>(RTLDependInfoFields::Flags))); | |||
4330 | CGF.EmitStoreOfScalar( | |||
4331 | llvm::ConstantInt::get(LLVMFlagsTy, static_cast<unsigned int>(DepKind)), | |||
4332 | FlagsLVal); | |||
4333 | if (unsigned *P = Pos.dyn_cast<unsigned *>()) { | |||
4334 | ++(*P); | |||
4335 | } else { | |||
4336 | LValue &PosLVal = *Pos.get<LValue *>(); | |||
4337 | llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc()); | |||
4338 | Idx = CGF.Builder.CreateNUWAdd(Idx, | |||
4339 | llvm::ConstantInt::get(Idx->getType(), 1)); | |||
4340 | CGF.EmitStoreOfScalar(Idx, PosLVal); | |||
4341 | } | |||
4342 | } | |||
4343 | } | |||
4344 | ||||
4345 | SmallVector<llvm::Value *, 4> CGOpenMPRuntime::emitDepobjElementsSizes( | |||
4346 | CodeGenFunction &CGF, QualType &KmpDependInfoTy, | |||
4347 | const OMPTaskDataTy::DependData &Data) { | |||
4348 | assert(Data.DepKind == OMPC_DEPEND_depobj &&(static_cast <bool> (Data.DepKind == OMPC_DEPEND_depobj && "Expected depobj dependency kind.") ? void (0) : __assert_fail ("Data.DepKind == OMPC_DEPEND_depobj && \"Expected depobj dependency kind.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4349, __extension__ __PRETTY_FUNCTION__)) | |||
4349 | "Expected depobj dependency kind.")(static_cast <bool> (Data.DepKind == OMPC_DEPEND_depobj && "Expected depobj dependency kind.") ? void (0) : __assert_fail ("Data.DepKind == OMPC_DEPEND_depobj && \"Expected depobj dependency kind.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4349, __extension__ __PRETTY_FUNCTION__)); | |||
4350 | SmallVector<llvm::Value *, 4> Sizes; | |||
4351 | SmallVector<LValue, 4> SizeLVals; | |||
4352 | ASTContext &C = CGF.getContext(); | |||
4353 | { | |||
4354 | OMPIteratorGeneratorScope IteratorScope( | |||
4355 | CGF, cast_or_null<OMPIteratorExpr>( | |||
4356 | Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts() | |||
4357 | : nullptr)); | |||
4358 | for (const Expr *E : Data.DepExprs) { | |||
4359 | llvm::Value *NumDeps; | |||
4360 | LValue Base; | |||
4361 | LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts()); | |||
4362 | std::tie(NumDeps, Base) = | |||
4363 | getDepobjElements(CGF, DepobjLVal, E->getExprLoc()); | |||
4364 | LValue NumLVal = CGF.MakeAddrLValue( | |||
4365 | CGF.CreateMemTemp(C.getUIntPtrType(), "depobj.size.addr"), | |||
4366 | C.getUIntPtrType()); | |||
4367 | CGF.Builder.CreateStore(llvm::ConstantInt::get(CGF.IntPtrTy, 0), | |||
4368 | NumLVal.getAddress(CGF)); | |||
4369 | llvm::Value *PrevVal = CGF.EmitLoadOfScalar(NumLVal, E->getExprLoc()); | |||
4370 | llvm::Value *Add = CGF.Builder.CreateNUWAdd(PrevVal, NumDeps); | |||
4371 | CGF.EmitStoreOfScalar(Add, NumLVal); | |||
4372 | SizeLVals.push_back(NumLVal); | |||
4373 | } | |||
4374 | } | |||
4375 | for (unsigned I = 0, E = SizeLVals.size(); I < E; ++I) { | |||
4376 | llvm::Value *Size = | |||
4377 | CGF.EmitLoadOfScalar(SizeLVals[I], Data.DepExprs[I]->getExprLoc()); | |||
4378 | Sizes.push_back(Size); | |||
4379 | } | |||
4380 | return Sizes; | |||
4381 | } | |||
4382 | ||||
4383 | void CGOpenMPRuntime::emitDepobjElements(CodeGenFunction &CGF, | |||
4384 | QualType &KmpDependInfoTy, | |||
4385 | LValue PosLVal, | |||
4386 | const OMPTaskDataTy::DependData &Data, | |||
4387 | Address DependenciesArray) { | |||
4388 | assert(Data.DepKind == OMPC_DEPEND_depobj &&(static_cast <bool> (Data.DepKind == OMPC_DEPEND_depobj && "Expected depobj dependency kind.") ? void (0) : __assert_fail ("Data.DepKind == OMPC_DEPEND_depobj && \"Expected depobj dependency kind.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4389, __extension__ __PRETTY_FUNCTION__)) | |||
4389 | "Expected depobj dependency kind.")(static_cast <bool> (Data.DepKind == OMPC_DEPEND_depobj && "Expected depobj dependency kind.") ? void (0) : __assert_fail ("Data.DepKind == OMPC_DEPEND_depobj && \"Expected depobj dependency kind.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4389, __extension__ __PRETTY_FUNCTION__)); | |||
4390 | llvm::Value *ElSize = CGF.getTypeSize(KmpDependInfoTy); | |||
4391 | { | |||
4392 | OMPIteratorGeneratorScope IteratorScope( | |||
4393 | CGF, cast_or_null<OMPIteratorExpr>( | |||
4394 | Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts() | |||
4395 | : nullptr)); | |||
4396 | for (unsigned I = 0, End = Data.DepExprs.size(); I < End; ++I) { | |||
4397 | const Expr *E = Data.DepExprs[I]; | |||
4398 | llvm::Value *NumDeps; | |||
4399 | LValue Base; | |||
4400 | LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts()); | |||
4401 | std::tie(NumDeps, Base) = | |||
4402 | getDepobjElements(CGF, DepobjLVal, E->getExprLoc()); | |||
4403 | ||||
4404 | // memcopy dependency data. | |||
4405 | llvm::Value *Size = CGF.Builder.CreateNUWMul( | |||
4406 | ElSize, | |||
4407 | CGF.Builder.CreateIntCast(NumDeps, CGF.SizeTy, /*isSigned=*/false)); | |||
4408 | llvm::Value *Pos = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc()); | |||
4409 | Address DepAddr = CGF.Builder.CreateGEP(DependenciesArray, Pos); | |||
4410 | CGF.Builder.CreateMemCpy(DepAddr, Base.getAddress(CGF), Size); | |||
4411 | ||||
4412 | // Increase pos. | |||
4413 | // pos += size; | |||
4414 | llvm::Value *Add = CGF.Builder.CreateNUWAdd(Pos, NumDeps); | |||
4415 | CGF.EmitStoreOfScalar(Add, PosLVal); | |||
4416 | } | |||
4417 | } | |||
4418 | } | |||
4419 | ||||
4420 | std::pair<llvm::Value *, Address> CGOpenMPRuntime::emitDependClause( | |||
4421 | CodeGenFunction &CGF, ArrayRef<OMPTaskDataTy::DependData> Dependencies, | |||
4422 | SourceLocation Loc) { | |||
4423 | if (llvm::all_of(Dependencies, [](const OMPTaskDataTy::DependData &D) { | |||
4424 | return D.DepExprs.empty(); | |||
4425 | })) | |||
4426 | return std::make_pair(nullptr, Address::invalid()); | |||
4427 | // Process list of dependencies. | |||
4428 | ASTContext &C = CGM.getContext(); | |||
4429 | Address DependenciesArray = Address::invalid(); | |||
4430 | llvm::Value *NumOfElements = nullptr; | |||
4431 | unsigned NumDependencies = std::accumulate( | |||
4432 | Dependencies.begin(), Dependencies.end(), 0, | |||
4433 | [](unsigned V, const OMPTaskDataTy::DependData &D) { | |||
4434 | return D.DepKind == OMPC_DEPEND_depobj | |||
4435 | ? V | |||
4436 | : (V + (D.IteratorExpr ? 0 : D.DepExprs.size())); | |||
4437 | }); | |||
4438 | QualType FlagsTy; | |||
4439 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4440 | bool HasDepobjDeps = false; | |||
4441 | bool HasRegularWithIterators = false; | |||
4442 | llvm::Value *NumOfDepobjElements = llvm::ConstantInt::get(CGF.IntPtrTy, 0); | |||
4443 | llvm::Value *NumOfRegularWithIterators = | |||
4444 | llvm::ConstantInt::get(CGF.IntPtrTy, 0); | |||
4445 | // Calculate number of depobj dependencies and regular deps with the | |||
4446 | // iterators. | |||
4447 | for (const OMPTaskDataTy::DependData &D : Dependencies) { | |||
4448 | if (D.DepKind == OMPC_DEPEND_depobj) { | |||
4449 | SmallVector<llvm::Value *, 4> Sizes = | |||
4450 | emitDepobjElementsSizes(CGF, KmpDependInfoTy, D); | |||
4451 | for (llvm::Value *Size : Sizes) { | |||
4452 | NumOfDepobjElements = | |||
4453 | CGF.Builder.CreateNUWAdd(NumOfDepobjElements, Size); | |||
4454 | } | |||
4455 | HasDepobjDeps = true; | |||
4456 | continue; | |||
4457 | } | |||
4458 | // Include number of iterations, if any. | |||
4459 | ||||
4460 | if (const auto *IE = cast_or_null<OMPIteratorExpr>(D.IteratorExpr)) { | |||
4461 | for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) { | |||
4462 | llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper); | |||
4463 | Sz = CGF.Builder.CreateIntCast(Sz, CGF.IntPtrTy, /*isSigned=*/false); | |||
4464 | llvm::Value *NumClauseDeps = CGF.Builder.CreateNUWMul( | |||
4465 | Sz, llvm::ConstantInt::get(CGF.IntPtrTy, D.DepExprs.size())); | |||
4466 | NumOfRegularWithIterators = | |||
4467 | CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumClauseDeps); | |||
4468 | } | |||
4469 | HasRegularWithIterators = true; | |||
4470 | continue; | |||
4471 | } | |||
4472 | } | |||
4473 | ||||
4474 | QualType KmpDependInfoArrayTy; | |||
4475 | if (HasDepobjDeps || HasRegularWithIterators) { | |||
4476 | NumOfElements = llvm::ConstantInt::get(CGM.IntPtrTy, NumDependencies, | |||
4477 | /*isSigned=*/false); | |||
4478 | if (HasDepobjDeps) { | |||
4479 | NumOfElements = | |||
4480 | CGF.Builder.CreateNUWAdd(NumOfDepobjElements, NumOfElements); | |||
4481 | } | |||
4482 | if (HasRegularWithIterators) { | |||
4483 | NumOfElements = | |||
4484 | CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumOfElements); | |||
4485 | } | |||
4486 | auto *OVE = new (C) OpaqueValueExpr( | |||
4487 | Loc, C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0), | |||
4488 | VK_PRValue); | |||
4489 | CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE, | |||
4490 | RValue::get(NumOfElements)); | |||
4491 | KmpDependInfoArrayTy = | |||
4492 | C.getVariableArrayType(KmpDependInfoTy, OVE, ArrayType::Normal, | |||
4493 | /*IndexTypeQuals=*/0, SourceRange(Loc, Loc)); | |||
4494 | // CGF.EmitVariablyModifiedType(KmpDependInfoArrayTy); | |||
4495 | // Properly emit variable-sized array. | |||
4496 | auto *PD = ImplicitParamDecl::Create(C, KmpDependInfoArrayTy, | |||
4497 | ImplicitParamDecl::Other); | |||
4498 | CGF.EmitVarDecl(*PD); | |||
4499 | DependenciesArray = CGF.GetAddrOfLocalVar(PD); | |||
4500 | NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty, | |||
4501 | /*isSigned=*/false); | |||
4502 | } else { | |||
4503 | KmpDependInfoArrayTy = C.getConstantArrayType( | |||
4504 | KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies), nullptr, | |||
4505 | ArrayType::Normal, /*IndexTypeQuals=*/0); | |||
4506 | DependenciesArray = | |||
4507 | CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr"); | |||
4508 | DependenciesArray = CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0); | |||
4509 | NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumDependencies, | |||
4510 | /*isSigned=*/false); | |||
4511 | } | |||
4512 | unsigned Pos = 0; | |||
4513 | for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) { | |||
4514 | if (Dependencies[I].DepKind == OMPC_DEPEND_depobj || | |||
4515 | Dependencies[I].IteratorExpr) | |||
4516 | continue; | |||
4517 | emitDependData(CGF, KmpDependInfoTy, &Pos, Dependencies[I], | |||
4518 | DependenciesArray); | |||
4519 | } | |||
4520 | // Copy regular dependencies with iterators. | |||
4521 | LValue PosLVal = CGF.MakeAddrLValue( | |||
4522 | CGF.CreateMemTemp(C.getSizeType(), "dep.counter.addr"), C.getSizeType()); | |||
4523 | CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal); | |||
4524 | for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) { | |||
4525 | if (Dependencies[I].DepKind == OMPC_DEPEND_depobj || | |||
4526 | !Dependencies[I].IteratorExpr) | |||
4527 | continue; | |||
4528 | emitDependData(CGF, KmpDependInfoTy, &PosLVal, Dependencies[I], | |||
4529 | DependenciesArray); | |||
4530 | } | |||
4531 | // Copy final depobj arrays without iterators. | |||
4532 | if (HasDepobjDeps) { | |||
4533 | for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) { | |||
4534 | if (Dependencies[I].DepKind != OMPC_DEPEND_depobj) | |||
4535 | continue; | |||
4536 | emitDepobjElements(CGF, KmpDependInfoTy, PosLVal, Dependencies[I], | |||
4537 | DependenciesArray); | |||
4538 | } | |||
4539 | } | |||
4540 | DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4541 | DependenciesArray, CGF.VoidPtrTy, CGF.Int8Ty); | |||
4542 | return std::make_pair(NumOfElements, DependenciesArray); | |||
4543 | } | |||
4544 | ||||
4545 | Address CGOpenMPRuntime::emitDepobjDependClause( | |||
4546 | CodeGenFunction &CGF, const OMPTaskDataTy::DependData &Dependencies, | |||
4547 | SourceLocation Loc) { | |||
4548 | if (Dependencies.DepExprs.empty()) | |||
4549 | return Address::invalid(); | |||
4550 | // Process list of dependencies. | |||
4551 | ASTContext &C = CGM.getContext(); | |||
4552 | Address DependenciesArray = Address::invalid(); | |||
4553 | unsigned NumDependencies = Dependencies.DepExprs.size(); | |||
4554 | QualType FlagsTy; | |||
4555 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4556 | RecordDecl *KmpDependInfoRD = | |||
4557 | cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); | |||
4558 | ||||
4559 | llvm::Value *Size; | |||
4560 | // Define type kmp_depend_info[<Dependencies.size()>]; | |||
4561 | // For depobj reserve one extra element to store the number of elements. | |||
4562 | // It is required to handle depobj(x) update(in) construct. | |||
4563 | // kmp_depend_info[<Dependencies.size()>] deps; | |||
4564 | llvm::Value *NumDepsVal; | |||
4565 | CharUnits Align = C.getTypeAlignInChars(KmpDependInfoTy); | |||
4566 | if (const auto *IE = | |||
4567 | cast_or_null<OMPIteratorExpr>(Dependencies.IteratorExpr)) { | |||
4568 | NumDepsVal = llvm::ConstantInt::get(CGF.SizeTy, 1); | |||
4569 | for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) { | |||
4570 | llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper); | |||
4571 | Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false); | |||
4572 | NumDepsVal = CGF.Builder.CreateNUWMul(NumDepsVal, Sz); | |||
4573 | } | |||
4574 | Size = CGF.Builder.CreateNUWAdd(llvm::ConstantInt::get(CGF.SizeTy, 1), | |||
4575 | NumDepsVal); | |||
4576 | CharUnits SizeInBytes = | |||
4577 | C.getTypeSizeInChars(KmpDependInfoTy).alignTo(Align); | |||
4578 | llvm::Value *RecSize = CGM.getSize(SizeInBytes); | |||
4579 | Size = CGF.Builder.CreateNUWMul(Size, RecSize); | |||
4580 | NumDepsVal = | |||
4581 | CGF.Builder.CreateIntCast(NumDepsVal, CGF.IntPtrTy, /*isSigned=*/false); | |||
4582 | } else { | |||
4583 | QualType KmpDependInfoArrayTy = C.getConstantArrayType( | |||
4584 | KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies + 1), | |||
4585 | nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0); | |||
4586 | CharUnits Sz = C.getTypeSizeInChars(KmpDependInfoArrayTy); | |||
4587 | Size = CGM.getSize(Sz.alignTo(Align)); | |||
4588 | NumDepsVal = llvm::ConstantInt::get(CGF.IntPtrTy, NumDependencies); | |||
4589 | } | |||
4590 | // Need to allocate on the dynamic memory. | |||
4591 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
4592 | // Use default allocator. | |||
4593 | llvm::Value *Allocator = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
4594 | llvm::Value *Args[] = {ThreadID, Size, Allocator}; | |||
4595 | ||||
4596 | llvm::Value *Addr = | |||
4597 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4598 | CGM.getModule(), OMPRTL___kmpc_alloc), | |||
4599 | Args, ".dep.arr.addr"); | |||
4600 | llvm::Type *KmpDependInfoLlvmTy = CGF.ConvertTypeForMem(KmpDependInfoTy); | |||
4601 | Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4602 | Addr, KmpDependInfoLlvmTy->getPointerTo()); | |||
4603 | DependenciesArray = Address(Addr, KmpDependInfoLlvmTy, Align); | |||
4604 | // Write number of elements in the first element of array for depobj. | |||
4605 | LValue Base = CGF.MakeAddrLValue(DependenciesArray, KmpDependInfoTy); | |||
4606 | // deps[i].base_addr = NumDependencies; | |||
4607 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4608 | Base, | |||
4609 | *std::next(KmpDependInfoRD->field_begin(), | |||
4610 | static_cast<unsigned int>(RTLDependInfoFields::BaseAddr))); | |||
4611 | CGF.EmitStoreOfScalar(NumDepsVal, BaseAddrLVal); | |||
4612 | llvm::PointerUnion<unsigned *, LValue *> Pos; | |||
4613 | unsigned Idx = 1; | |||
4614 | LValue PosLVal; | |||
4615 | if (Dependencies.IteratorExpr) { | |||
4616 | PosLVal = CGF.MakeAddrLValue( | |||
4617 | CGF.CreateMemTemp(C.getSizeType(), "iterator.counter.addr"), | |||
4618 | C.getSizeType()); | |||
4619 | CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Idx), PosLVal, | |||
4620 | /*IsInit=*/true); | |||
4621 | Pos = &PosLVal; | |||
4622 | } else { | |||
4623 | Pos = &Idx; | |||
4624 | } | |||
4625 | emitDependData(CGF, KmpDependInfoTy, Pos, Dependencies, DependenciesArray); | |||
4626 | DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4627 | CGF.Builder.CreateConstGEP(DependenciesArray, 1), CGF.VoidPtrTy, | |||
4628 | CGF.Int8Ty); | |||
4629 | return DependenciesArray; | |||
4630 | } | |||
4631 | ||||
4632 | void CGOpenMPRuntime::emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal, | |||
4633 | SourceLocation Loc) { | |||
4634 | ASTContext &C = CGM.getContext(); | |||
4635 | QualType FlagsTy; | |||
4636 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4637 | LValue Base = CGF.EmitLoadOfPointerLValue( | |||
4638 | DepobjLVal.getAddress(CGF), C.VoidPtrTy.castAs<PointerType>()); | |||
4639 | QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy); | |||
4640 | Address Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4641 | Base.getAddress(CGF), CGF.ConvertTypeForMem(KmpDependInfoPtrTy), | |||
4642 | CGF.ConvertTypeForMem(KmpDependInfoTy)); | |||
4643 | llvm::Value *DepObjAddr = CGF.Builder.CreateGEP( | |||
4644 | Addr.getElementType(), Addr.getPointer(), | |||
4645 | llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true)); | |||
4646 | DepObjAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(DepObjAddr, | |||
4647 | CGF.VoidPtrTy); | |||
4648 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
4649 | // Use default allocator. | |||
4650 | llvm::Value *Allocator = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
4651 | llvm::Value *Args[] = {ThreadID, DepObjAddr, Allocator}; | |||
4652 | ||||
4653 | // _kmpc_free(gtid, addr, nullptr); | |||
4654 | (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4655 | CGM.getModule(), OMPRTL___kmpc_free), | |||
4656 | Args); | |||
4657 | } | |||
4658 | ||||
4659 | void CGOpenMPRuntime::emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal, | |||
4660 | OpenMPDependClauseKind NewDepKind, | |||
4661 | SourceLocation Loc) { | |||
4662 | ASTContext &C = CGM.getContext(); | |||
4663 | QualType FlagsTy; | |||
4664 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4665 | RecordDecl *KmpDependInfoRD = | |||
4666 | cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); | |||
4667 | llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy); | |||
4668 | llvm::Value *NumDeps; | |||
4669 | LValue Base; | |||
4670 | std::tie(NumDeps, Base) = getDepobjElements(CGF, DepobjLVal, Loc); | |||
4671 | ||||
4672 | Address Begin = Base.getAddress(CGF); | |||
4673 | // Cast from pointer to array type to pointer to single element. | |||
4674 | llvm::Value *End = CGF.Builder.CreateGEP( | |||
4675 | Begin.getElementType(), Begin.getPointer(), NumDeps); | |||
4676 | // The basic structure here is a while-do loop. | |||
4677 | llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.body"); | |||
4678 | llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.done"); | |||
4679 | llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); | |||
4680 | CGF.EmitBlock(BodyBB); | |||
4681 | llvm::PHINode *ElementPHI = | |||
4682 | CGF.Builder.CreatePHI(Begin.getType(), 2, "omp.elementPast"); | |||
4683 | ElementPHI->addIncoming(Begin.getPointer(), EntryBB); | |||
4684 | Begin = Begin.withPointer(ElementPHI, KnownNonNull); | |||
4685 | Base = CGF.MakeAddrLValue(Begin, KmpDependInfoTy, Base.getBaseInfo(), | |||
4686 | Base.getTBAAInfo()); | |||
4687 | // deps[i].flags = NewDepKind; | |||
4688 | RTLDependenceKindTy DepKind = translateDependencyKind(NewDepKind); | |||
4689 | LValue FlagsLVal = CGF.EmitLValueForField( | |||
4690 | Base, *std::next(KmpDependInfoRD->field_begin(), | |||
4691 | static_cast<unsigned int>(RTLDependInfoFields::Flags))); | |||
4692 | CGF.EmitStoreOfScalar( | |||
4693 | llvm::ConstantInt::get(LLVMFlagsTy, static_cast<unsigned int>(DepKind)), | |||
4694 | FlagsLVal); | |||
4695 | ||||
4696 | // Shift the address forward by one element. | |||
4697 | Address ElementNext = | |||
4698 | CGF.Builder.CreateConstGEP(Begin, /*Index=*/1, "omp.elementNext"); | |||
4699 | ElementPHI->addIncoming(ElementNext.getPointer(), | |||
4700 | CGF.Builder.GetInsertBlock()); | |||
4701 | llvm::Value *IsEmpty = | |||
4702 | CGF.Builder.CreateICmpEQ(ElementNext.getPointer(), End, "omp.isempty"); | |||
4703 | CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); | |||
4704 | // Done. | |||
4705 | CGF.EmitBlock(DoneBB, /*IsFinished=*/true); | |||
4706 | } | |||
4707 | ||||
4708 | void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
4709 | const OMPExecutableDirective &D, | |||
4710 | llvm::Function *TaskFunction, | |||
4711 | QualType SharedsTy, Address Shareds, | |||
4712 | const Expr *IfCond, | |||
4713 | const OMPTaskDataTy &Data) { | |||
4714 | if (!CGF.HaveInsertPoint()) | |||
4715 | return; | |||
4716 | ||||
4717 | TaskResultTy Result = | |||
4718 | emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data); | |||
4719 | llvm::Value *NewTask = Result.NewTask; | |||
4720 | llvm::Function *TaskEntry = Result.TaskEntry; | |||
4721 | llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy; | |||
4722 | LValue TDBase = Result.TDBase; | |||
4723 | const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD; | |||
4724 | // Process list of dependences. | |||
4725 | Address DependenciesArray = Address::invalid(); | |||
4726 | llvm::Value *NumOfElements; | |||
4727 | std::tie(NumOfElements, DependenciesArray) = | |||
4728 | emitDependClause(CGF, Data.Dependences, Loc); | |||
4729 | ||||
4730 | // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc() | |||
4731 | // libcall. | |||
4732 | // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid, | |||
4733 | // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list, | |||
4734 | // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence | |||
4735 | // list is not empty | |||
4736 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
4737 | llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc); | |||
4738 | llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask }; | |||
4739 | llvm::Value *DepTaskArgs[7]; | |||
4740 | if (!Data.Dependences.empty()) { | |||
4741 | DepTaskArgs[0] = UpLoc; | |||
4742 | DepTaskArgs[1] = ThreadID; | |||
4743 | DepTaskArgs[2] = NewTask; | |||
4744 | DepTaskArgs[3] = NumOfElements; | |||
4745 | DepTaskArgs[4] = DependenciesArray.getPointer(); | |||
4746 | DepTaskArgs[5] = CGF.Builder.getInt32(0); | |||
4747 | DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
4748 | } | |||
4749 | auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, &TaskArgs, | |||
4750 | &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) { | |||
4751 | if (!Data.Tied) { | |||
4752 | auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId); | |||
4753 | LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI); | |||
4754 | CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal); | |||
4755 | } | |||
4756 | if (!Data.Dependences.empty()) { | |||
4757 | CGF.EmitRuntimeCall( | |||
4758 | OMPBuilder.getOrCreateRuntimeFunction( | |||
4759 | CGM.getModule(), OMPRTL___kmpc_omp_task_with_deps), | |||
4760 | DepTaskArgs); | |||
4761 | } else { | |||
4762 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4763 | CGM.getModule(), OMPRTL___kmpc_omp_task), | |||
4764 | TaskArgs); | |||
4765 | } | |||
4766 | // Check if parent region is untied and build return for untied task; | |||
4767 | if (auto *Region = | |||
4768 | dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) | |||
4769 | Region->emitUntiedSwitch(CGF); | |||
4770 | }; | |||
4771 | ||||
4772 | llvm::Value *DepWaitTaskArgs[7]; | |||
4773 | if (!Data.Dependences.empty()) { | |||
4774 | DepWaitTaskArgs[0] = UpLoc; | |||
4775 | DepWaitTaskArgs[1] = ThreadID; | |||
4776 | DepWaitTaskArgs[2] = NumOfElements; | |||
4777 | DepWaitTaskArgs[3] = DependenciesArray.getPointer(); | |||
4778 | DepWaitTaskArgs[4] = CGF.Builder.getInt32(0); | |||
4779 | DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
4780 | DepWaitTaskArgs[6] = | |||
4781 | llvm::ConstantInt::get(CGF.Int32Ty, Data.HasNowaitClause); | |||
4782 | } | |||
4783 | auto &M = CGM.getModule(); | |||
4784 | auto &&ElseCodeGen = [this, &M, &TaskArgs, ThreadID, NewTaskNewTaskTTy, | |||
4785 | TaskEntry, &Data, &DepWaitTaskArgs, | |||
4786 | Loc](CodeGenFunction &CGF, PrePostActionTy &) { | |||
4787 | CodeGenFunction::RunCleanupsScope LocalScope(CGF); | |||
4788 | // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid, | |||
4789 | // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 | |||
4790 | // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info | |||
4791 | // is specified. | |||
4792 | if (!Data.Dependences.empty()) | |||
4793 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4794 | M, OMPRTL___kmpc_omp_taskwait_deps_51), | |||
4795 | DepWaitTaskArgs); | |||
4796 | // Call proxy_task_entry(gtid, new_task); | |||
4797 | auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy, | |||
4798 | Loc](CodeGenFunction &CGF, PrePostActionTy &Action) { | |||
4799 | Action.Enter(CGF); | |||
4800 | llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy}; | |||
4801 | CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry, | |||
4802 | OutlinedFnArgs); | |||
4803 | }; | |||
4804 | ||||
4805 | // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid, | |||
4806 | // kmp_task_t *new_task); | |||
4807 | // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid, | |||
4808 | // kmp_task_t *new_task); | |||
4809 | RegionCodeGenTy RCG(CodeGen); | |||
4810 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
4811 | M, OMPRTL___kmpc_omp_task_begin_if0), | |||
4812 | TaskArgs, | |||
4813 | OMPBuilder.getOrCreateRuntimeFunction( | |||
4814 | M, OMPRTL___kmpc_omp_task_complete_if0), | |||
4815 | TaskArgs); | |||
4816 | RCG.setAction(Action); | |||
4817 | RCG(CGF); | |||
4818 | }; | |||
4819 | ||||
4820 | if (IfCond) { | |||
4821 | emitIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen); | |||
4822 | } else { | |||
4823 | RegionCodeGenTy ThenRCG(ThenCodeGen); | |||
4824 | ThenRCG(CGF); | |||
4825 | } | |||
4826 | } | |||
4827 | ||||
4828 | void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
4829 | const OMPLoopDirective &D, | |||
4830 | llvm::Function *TaskFunction, | |||
4831 | QualType SharedsTy, Address Shareds, | |||
4832 | const Expr *IfCond, | |||
4833 | const OMPTaskDataTy &Data) { | |||
4834 | if (!CGF.HaveInsertPoint()) | |||
4835 | return; | |||
4836 | TaskResultTy Result = | |||
4837 | emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data); | |||
4838 | // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc() | |||
4839 | // libcall. | |||
4840 | // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int | |||
4841 | // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int | |||
4842 | // sched, kmp_uint64 grainsize, void *task_dup); | |||
4843 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
4844 | llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc); | |||
4845 | llvm::Value *IfVal; | |||
4846 | if (IfCond) { | |||
4847 | IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy, | |||
4848 | /*isSigned=*/true); | |||
4849 | } else { | |||
4850 | IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1); | |||
4851 | } | |||
4852 | ||||
4853 | LValue LBLVal = CGF.EmitLValueForField( | |||
4854 | Result.TDBase, | |||
4855 | *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound)); | |||
4856 | const auto *LBVar = | |||
4857 | cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl()); | |||
4858 | CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(CGF), | |||
4859 | LBLVal.getQuals(), | |||
4860 | /*IsInitializer=*/true); | |||
4861 | LValue UBLVal = CGF.EmitLValueForField( | |||
4862 | Result.TDBase, | |||
4863 | *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound)); | |||
4864 | const auto *UBVar = | |||
4865 | cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl()); | |||
4866 | CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(CGF), | |||
4867 | UBLVal.getQuals(), | |||
4868 | /*IsInitializer=*/true); | |||
4869 | LValue StLVal = CGF.EmitLValueForField( | |||
4870 | Result.TDBase, | |||
4871 | *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride)); | |||
4872 | const auto *StVar = | |||
4873 | cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl()); | |||
4874 | CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(CGF), | |||
4875 | StLVal.getQuals(), | |||
4876 | /*IsInitializer=*/true); | |||
4877 | // Store reductions address. | |||
4878 | LValue RedLVal = CGF.EmitLValueForField( | |||
4879 | Result.TDBase, | |||
4880 | *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions)); | |||
4881 | if (Data.Reductions) { | |||
4882 | CGF.EmitStoreOfScalar(Data.Reductions, RedLVal); | |||
4883 | } else { | |||
4884 | CGF.EmitNullInitialization(RedLVal.getAddress(CGF), | |||
4885 | CGF.getContext().VoidPtrTy); | |||
4886 | } | |||
4887 | enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 }; | |||
4888 | llvm::Value *TaskArgs[] = { | |||
4889 | UpLoc, | |||
4890 | ThreadID, | |||
4891 | Result.NewTask, | |||
4892 | IfVal, | |||
4893 | LBLVal.getPointer(CGF), | |||
4894 | UBLVal.getPointer(CGF), | |||
4895 | CGF.EmitLoadOfScalar(StLVal, Loc), | |||
4896 | llvm::ConstantInt::getSigned( | |||
4897 | CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler | |||
4898 | llvm::ConstantInt::getSigned( | |||
4899 | CGF.IntTy, Data.Schedule.getPointer() | |||
4900 | ? Data.Schedule.getInt() ? NumTasks : Grainsize | |||
4901 | : NoSchedule), | |||
4902 | Data.Schedule.getPointer() | |||
4903 | ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty, | |||
4904 | /*isSigned=*/false) | |||
4905 | : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0), | |||
4906 | Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4907 | Result.TaskDupFn, CGF.VoidPtrTy) | |||
4908 | : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)}; | |||
4909 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4910 | CGM.getModule(), OMPRTL___kmpc_taskloop), | |||
4911 | TaskArgs); | |||
4912 | } | |||
4913 | ||||
4914 | /// Emit reduction operation for each element of array (required for | |||
4915 | /// array sections) LHS op = RHS. | |||
4916 | /// \param Type Type of array. | |||
4917 | /// \param LHSVar Variable on the left side of the reduction operation | |||
4918 | /// (references element of array in original variable). | |||
4919 | /// \param RHSVar Variable on the right side of the reduction operation | |||
4920 | /// (references element of array in original variable). | |||
4921 | /// \param RedOpGen Generator of reduction operation with use of LHSVar and | |||
4922 | /// RHSVar. | |||
4923 | static void EmitOMPAggregateReduction( | |||
4924 | CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar, | |||
4925 | const VarDecl *RHSVar, | |||
4926 | const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *, | |||
4927 | const Expr *, const Expr *)> &RedOpGen, | |||
4928 | const Expr *XExpr = nullptr, const Expr *EExpr = nullptr, | |||
4929 | const Expr *UpExpr = nullptr) { | |||
4930 | // Perform element-by-element initialization. | |||
4931 | QualType ElementTy; | |||
4932 | Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar); | |||
4933 | Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar); | |||
4934 | ||||
4935 | // Drill down to the base element type on both arrays. | |||
4936 | const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe(); | |||
4937 | llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr); | |||
4938 | ||||
4939 | llvm::Value *RHSBegin = RHSAddr.getPointer(); | |||
4940 | llvm::Value *LHSBegin = LHSAddr.getPointer(); | |||
4941 | // Cast from pointer to array type to pointer to single element. | |||
4942 | llvm::Value *LHSEnd = | |||
4943 | CGF.Builder.CreateGEP(LHSAddr.getElementType(), LHSBegin, NumElements); | |||
4944 | // The basic structure here is a while-do loop. | |||
4945 | llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body"); | |||
4946 | llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done"); | |||
4947 | llvm::Value *IsEmpty = | |||
4948 | CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty"); | |||
4949 | CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); | |||
4950 | ||||
4951 | // Enter the loop body, making that address the current address. | |||
4952 | llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); | |||
4953 | CGF.EmitBlock(BodyBB); | |||
4954 | ||||
4955 | CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); | |||
4956 | ||||
4957 | llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI( | |||
4958 | RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast"); | |||
4959 | RHSElementPHI->addIncoming(RHSBegin, EntryBB); | |||
4960 | Address RHSElementCurrent( | |||
4961 | RHSElementPHI, RHSAddr.getElementType(), | |||
4962 | RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize)); | |||
4963 | ||||
4964 | llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI( | |||
4965 | LHSBegin->getType(), 2, "omp.arraycpy.destElementPast"); | |||
4966 | LHSElementPHI->addIncoming(LHSBegin, EntryBB); | |||
4967 | Address LHSElementCurrent( | |||
4968 | LHSElementPHI, LHSAddr.getElementType(), | |||
4969 | LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize)); | |||
4970 | ||||
4971 | // Emit copy. | |||
4972 | CodeGenFunction::OMPPrivateScope Scope(CGF); | |||
4973 | Scope.addPrivate(LHSVar, LHSElementCurrent); | |||
4974 | Scope.addPrivate(RHSVar, RHSElementCurrent); | |||
4975 | Scope.Privatize(); | |||
4976 | RedOpGen(CGF, XExpr, EExpr, UpExpr); | |||
4977 | Scope.ForceCleanup(); | |||
4978 | ||||
4979 | // Shift the address forward by one element. | |||
4980 | llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32( | |||
4981 | LHSAddr.getElementType(), LHSElementPHI, /*Idx0=*/1, | |||
4982 | "omp.arraycpy.dest.element"); | |||
4983 | llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32( | |||
4984 | RHSAddr.getElementType(), RHSElementPHI, /*Idx0=*/1, | |||
4985 | "omp.arraycpy.src.element"); | |||
4986 | // Check whether we've reached the end. | |||
4987 | llvm::Value *Done = | |||
4988 | CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done"); | |||
4989 | CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); | |||
4990 | LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock()); | |||
4991 | RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock()); | |||
4992 | ||||
4993 | // Done. | |||
4994 | CGF.EmitBlock(DoneBB, /*IsFinished=*/true); | |||
4995 | } | |||
4996 | ||||
4997 | /// Emit reduction combiner. If the combiner is a simple expression emit it as | |||
4998 | /// is, otherwise consider it as combiner of UDR decl and emit it as a call of | |||
4999 | /// UDR combiner function. | |||
5000 | static void emitReductionCombiner(CodeGenFunction &CGF, | |||
5001 | const Expr *ReductionOp) { | |||
5002 | if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) | |||
5003 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) | |||
5004 | if (const auto *DRE = | |||
5005 | dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) | |||
5006 | if (const auto *DRD = | |||
5007 | dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) { | |||
5008 | std::pair<llvm::Function *, llvm::Function *> Reduction = | |||
5009 | CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); | |||
5010 | RValue Func = RValue::get(Reduction.first); | |||
5011 | CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); | |||
5012 | CGF.EmitIgnoredExpr(ReductionOp); | |||
5013 | return; | |||
5014 | } | |||
5015 | CGF.EmitIgnoredExpr(ReductionOp); | |||
5016 | } | |||
5017 | ||||
5018 | llvm::Function *CGOpenMPRuntime::emitReductionFunction( | |||
5019 | StringRef ReducerName, SourceLocation Loc, llvm::Type *ArgsElemType, | |||
5020 | ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, | |||
5021 | ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) { | |||
5022 | ASTContext &C = CGM.getContext(); | |||
5023 | ||||
5024 | // void reduction_func(void *LHSArg, void *RHSArg); | |||
5025 | FunctionArgList Args; | |||
5026 | ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
5027 | ImplicitParamDecl::Other); | |||
5028 | ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
5029 | ImplicitParamDecl::Other); | |||
5030 | Args.push_back(&LHSArg); | |||
5031 | Args.push_back(&RHSArg); | |||
5032 | const auto &CGFI = | |||
5033 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
5034 | std::string Name = getReductionFuncName(ReducerName); | |||
5035 | auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI), | |||
5036 | llvm::GlobalValue::InternalLinkage, Name, | |||
5037 | &CGM.getModule()); | |||
5038 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); | |||
5039 | Fn->setDoesNotRecurse(); | |||
5040 | CodeGenFunction CGF(CGM); | |||
5041 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); | |||
5042 | ||||
5043 | // Dst = (void*[n])(LHSArg); | |||
5044 | // Src = (void*[n])(RHSArg); | |||
5045 | Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5046 | CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)), | |||
5047 | ArgsElemType->getPointerTo()), | |||
5048 | ArgsElemType, CGF.getPointerAlign()); | |||
5049 | Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5050 | CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)), | |||
5051 | ArgsElemType->getPointerTo()), | |||
5052 | ArgsElemType, CGF.getPointerAlign()); | |||
5053 | ||||
5054 | // ... | |||
5055 | // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); | |||
5056 | // ... | |||
5057 | CodeGenFunction::OMPPrivateScope Scope(CGF); | |||
5058 | const auto *IPriv = Privates.begin(); | |||
5059 | unsigned Idx = 0; | |||
5060 | for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) { | |||
5061 | const auto *RHSVar = | |||
5062 | cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()); | |||
5063 | Scope.addPrivate(RHSVar, emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar)); | |||
5064 | const auto *LHSVar = | |||
5065 | cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()); | |||
5066 | Scope.addPrivate(LHSVar, emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar)); | |||
5067 | QualType PrivTy = (*IPriv)->getType(); | |||
5068 | if (PrivTy->isVariablyModifiedType()) { | |||
5069 | // Get array size and emit VLA type. | |||
5070 | ++Idx; | |||
5071 | Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx); | |||
5072 | llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem); | |||
5073 | const VariableArrayType *VLA = | |||
5074 | CGF.getContext().getAsVariableArrayType(PrivTy); | |||
5075 | const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr()); | |||
5076 | CodeGenFunction::OpaqueValueMapping OpaqueMap( | |||
5077 | CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy))); | |||
5078 | CGF.EmitVariablyModifiedType(PrivTy); | |||
5079 | } | |||
5080 | } | |||
5081 | Scope.Privatize(); | |||
5082 | IPriv = Privates.begin(); | |||
5083 | const auto *ILHS = LHSExprs.begin(); | |||
5084 | const auto *IRHS = RHSExprs.begin(); | |||
5085 | for (const Expr *E : ReductionOps) { | |||
5086 | if ((*IPriv)->getType()->isArrayType()) { | |||
5087 | // Emit reduction for array section. | |||
5088 | const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); | |||
5089 | const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); | |||
5090 | EmitOMPAggregateReduction( | |||
5091 | CGF, (*IPriv)->getType(), LHSVar, RHSVar, | |||
5092 | [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) { | |||
5093 | emitReductionCombiner(CGF, E); | |||
5094 | }); | |||
5095 | } else { | |||
5096 | // Emit reduction for array subscript or single variable. | |||
5097 | emitReductionCombiner(CGF, E); | |||
5098 | } | |||
5099 | ++IPriv; | |||
5100 | ++ILHS; | |||
5101 | ++IRHS; | |||
5102 | } | |||
5103 | Scope.ForceCleanup(); | |||
5104 | CGF.FinishFunction(); | |||
5105 | return Fn; | |||
5106 | } | |||
5107 | ||||
5108 | void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF, | |||
5109 | const Expr *ReductionOp, | |||
5110 | const Expr *PrivateRef, | |||
5111 | const DeclRefExpr *LHS, | |||
5112 | const DeclRefExpr *RHS) { | |||
5113 | if (PrivateRef->getType()->isArrayType()) { | |||
5114 | // Emit reduction for array section. | |||
5115 | const auto *LHSVar = cast<VarDecl>(LHS->getDecl()); | |||
5116 | const auto *RHSVar = cast<VarDecl>(RHS->getDecl()); | |||
5117 | EmitOMPAggregateReduction( | |||
5118 | CGF, PrivateRef->getType(), LHSVar, RHSVar, | |||
5119 | [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) { | |||
5120 | emitReductionCombiner(CGF, ReductionOp); | |||
5121 | }); | |||
5122 | } else { | |||
5123 | // Emit reduction for array subscript or single variable. | |||
5124 | emitReductionCombiner(CGF, ReductionOp); | |||
5125 | } | |||
5126 | } | |||
5127 | ||||
5128 | void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc, | |||
5129 | ArrayRef<const Expr *> Privates, | |||
5130 | ArrayRef<const Expr *> LHSExprs, | |||
5131 | ArrayRef<const Expr *> RHSExprs, | |||
5132 | ArrayRef<const Expr *> ReductionOps, | |||
5133 | ReductionOptionsTy Options) { | |||
5134 | if (!CGF.HaveInsertPoint()) | |||
5135 | return; | |||
5136 | ||||
5137 | bool WithNowait = Options.WithNowait; | |||
5138 | bool SimpleReduction = Options.SimpleReduction; | |||
5139 | ||||
5140 | // Next code should be emitted for reduction: | |||
5141 | // | |||
5142 | // static kmp_critical_name lock = { 0 }; | |||
5143 | // | |||
5144 | // void reduce_func(void *lhs[<n>], void *rhs[<n>]) { | |||
5145 | // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]); | |||
5146 | // ... | |||
5147 | // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1], | |||
5148 | // *(Type<n>-1*)rhs[<n>-1]); | |||
5149 | // } | |||
5150 | // | |||
5151 | // ... | |||
5152 | // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; | |||
5153 | // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), | |||
5154 | // RedList, reduce_func, &<lock>)) { | |||
5155 | // case 1: | |||
5156 | // ... | |||
5157 | // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); | |||
5158 | // ... | |||
5159 | // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); | |||
5160 | // break; | |||
5161 | // case 2: | |||
5162 | // ... | |||
5163 | // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); | |||
5164 | // ... | |||
5165 | // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);] | |||
5166 | // break; | |||
5167 | // default:; | |||
5168 | // } | |||
5169 | // | |||
5170 | // if SimpleReduction is true, only the next code is generated: | |||
5171 | // ... | |||
5172 | // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); | |||
5173 | // ... | |||
5174 | ||||
5175 | ASTContext &C = CGM.getContext(); | |||
5176 | ||||
5177 | if (SimpleReduction) { | |||
5178 | CodeGenFunction::RunCleanupsScope Scope(CGF); | |||
5179 | const auto *IPriv = Privates.begin(); | |||
5180 | const auto *ILHS = LHSExprs.begin(); | |||
5181 | const auto *IRHS = RHSExprs.begin(); | |||
5182 | for (const Expr *E : ReductionOps) { | |||
5183 | emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), | |||
5184 | cast<DeclRefExpr>(*IRHS)); | |||
5185 | ++IPriv; | |||
5186 | ++ILHS; | |||
5187 | ++IRHS; | |||
5188 | } | |||
5189 | return; | |||
5190 | } | |||
5191 | ||||
5192 | // 1. Build a list of reduction variables. | |||
5193 | // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]}; | |||
5194 | auto Size = RHSExprs.size(); | |||
5195 | for (const Expr *E : Privates) { | |||
5196 | if (E->getType()->isVariablyModifiedType()) | |||
5197 | // Reserve place for array size. | |||
5198 | ++Size; | |||
5199 | } | |||
5200 | llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size); | |||
5201 | QualType ReductionArrayTy = | |||
5202 | C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal, | |||
5203 | /*IndexTypeQuals=*/0); | |||
5204 | Address ReductionList = | |||
5205 | CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list"); | |||
5206 | const auto *IPriv = Privates.begin(); | |||
5207 | unsigned Idx = 0; | |||
5208 | for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) { | |||
5209 | Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx); | |||
5210 | CGF.Builder.CreateStore( | |||
5211 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5212 | CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy), | |||
5213 | Elem); | |||
5214 | if ((*IPriv)->getType()->isVariablyModifiedType()) { | |||
5215 | // Store array size. | |||
5216 | ++Idx; | |||
5217 | Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx); | |||
5218 | llvm::Value *Size = CGF.Builder.CreateIntCast( | |||
5219 | CGF.getVLASize( | |||
5220 | CGF.getContext().getAsVariableArrayType((*IPriv)->getType())) | |||
5221 | .NumElts, | |||
5222 | CGF.SizeTy, /*isSigned=*/false); | |||
5223 | CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy), | |||
5224 | Elem); | |||
5225 | } | |||
5226 | } | |||
5227 | ||||
5228 | // 2. Emit reduce_func(). | |||
5229 | llvm::Function *ReductionFn = emitReductionFunction( | |||
5230 | CGF.CurFn->getName(), Loc, CGF.ConvertTypeForMem(ReductionArrayTy), | |||
5231 | Privates, LHSExprs, RHSExprs, ReductionOps); | |||
5232 | ||||
5233 | // 3. Create static kmp_critical_name lock = { 0 }; | |||
5234 | std::string Name = getName({"reduction"}); | |||
5235 | llvm::Value *Lock = getCriticalRegionLock(Name); | |||
5236 | ||||
5237 | // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), | |||
5238 | // RedList, reduce_func, &<lock>); | |||
5239 | llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE); | |||
5240 | llvm::Value *ThreadId = getThreadID(CGF, Loc); | |||
5241 | llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy); | |||
5242 | llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5243 | ReductionList.getPointer(), CGF.VoidPtrTy); | |||
5244 | llvm::Value *Args[] = { | |||
5245 | IdentTLoc, // ident_t *<loc> | |||
5246 | ThreadId, // i32 <gtid> | |||
5247 | CGF.Builder.getInt32(RHSExprs.size()), // i32 <n> | |||
5248 | ReductionArrayTySize, // size_type sizeof(RedList) | |||
5249 | RL, // void *RedList | |||
5250 | ReductionFn, // void (*) (void *, void *) <reduce_func> | |||
5251 | Lock // kmp_critical_name *&<lock> | |||
5252 | }; | |||
5253 | llvm::Value *Res = CGF.EmitRuntimeCall( | |||
5254 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5255 | CGM.getModule(), | |||
5256 | WithNowait ? OMPRTL___kmpc_reduce_nowait : OMPRTL___kmpc_reduce), | |||
5257 | Args); | |||
5258 | ||||
5259 | // 5. Build switch(res) | |||
5260 | llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default"); | |||
5261 | llvm::SwitchInst *SwInst = | |||
5262 | CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2); | |||
5263 | ||||
5264 | // 6. Build case 1: | |||
5265 | // ... | |||
5266 | // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); | |||
5267 | // ... | |||
5268 | // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); | |||
5269 | // break; | |||
5270 | llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1"); | |||
5271 | SwInst->addCase(CGF.Builder.getInt32(1), Case1BB); | |||
5272 | CGF.EmitBlock(Case1BB); | |||
5273 | ||||
5274 | // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); | |||
5275 | llvm::Value *EndArgs[] = { | |||
5276 | IdentTLoc, // ident_t *<loc> | |||
5277 | ThreadId, // i32 <gtid> | |||
5278 | Lock // kmp_critical_name *&<lock> | |||
5279 | }; | |||
5280 | auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps]( | |||
5281 | CodeGenFunction &CGF, PrePostActionTy &Action) { | |||
5282 | CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); | |||
5283 | const auto *IPriv = Privates.begin(); | |||
5284 | const auto *ILHS = LHSExprs.begin(); | |||
5285 | const auto *IRHS = RHSExprs.begin(); | |||
5286 | for (const Expr *E : ReductionOps) { | |||
5287 | RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), | |||
5288 | cast<DeclRefExpr>(*IRHS)); | |||
5289 | ++IPriv; | |||
5290 | ++ILHS; | |||
5291 | ++IRHS; | |||
5292 | } | |||
5293 | }; | |||
5294 | RegionCodeGenTy RCG(CodeGen); | |||
5295 | CommonActionTy Action( | |||
5296 | nullptr, std::nullopt, | |||
5297 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5298 | CGM.getModule(), WithNowait ? OMPRTL___kmpc_end_reduce_nowait | |||
5299 | : OMPRTL___kmpc_end_reduce), | |||
5300 | EndArgs); | |||
5301 | RCG.setAction(Action); | |||
5302 | RCG(CGF); | |||
5303 | ||||
5304 | CGF.EmitBranch(DefaultBB); | |||
5305 | ||||
5306 | // 7. Build case 2: | |||
5307 | // ... | |||
5308 | // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); | |||
5309 | // ... | |||
5310 | // break; | |||
5311 | llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2"); | |||
5312 | SwInst->addCase(CGF.Builder.getInt32(2), Case2BB); | |||
5313 | CGF.EmitBlock(Case2BB); | |||
5314 | ||||
5315 | auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps]( | |||
5316 | CodeGenFunction &CGF, PrePostActionTy &Action) { | |||
5317 | const auto *ILHS = LHSExprs.begin(); | |||
5318 | const auto *IRHS = RHSExprs.begin(); | |||
5319 | const auto *IPriv = Privates.begin(); | |||
5320 | for (const Expr *E : ReductionOps) { | |||
5321 | const Expr *XExpr = nullptr; | |||
5322 | const Expr *EExpr = nullptr; | |||
5323 | const Expr *UpExpr = nullptr; | |||
5324 | BinaryOperatorKind BO = BO_Comma; | |||
5325 | if (const auto *BO = dyn_cast<BinaryOperator>(E)) { | |||
5326 | if (BO->getOpcode() == BO_Assign) { | |||
5327 | XExpr = BO->getLHS(); | |||
5328 | UpExpr = BO->getRHS(); | |||
5329 | } | |||
5330 | } | |||
5331 | // Try to emit update expression as a simple atomic. | |||
5332 | const Expr *RHSExpr = UpExpr; | |||
5333 | if (RHSExpr) { | |||
5334 | // Analyze RHS part of the whole expression. | |||
5335 | if (const auto *ACO = dyn_cast<AbstractConditionalOperator>( | |||
5336 | RHSExpr->IgnoreParenImpCasts())) { | |||
5337 | // If this is a conditional operator, analyze its condition for | |||
5338 | // min/max reduction operator. | |||
5339 | RHSExpr = ACO->getCond(); | |||
5340 | } | |||
5341 | if (const auto *BORHS = | |||
5342 | dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) { | |||
5343 | EExpr = BORHS->getRHS(); | |||
5344 | BO = BORHS->getOpcode(); | |||
5345 | } | |||
5346 | } | |||
5347 | if (XExpr) { | |||
5348 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); | |||
5349 | auto &&AtomicRedGen = [BO, VD, | |||
5350 | Loc](CodeGenFunction &CGF, const Expr *XExpr, | |||
5351 | const Expr *EExpr, const Expr *UpExpr) { | |||
5352 | LValue X = CGF.EmitLValue(XExpr); | |||
5353 | RValue E; | |||
5354 | if (EExpr) | |||
5355 | E = CGF.EmitAnyExpr(EExpr); | |||
5356 | CGF.EmitOMPAtomicSimpleUpdateExpr( | |||
5357 | X, E, BO, /*IsXLHSInRHSPart=*/true, | |||
5358 | llvm::AtomicOrdering::Monotonic, Loc, | |||
5359 | [&CGF, UpExpr, VD, Loc](RValue XRValue) { | |||
5360 | CodeGenFunction::OMPPrivateScope PrivateScope(CGF); | |||
5361 | Address LHSTemp = CGF.CreateMemTemp(VD->getType()); | |||
5362 | CGF.emitOMPSimpleStore( | |||
5363 | CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue, | |||
5364 | VD->getType().getNonReferenceType(), Loc); | |||
5365 | PrivateScope.addPrivate(VD, LHSTemp); | |||
5366 | (void)PrivateScope.Privatize(); | |||
5367 | return CGF.EmitAnyExpr(UpExpr); | |||
5368 | }); | |||
5369 | }; | |||
5370 | if ((*IPriv)->getType()->isArrayType()) { | |||
5371 | // Emit atomic reduction for array section. | |||
5372 | const auto *RHSVar = | |||
5373 | cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); | |||
5374 | EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar, | |||
5375 | AtomicRedGen, XExpr, EExpr, UpExpr); | |||
5376 | } else { | |||
5377 | // Emit atomic reduction for array subscript or single variable. | |||
5378 | AtomicRedGen(CGF, XExpr, EExpr, UpExpr); | |||
5379 | } | |||
5380 | } else { | |||
5381 | // Emit as a critical region. | |||
5382 | auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *, | |||
5383 | const Expr *, const Expr *) { | |||
5384 | CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); | |||
5385 | std::string Name = RT.getName({"atomic_reduction"}); | |||
5386 | RT.emitCriticalRegion( | |||
5387 | CGF, Name, | |||
5388 | [=](CodeGenFunction &CGF, PrePostActionTy &Action) { | |||
5389 | Action.Enter(CGF); | |||
5390 | emitReductionCombiner(CGF, E); | |||
5391 | }, | |||
5392 | Loc); | |||
5393 | }; | |||
5394 | if ((*IPriv)->getType()->isArrayType()) { | |||
5395 | const auto *LHSVar = | |||
5396 | cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); | |||
5397 | const auto *RHSVar = | |||
5398 | cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); | |||
5399 | EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar, | |||
5400 | CritRedGen); | |||
5401 | } else { | |||
5402 | CritRedGen(CGF, nullptr, nullptr, nullptr); | |||
5403 | } | |||
5404 | } | |||
5405 | ++ILHS; | |||
5406 | ++IRHS; | |||
5407 | ++IPriv; | |||
5408 | } | |||
5409 | }; | |||
5410 | RegionCodeGenTy AtomicRCG(AtomicCodeGen); | |||
5411 | if (!WithNowait) { | |||
5412 | // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>); | |||
5413 | llvm::Value *EndArgs[] = { | |||
5414 | IdentTLoc, // ident_t *<loc> | |||
5415 | ThreadId, // i32 <gtid> | |||
5416 | Lock // kmp_critical_name *&<lock> | |||
5417 | }; | |||
5418 | CommonActionTy Action(nullptr, std::nullopt, | |||
5419 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5420 | CGM.getModule(), OMPRTL___kmpc_end_reduce), | |||
5421 | EndArgs); | |||
5422 | AtomicRCG.setAction(Action); | |||
5423 | AtomicRCG(CGF); | |||
5424 | } else { | |||
5425 | AtomicRCG(CGF); | |||
5426 | } | |||
5427 | ||||
5428 | CGF.EmitBranch(DefaultBB); | |||
5429 | CGF.EmitBlock(DefaultBB, /*IsFinished=*/true); | |||
5430 | } | |||
5431 | ||||
5432 | /// Generates unique name for artificial threadprivate variables. | |||
5433 | /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>" | |||
5434 | static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix, | |||
5435 | const Expr *Ref) { | |||
5436 | SmallString<256> Buffer; | |||
5437 | llvm::raw_svector_ostream Out(Buffer); | |||
5438 | const clang::DeclRefExpr *DE; | |||
5439 | const VarDecl *D = ::getBaseDecl(Ref, DE); | |||
5440 | if (!D) | |||
5441 | D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl()); | |||
5442 | D = D->getCanonicalDecl(); | |||
5443 | std::string Name = CGM.getOpenMPRuntime().getName( | |||
5444 | {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)}); | |||
5445 | Out << Prefix << Name << "_" | |||
5446 | << D->getCanonicalDecl()->getBeginLoc().getRawEncoding(); | |||
5447 | return std::string(Out.str()); | |||
5448 | } | |||
5449 | ||||
5450 | /// Emits reduction initializer function: | |||
5451 | /// \code | |||
5452 | /// void @.red_init(void* %arg, void* %orig) { | |||
5453 | /// %0 = bitcast void* %arg to <type>* | |||
5454 | /// store <type> <init>, <type>* %0 | |||
5455 | /// ret void | |||
5456 | /// } | |||
5457 | /// \endcode | |||
5458 | static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM, | |||
5459 | SourceLocation Loc, | |||
5460 | ReductionCodeGen &RCG, unsigned N) { | |||
5461 | ASTContext &C = CGM.getContext(); | |||
5462 | QualType VoidPtrTy = C.VoidPtrTy; | |||
5463 | VoidPtrTy.addRestrict(); | |||
5464 | FunctionArgList Args; | |||
5465 | ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, VoidPtrTy, | |||
5466 | ImplicitParamDecl::Other); | |||
5467 | ImplicitParamDecl ParamOrig(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, VoidPtrTy, | |||
5468 | ImplicitParamDecl::Other); | |||
5469 | Args.emplace_back(&Param); | |||
5470 | Args.emplace_back(&ParamOrig); | |||
5471 | const auto &FnInfo = | |||
5472 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
5473 | llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); | |||
5474 | std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""}); | |||
5475 | auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, | |||
5476 | Name, &CGM.getModule()); | |||
5477 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); | |||
5478 | Fn->setDoesNotRecurse(); | |||
5479 | CodeGenFunction CGF(CGM); | |||
5480 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); | |||
5481 | QualType PrivateType = RCG.getPrivateType(N); | |||
5482 | Address PrivateAddr = CGF.EmitLoadOfPointer( | |||
5483 | CGF.Builder.CreateElementBitCast( | |||
5484 | CGF.GetAddrOfLocalVar(&Param), | |||
5485 | CGF.ConvertTypeForMem(PrivateType)->getPointerTo()), | |||
5486 | C.getPointerType(PrivateType)->castAs<PointerType>()); | |||
5487 | llvm::Value *Size = nullptr; | |||
5488 | // If the size of the reduction item is non-constant, load it from global | |||
5489 | // threadprivate variable. | |||
5490 | if (RCG.getSizes(N).second) { | |||
5491 | Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( | |||
5492 | CGF, CGM.getContext().getSizeType(), | |||
5493 | generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); | |||
5494 | Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, | |||
5495 | CGM.getContext().getSizeType(), Loc); | |||
5496 | } | |||
5497 | RCG.emitAggregateType(CGF, N, Size); | |||
5498 | Address OrigAddr = Address::invalid(); | |||
5499 | // If initializer uses initializer from declare reduction construct, emit a | |||
5500 | // pointer to the address of the original reduction item (reuired by reduction | |||
5501 | // initializer) | |||
5502 | if (RCG.usesReductionInitializer(N)) { | |||
5503 | Address SharedAddr = CGF.GetAddrOfLocalVar(&ParamOrig); | |||
5504 | OrigAddr = CGF.EmitLoadOfPointer( | |||
5505 | SharedAddr, | |||
5506 | CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr()); | |||
5507 | } | |||
5508 | // Emit the initializer: | |||
5509 | // %0 = bitcast void* %arg to <type>* | |||
5510 | // store <type> <init>, <type>* %0 | |||
5511 | RCG.emitInitialization(CGF, N, PrivateAddr, OrigAddr, | |||
5512 | [](CodeGenFunction &) { return false; }); | |||
5513 | CGF.FinishFunction(); | |||
5514 | return Fn; | |||
5515 | } | |||
5516 | ||||
5517 | /// Emits reduction combiner function: | |||
5518 | /// \code | |||
5519 | /// void @.red_comb(void* %arg0, void* %arg1) { | |||
5520 | /// %lhs = bitcast void* %arg0 to <type>* | |||
5521 | /// %rhs = bitcast void* %arg1 to <type>* | |||
5522 | /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs) | |||
5523 | /// store <type> %2, <type>* %lhs | |||
5524 | /// ret void | |||
5525 | /// } | |||
5526 | /// \endcode | |||
5527 | static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM, | |||
5528 | SourceLocation Loc, | |||
5529 | ReductionCodeGen &RCG, unsigned N, | |||
5530 | const Expr *ReductionOp, | |||
5531 | const Expr *LHS, const Expr *RHS, | |||
5532 | const Expr *PrivateRef) { | |||
5533 | ASTContext &C = CGM.getContext(); | |||
5534 | const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl()); | |||
5535 | const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl()); | |||
5536 | FunctionArgList Args; | |||
5537 | ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
5538 | C.VoidPtrTy, ImplicitParamDecl::Other); | |||
5539 | ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
5540 | ImplicitParamDecl::Other); | |||
5541 | Args.emplace_back(&ParamInOut); | |||
5542 | Args.emplace_back(&ParamIn); | |||
5543 | const auto &FnInfo = | |||
5544 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
5545 | llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); | |||
5546 | std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""}); | |||
5547 | auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, | |||
5548 | Name, &CGM.getModule()); | |||
5549 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); | |||
5550 | Fn->setDoesNotRecurse(); | |||
5551 | CodeGenFunction CGF(CGM); | |||
5552 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); | |||
5553 | llvm::Value *Size = nullptr; | |||
5554 | // If the size of the reduction item is non-constant, load it from global | |||
5555 | // threadprivate variable. | |||
5556 | if (RCG.getSizes(N).second) { | |||
5557 | Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( | |||
5558 | CGF, CGM.getContext().getSizeType(), | |||
5559 | generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); | |||
5560 | Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, | |||
5561 | CGM.getContext().getSizeType(), Loc); | |||
5562 | } | |||
5563 | RCG.emitAggregateType(CGF, N, Size); | |||
5564 | // Remap lhs and rhs variables to the addresses of the function arguments. | |||
5565 | // %lhs = bitcast void* %arg0 to <type>* | |||
5566 | // %rhs = bitcast void* %arg1 to <type>* | |||
5567 | CodeGenFunction::OMPPrivateScope PrivateScope(CGF); | |||
5568 | PrivateScope.addPrivate( | |||
5569 | LHSVD, | |||
5570 | // Pull out the pointer to the variable. | |||
5571 | CGF.EmitLoadOfPointer( | |||
5572 | CGF.Builder.CreateElementBitCast( | |||
5573 | CGF.GetAddrOfLocalVar(&ParamInOut), | |||
5574 | CGF.ConvertTypeForMem(LHSVD->getType())->getPointerTo()), | |||
5575 | C.getPointerType(LHSVD->getType())->castAs<PointerType>())); | |||
5576 | PrivateScope.addPrivate( | |||
5577 | RHSVD, | |||
5578 | // Pull out the pointer to the variable. | |||
5579 | CGF.EmitLoadOfPointer( | |||
5580 | CGF.Builder.CreateElementBitCast( | |||
5581 | CGF.GetAddrOfLocalVar(&ParamIn), | |||
5582 | CGF.ConvertTypeForMem(RHSVD->getType())->getPointerTo()), | |||
5583 | C.getPointerType(RHSVD->getType())->castAs<PointerType>())); | |||
5584 | PrivateScope.Privatize(); | |||
5585 | // Emit the combiner body: | |||
5586 | // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs) | |||
5587 | // store <type> %2, <type>* %lhs | |||
5588 | CGM.getOpenMPRuntime().emitSingleReductionCombiner( | |||
5589 | CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS), | |||
5590 | cast<DeclRefExpr>(RHS)); | |||
5591 | CGF.FinishFunction(); | |||
5592 | return Fn; | |||
5593 | } | |||
5594 | ||||
5595 | /// Emits reduction finalizer function: | |||
5596 | /// \code | |||
5597 | /// void @.red_fini(void* %arg) { | |||
5598 | /// %0 = bitcast void* %arg to <type>* | |||
5599 | /// <destroy>(<type>* %0) | |||
5600 | /// ret void | |||
5601 | /// } | |||
5602 | /// \endcode | |||
5603 | static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM, | |||
5604 | SourceLocation Loc, | |||
5605 | ReductionCodeGen &RCG, unsigned N) { | |||
5606 | if (!RCG.needCleanups(N)) | |||
5607 | return nullptr; | |||
5608 | ASTContext &C = CGM.getContext(); | |||
5609 | FunctionArgList Args; | |||
5610 | ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
5611 | ImplicitParamDecl::Other); | |||
5612 | Args.emplace_back(&Param); | |||
5613 | const auto &FnInfo = | |||
5614 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
5615 | llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); | |||
5616 | std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""}); | |||
5617 | auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, | |||
5618 | Name, &CGM.getModule()); | |||
5619 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); | |||
5620 | Fn->setDoesNotRecurse(); | |||
5621 | CodeGenFunction CGF(CGM); | |||
5622 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); | |||
5623 | Address PrivateAddr = CGF.EmitLoadOfPointer( | |||
5624 | CGF.GetAddrOfLocalVar(&Param), C.VoidPtrTy.castAs<PointerType>()); | |||
5625 | llvm::Value *Size = nullptr; | |||
5626 | // If the size of the reduction item is non-constant, load it from global | |||
5627 | // threadprivate variable. | |||
5628 | if (RCG.getSizes(N).second) { | |||
5629 | Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( | |||
5630 | CGF, CGM.getContext().getSizeType(), | |||
5631 | generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); | |||
5632 | Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, | |||
5633 | CGM.getContext().getSizeType(), Loc); | |||
5634 | } | |||
5635 | RCG.emitAggregateType(CGF, N, Size); | |||
5636 | // Emit the finalizer body: | |||
5637 | // <destroy>(<type>* %0) | |||
5638 | RCG.emitCleanups(CGF, N, PrivateAddr); | |||
5639 | CGF.FinishFunction(Loc); | |||
5640 | return Fn; | |||
5641 | } | |||
5642 | ||||
5643 | llvm::Value *CGOpenMPRuntime::emitTaskReductionInit( | |||
5644 | CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, | |||
5645 | ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) { | |||
5646 | if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty()) | |||
5647 | return nullptr; | |||
5648 | ||||
5649 | // Build typedef struct: | |||
5650 | // kmp_taskred_input { | |||
5651 | // void *reduce_shar; // shared reduction item | |||
5652 | // void *reduce_orig; // original reduction item used for initialization | |||
5653 | // size_t reduce_size; // size of data item | |||
5654 | // void *reduce_init; // data initialization routine | |||
5655 | // void *reduce_fini; // data finalization routine | |||
5656 | // void *reduce_comb; // data combiner routine | |||
5657 | // kmp_task_red_flags_t flags; // flags for additional info from compiler | |||
5658 | // } kmp_taskred_input_t; | |||
5659 | ASTContext &C = CGM.getContext(); | |||
5660 | RecordDecl *RD = C.buildImplicitRecord("kmp_taskred_input_t"); | |||
5661 | RD->startDefinition(); | |||
5662 | const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5663 | const FieldDecl *OrigFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5664 | const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType()); | |||
5665 | const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5666 | const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5667 | const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5668 | const FieldDecl *FlagsFD = addFieldToRecordDecl( | |||
5669 | C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false)); | |||
5670 | RD->completeDefinition(); | |||
5671 | QualType RDType = C.getRecordType(RD); | |||
5672 | unsigned Size = Data.ReductionVars.size(); | |||
5673 | llvm::APInt ArraySize(/*numBits=*/64, Size); | |||
5674 | QualType ArrayRDType = C.getConstantArrayType( | |||
5675 | RDType, ArraySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0); | |||
5676 | // kmp_task_red_input_t .rd_input.[Size]; | |||
5677 | Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input."); | |||
5678 | ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionOrigs, | |||
5679 | Data.ReductionCopies, Data.ReductionOps); | |||
5680 | for (unsigned Cnt = 0; Cnt < Size; ++Cnt) { | |||
5681 | // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt]; | |||
5682 | llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0), | |||
5683 | llvm::ConstantInt::get(CGM.SizeTy, Cnt)}; | |||
5684 | llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP( | |||
5685 | TaskRedInput.getElementType(), TaskRedInput.getPointer(), Idxs, | |||
5686 | /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc, | |||
5687 | ".rd_input.gep."); | |||
5688 | LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType); | |||
5689 | // ElemLVal.reduce_shar = &Shareds[Cnt]; | |||
5690 | LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD); | |||
5691 | RCG.emitSharedOrigLValue(CGF, Cnt); | |||
5692 | llvm::Value *CastedShared = | |||
5693 | CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer(CGF)); | |||
5694 | CGF.EmitStoreOfScalar(CastedShared, SharedLVal); | |||
5695 | // ElemLVal.reduce_orig = &Origs[Cnt]; | |||
5696 | LValue OrigLVal = CGF.EmitLValueForField(ElemLVal, OrigFD); | |||
5697 | llvm::Value *CastedOrig = | |||
5698 | CGF.EmitCastToVoidPtr(RCG.getOrigLValue(Cnt).getPointer(CGF)); | |||
5699 | CGF.EmitStoreOfScalar(CastedOrig, OrigLVal); | |||
5700 | RCG.emitAggregateType(CGF, Cnt); | |||
5701 | llvm::Value *SizeValInChars; | |||
5702 | llvm::Value *SizeVal; | |||
5703 | std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt); | |||
5704 | // We use delayed creation/initialization for VLAs and array sections. It is | |||
5705 | // required because runtime does not provide the way to pass the sizes of | |||
5706 | // VLAs/array sections to initializer/combiner/finalizer functions. Instead | |||
5707 | // threadprivate global variables are used to store these values and use | |||
5708 | // them in the functions. | |||
5709 | bool DelayedCreation = !!SizeVal; | |||
5710 | SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy, | |||
5711 | /*isSigned=*/false); | |||
5712 | LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD); | |||
5713 | CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal); | |||
5714 | // ElemLVal.reduce_init = init; | |||
5715 | LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD); | |||
5716 | llvm::Value *InitAddr = | |||
5717 | CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt)); | |||
5718 | CGF.EmitStoreOfScalar(InitAddr, InitLVal); | |||
5719 | // ElemLVal.reduce_fini = fini; | |||
5720 | LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD); | |||
5721 | llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt); | |||
5722 | llvm::Value *FiniAddr = Fini | |||
5723 | ? CGF.EmitCastToVoidPtr(Fini) | |||
5724 | : llvm::ConstantPointerNull::get(CGM.VoidPtrTy); | |||
5725 | CGF.EmitStoreOfScalar(FiniAddr, FiniLVal); | |||
5726 | // ElemLVal.reduce_comb = comb; | |||
5727 | LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD); | |||
5728 | llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction( | |||
5729 | CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt], | |||
5730 | RHSExprs[Cnt], Data.ReductionCopies[Cnt])); | |||
5731 | CGF.EmitStoreOfScalar(CombAddr, CombLVal); | |||
5732 | // ElemLVal.flags = 0; | |||
5733 | LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD); | |||
5734 | if (DelayedCreation) { | |||
5735 | CGF.EmitStoreOfScalar( | |||
5736 | llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*isSigned=*/true), | |||
5737 | FlagsLVal); | |||
5738 | } else | |||
5739 | CGF.EmitNullInitialization(FlagsLVal.getAddress(CGF), | |||
5740 | FlagsLVal.getType()); | |||
5741 | } | |||
5742 | if (Data.IsReductionWithTaskMod) { | |||
5743 | // Build call void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int | |||
5744 | // is_ws, int num, void *data); | |||
5745 | llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc); | |||
5746 | llvm::Value *GTid = CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), | |||
5747 | CGM.IntTy, /*isSigned=*/true); | |||
5748 | llvm::Value *Args[] = { | |||
5749 | IdentTLoc, GTid, | |||
5750 | llvm::ConstantInt::get(CGM.IntTy, Data.IsWorksharingReduction ? 1 : 0, | |||
5751 | /*isSigned=*/true), | |||
5752 | llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true), | |||
5753 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5754 | TaskRedInput.getPointer(), CGM.VoidPtrTy)}; | |||
5755 | return CGF.EmitRuntimeCall( | |||
5756 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5757 | CGM.getModule(), OMPRTL___kmpc_taskred_modifier_init), | |||
5758 | Args); | |||
5759 | } | |||
5760 | // Build call void *__kmpc_taskred_init(int gtid, int num_data, void *data); | |||
5761 | llvm::Value *Args[] = { | |||
5762 | CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy, | |||
5763 | /*isSigned=*/true), | |||
5764 | llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true), | |||
5765 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(), | |||
5766 | CGM.VoidPtrTy)}; | |||
5767 | return CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
5768 | CGM.getModule(), OMPRTL___kmpc_taskred_init), | |||
5769 | Args); | |||
5770 | } | |||
5771 | ||||
5772 | void CGOpenMPRuntime::emitTaskReductionFini(CodeGenFunction &CGF, | |||
5773 | SourceLocation Loc, | |||
5774 | bool IsWorksharingReduction) { | |||
5775 | // Build call void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int | |||
5776 | // is_ws, int num, void *data); | |||
5777 | llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc); | |||
5778 | llvm::Value *GTid = CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), | |||
5779 | CGM.IntTy, /*isSigned=*/true); | |||
5780 | llvm::Value *Args[] = {IdentTLoc, GTid, | |||
5781 | llvm::ConstantInt::get(CGM.IntTy, | |||
5782 | IsWorksharingReduction ? 1 : 0, | |||
5783 | /*isSigned=*/true)}; | |||
5784 | (void)CGF.EmitRuntimeCall( | |||
5785 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5786 | CGM.getModule(), OMPRTL___kmpc_task_reduction_modifier_fini), | |||
5787 | Args); | |||
5788 | } | |||
5789 | ||||
5790 | void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF, | |||
5791 | SourceLoc |