clang 23.0.0git
CIRGenOpenACCRecipe.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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// Helperes to emit OpenACC clause recipes as CIR code.
10//
11//===----------------------------------------------------------------------===//
12
13#include <numeric>
14
15#include "CIRGenOpenACCRecipe.h"
16
17namespace clang::CIRGen {
18mlir::Block *OpenACCRecipeBuilderBase::createRecipeBlock(mlir::Region &region,
19 mlir::Type opTy,
20 mlir::Location loc,
21 size_t numBounds,
22 bool isInit) {
24 types.reserve(numBounds + 2);
25 types.push_back(opTy);
26 // The init section is the only one that doesn't have TWO copies of the
27 // operation-type. Copy has a to/from, and destroy has a
28 // 'reference'/'privatized' copy version.
29 if (!isInit)
30 types.push_back(opTy);
31
32 auto boundsTy = mlir::acc::DataBoundsType::get(&cgf.getMLIRContext());
33 for (size_t i = 0; i < numBounds; ++i)
34 types.push_back(boundsTy);
35
36 llvm::SmallVector<mlir::Location> locs{types.size(), loc};
37 return builder.createBlock(&region, region.end(), types, locs);
38}
39void OpenACCRecipeBuilderBase::makeAllocaCopy(mlir::Location loc,
40 mlir::Type copyType,
41 mlir::Value numEltsToCopy,
42 mlir::Value offsetPerSubarray,
43 mlir::Value destAlloca,
44 mlir::Value srcAlloca) {
45 mlir::OpBuilder::InsertionGuard guardCase(builder);
46
47 mlir::Type itrTy = cgf.cgm.convertType(cgf.getContext().UnsignedLongLongTy);
48 auto itrPtrTy = cir::PointerType::get(itrTy);
49 mlir::IntegerAttr itrAlign =
52
53 auto loopBuilder = [&]() {
54 auto itr = cir::AllocaOp::create(builder, loc, itrPtrTy, "itr", itrAlign);
55 cir::ConstantOp constZero = builder.getConstInt(loc, itrTy, 0);
56 builder.CIRBaseBuilderTy::createStore(loc, constZero, itr);
58 loc,
59 /*condBuilder=*/
60 [&](mlir::OpBuilder &b, mlir::Location loc) {
61 // itr < numEltsToCopy
62 // Enforce a trip count of 1 if there wasn't any element count, this
63 // way we can just use this loop with a constant bounds instead of a
64 // separate code path.
65 if (!numEltsToCopy)
66 numEltsToCopy = builder.getConstInt(loc, itrTy, 1);
67
68 auto loadCur = cir::LoadOp::create(builder, loc, {itr});
69 auto cmp = builder.createCompare(loc, cir::CmpOpKind::lt, loadCur,
70 numEltsToCopy);
72 },
73 /*bodyBuilder=*/
74 [&](mlir::OpBuilder &b, mlir::Location loc) {
75 // destAlloca[itr] = srcAlloca[offsetPerSubArray * itr];
76 auto loadCur = cir::LoadOp::create(builder, loc, {itr});
77 auto srcOffset = builder.createMul(loc, offsetPerSubarray, loadCur);
78
79 auto ptrToOffsetIntoSrc = cir::PtrStrideOp::create(
80 builder, loc, copyType, srcAlloca, srcOffset);
81
82 auto offsetIntoDecayDest = cir::PtrStrideOp::create(
83 builder, loc, builder.getPointerTo(copyType), destAlloca,
84 loadCur);
85
86 builder.CIRBaseBuilderTy::createStore(loc, ptrToOffsetIntoSrc,
87 offsetIntoDecayDest);
88 builder.createYield(loc);
89 },
90 /*stepBuilder=*/
91 [&](mlir::OpBuilder &b, mlir::Location loc) {
92 // Simple increment of the iterator.
93 auto load = cir::LoadOp::create(builder, loc, {itr});
94 auto inc = builder.createInc(loc, load);
95 builder.CIRBaseBuilderTy::createStore(loc, inc, itr);
96 builder.createYield(loc);
97 });
98 };
99
100 cir::ScopeOp::create(builder, loc,
101 [&](mlir::OpBuilder &b, mlir::Location loc) {
102 loopBuilder();
103 builder.createYield(loc);
104 });
105}
106
107mlir::Value OpenACCRecipeBuilderBase::makeBoundsAlloca(
108 mlir::Block *block, SourceRange exprRange, mlir::Location loc,
109 std::string_view allocaName, size_t numBounds,
110 llvm::ArrayRef<QualType> boundTypes) {
111 mlir::OpBuilder::InsertionGuard guardCase(builder);
112
113 // Get the range of bounds arguments, which are all but the 1st arg.
114 llvm::ArrayRef<mlir::BlockArgument> boundsRange =
115 block->getArguments().drop_front(1);
116
117 // boundTypes contains the before and after of each bounds, so it ends up
118 // having 1 extra. Assert this is the case to ensure we don't call this in the
119 // wrong 'block'.
120 assert(boundsRange.size() + 1 == boundTypes.size());
121
122 mlir::Type itrTy = cgf.cgm.convertType(cgf.getContext().UnsignedLongLongTy);
123 auto idxType = mlir::IndexType::get(&cgf.getMLIRContext());
124
125 auto getUpperBound = [&](mlir::Value bound) {
126 auto upperBoundVal =
127 mlir::acc::GetUpperboundOp::create(builder, loc, idxType, bound);
128 return mlir::UnrealizedConversionCastOp::create(builder, loc, itrTy,
129 upperBoundVal.getResult())
130 .getResult(0);
131 };
132
133 auto isArrayTy = [&](QualType ty) {
134 if (ty->isArrayType() && !ty->isConstantArrayType())
135 cgf.cgm.errorNYI(exprRange, "OpenACC recipe init for VLAs");
136 return ty->isConstantArrayType();
137 };
138
139 mlir::Type topLevelTy = cgf.convertType(boundTypes.back());
140 cir::PointerType topLevelTyPtr = builder.getPointerTo(topLevelTy);
141 // Do an alloca for the 'top' level type without bounds.
142 mlir::Value initialAlloca = builder.createAlloca(
143 loc, topLevelTyPtr, allocaName,
144 cgf.getContext().getTypeAlignInChars(boundTypes.back()));
145
146 bool lastBoundWasArray = isArrayTy(boundTypes.back());
147
148 // Make sure we track a moving version of this so we can get our
149 // 'copying' back to correct.
150 mlir::Value lastAlloca = initialAlloca;
151
152 // Since we're iterating the types in reverse, this sets up for each index
153 // corresponding to the boundsRange to be the 'after application of the
154 // bounds.
155 llvm::ArrayRef<QualType> boundResults = boundTypes.drop_back(1);
156
157 // Collect the 'do we have any allocas needed after this type' list.
158 llvm::SmallVector<bool> allocasLeftArr;
159 llvm::ArrayRef<QualType> resultTypes = boundTypes.drop_front();
160 std::transform_inclusive_scan(
161 resultTypes.begin(), resultTypes.end(),
162 std::back_inserter(allocasLeftArr), std::plus<bool>{},
163 [](QualType ty) { return !ty->isConstantArrayType(); }, false);
164
165 // Keep track of the number of 'elements' that we're allocating. Individual
166 // allocas should multiply this by the size of its current allocation.
167 mlir::Value cumulativeElts;
168 for (auto [bound, resultType, allocasLeft] : llvm::reverse(
169 llvm::zip_equal(boundsRange, boundResults, allocasLeftArr))) {
170
171 // if there is no further 'alloca' operation we need to do, we can skip
172 // creating the UB/multiplications/etc.
173 if (!allocasLeft)
174 break;
175
176 // First: figure out the number of elements in the current 'bound' list.
177 mlir::Value eltsPerSubArray = getUpperBound(bound);
178 mlir::Value eltsToAlloca;
179
180 // IF we are in a sub-bounds, the total number of elements to alloca is
181 // the product of that one and the current 'bounds' size. That is,
182 // arr[5][5], we would need 25 elements, not just 5. Else it is just the
183 // current number of elements.
184 if (cumulativeElts)
185 eltsToAlloca = builder.createMul(loc, eltsPerSubArray, cumulativeElts);
186 else
187 eltsToAlloca = eltsPerSubArray;
188
189 if (!lastBoundWasArray) {
190 // If we have to do an allocation, figure out the size of the
191 // allocation. alloca takes the number of bytes, not elements.
192 TypeInfoChars eltInfo = cgf.getContext().getTypeInfoInChars(resultType);
193 cir::ConstantOp eltSize = builder.getConstInt(
194 loc, itrTy, eltInfo.Width.alignTo(eltInfo.Align).getQuantity());
195 mlir::Value curSize = builder.createMul(loc, eltsToAlloca, eltSize);
196
197 mlir::Type eltTy = cgf.convertType(resultType);
198 cir::PointerType ptrTy = builder.getPointerTo(eltTy);
199 mlir::Value curAlloca = builder.createAlloca(
200 loc, ptrTy, eltTy, "openacc.init.bounds",
201 cgf.getContext().getTypeAlignInChars(resultType), curSize);
202
203 makeAllocaCopy(loc, ptrTy, cumulativeElts, eltsPerSubArray, lastAlloca,
204 curAlloca);
205 lastAlloca = curAlloca;
206 } else {
207 // In the case of an array, we just need to decay the pointer, so just do
208 // a zero-offset stride on the last alloca to decay it down an array
209 // level.
210 cir::ConstantOp constZero = builder.getConstInt(loc, itrTy, 0);
211 lastAlloca = builder.getArrayElement(loc, loc, lastAlloca,
212 cgf.convertType(resultType),
213 constZero, /*shouldDecay=*/true);
214 }
215
216 cumulativeElts = eltsToAlloca;
217 lastBoundWasArray = isArrayTy(resultType);
218 }
219 return initialAlloca;
220}
221
222std::pair<mlir::Value, mlir::Value> OpenACCRecipeBuilderBase::createBoundsLoop(
223 mlir::Value subscriptedValue, mlir::Value subscriptedValue2,
224 mlir::Value bound, mlir::Location loc, bool inverse) {
225 mlir::Operation *bodyInsertLoc;
226
227 mlir::Type itrTy = cgf.cgm.convertType(cgf.getContext().UnsignedLongLongTy);
228 auto itrPtrTy = cir::PointerType::get(itrTy);
229 mlir::IntegerAttr itrAlign =
230 cgf.cgm.getSize(cgf.getContext().getTypeAlignInChars(
231 cgf.getContext().UnsignedLongLongTy));
232 auto idxType = mlir::IndexType::get(&cgf.getMLIRContext());
233
234 auto doSubscriptOp = [&](mlir::Value subVal,
235 cir::LoadOp idxLoad) -> mlir::Value {
236 auto eltTy = cast<cir::PointerType>(subVal.getType()).getPointee();
237
238 if (auto arrayTy = dyn_cast<cir::ArrayType>(eltTy))
239 return builder.getArrayElement(loc, loc, subVal, arrayTy.getElementType(),
240 idxLoad,
241 /*shouldDecay=*/true);
242
243 assert(isa<cir::PointerType>(eltTy));
244
245 auto eltLoad = cir::LoadOp::create(builder, loc, {subVal});
246
247 return cir::PtrStrideOp::create(builder, loc, eltLoad.getType(), eltLoad,
248 idxLoad);
249 };
250
251 auto forStmtBuilder = [&]() {
252 // get the lower and upper bound for iterating over.
253 auto lowerBoundVal =
254 mlir::acc::GetLowerboundOp::create(builder, loc, idxType, bound);
255 auto lbConversion = mlir::UnrealizedConversionCastOp::create(
256 builder, loc, itrTy, lowerBoundVal.getResult());
257 auto upperBoundVal =
258 mlir::acc::GetUpperboundOp::create(builder, loc, idxType, bound);
259 auto ubConversion = mlir::UnrealizedConversionCastOp::create(
260 builder, loc, itrTy, upperBoundVal.getResult());
261
262 // Create a memory location for the iterator.
263 auto itr = cir::AllocaOp::create(builder, loc, itrPtrTy, "iter", itrAlign);
264 // Store to the iterator: either lower bound, or if inverse loop, upper
265 // bound.
266 if (inverse) {
267 cir::ConstantOp constOne = builder.getConstInt(loc, itrTy, 1);
268
269 auto sub =
270 cir::SubOp::create(builder, loc, ubConversion.getResult(0), constOne);
271
272 // Upperbound is exclusive, so subtract 1.
273 builder.CIRBaseBuilderTy::createStore(loc, sub, itr);
274 } else {
275 // Lowerbound is inclusive, so we can include it.
276 builder.CIRBaseBuilderTy::createStore(loc, lbConversion.getResult(0),
277 itr);
278 }
279 // Save the 'end' iterator based on whether we are inverted or not. This
280 // end iterator never changes, so we can just get it and convert it, so no
281 // need to store/load/etc.
282 auto endItr = inverse ? lbConversion : ubConversion;
283
284 builder.createFor(
285 loc,
286 /*condBuilder=*/
287 [&](mlir::OpBuilder &b, mlir::Location loc) {
288 auto loadCur = cir::LoadOp::create(builder, loc, {itr});
289 // Use 'not equal' since we are just doing an increment/decrement.
290 auto cmp = builder.createCompare(
291 loc, inverse ? cir::CmpOpKind::ge : cir::CmpOpKind::lt, loadCur,
292 endItr.getResult(0));
293 builder.createCondition(cmp);
294 },
295 /*bodyBuilder=*/
296 [&](mlir::OpBuilder &b, mlir::Location loc) {
297 auto load = cir::LoadOp::create(builder, loc, {itr});
298
299 if (subscriptedValue)
300 subscriptedValue = doSubscriptOp(subscriptedValue, load);
301 if (subscriptedValue2)
302 subscriptedValue2 = doSubscriptOp(subscriptedValue2, load);
303 bodyInsertLoc = builder.createYield(loc);
304 },
305 /*stepBuilder=*/
306 [&](mlir::OpBuilder &b, mlir::Location loc) {
307 auto load = cir::LoadOp::create(builder, loc, {itr});
308 auto unary = inverse ? builder.createDec(loc, load)
309 : builder.createInc(loc, load);
310 builder.CIRBaseBuilderTy::createStore(loc, unary, itr);
311 builder.createYield(loc);
312 });
313 };
314
315 cir::ScopeOp::create(builder, loc,
316 [&](mlir::OpBuilder &b, mlir::Location loc) {
317 forStmtBuilder();
318 builder.createYield(loc);
319 });
320
321 // Leave the insertion point to be inside the body, so we can loop over
322 // these things.
323 builder.setInsertionPoint(bodyInsertLoc);
324 return {subscriptedValue, subscriptedValue2};
325}
326
327mlir::acc::ReductionOperator
329 switch (op) {
331 return mlir::acc::ReductionOperator::AccAdd;
333 return mlir::acc::ReductionOperator::AccMul;
335 return mlir::acc::ReductionOperator::AccMax;
337 return mlir::acc::ReductionOperator::AccMin;
339 return mlir::acc::ReductionOperator::AccIand;
341 return mlir::acc::ReductionOperator::AccIor;
343 return mlir::acc::ReductionOperator::AccXor;
345 return mlir::acc::ReductionOperator::AccLand;
347 return mlir::acc::ReductionOperator::AccLor;
349 llvm_unreachable("invalid reduction operator");
350 }
351
352 llvm_unreachable("invalid reduction operator");
353}
354
355// This function generates the 'destroy' section for a recipe. Note
356// that this function is not 'insertion point' clean, in that it alters the
357// insertion point to be inside of the 'destroy' section of the recipe, but
358// doesn't restore it aftewards.
360 mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp,
361 CharUnits alignment, QualType origType, size_t numBounds, QualType baseType,
362 mlir::Region &destroyRegion) {
363 mlir::Block *block = createRecipeBlock(destroyRegion, mainOp.getType(), loc,
364 numBounds, /*isInit=*/false);
365 builder.setInsertionPointToEnd(&destroyRegion.back());
366 CIRGenFunction::LexicalScope ls(cgf, loc, block);
367
368 mlir::Type elementTy =
369 mlir::cast<cir::PointerType>(mainOp.getType()).getPointee();
370 auto emitDestroy = [&](mlir::Value var, mlir::Type ty) {
371 Address addr{var, ty, alignment};
372 cgf.emitDestroy(addr, origType,
373 cgf.getDestroyer(QualType::DK_cxx_destructor));
374 };
375
376 if (numBounds) {
377 mlir::OpBuilder::InsertionGuard guardCase(builder);
378 // Get the range of bounds arguments, which are all but the 1st 2. 1st is
379 // a 'reference', 2nd is the 'private' variant we need to destroy from.
381 block->getArguments().drop_front(2);
382
383 mlir::Value subscriptedValue = block->getArgument(1);
384 for (mlir::BlockArgument boundArg : llvm::reverse(boundsRange))
385 subscriptedValue = createBoundsLoop(subscriptedValue, boundArg, loc,
386 /*inverse=*/true);
387
388 emitDestroy(subscriptedValue, cgf.cgm.convertType(origType));
389 } else {
390 // If we don't have any bounds, we can just destroy the variable directly.
391 // The destroy region has a signature of "original item, privatized item".
392 // So the 2nd item is the one that needs destroying, the former is just
393 // for reference and we don't really have a need for it at the moment.
394 emitDestroy(block->getArgument(1), elementTy);
395 }
396
397 ls.forceCleanup();
398 mlir::acc::YieldOp::create(builder, locEnd);
399}
400void OpenACCRecipeBuilderBase::makeBoundsInit(
401 mlir::Value alloca, mlir::Location loc, mlir::Block *block,
402 const VarDecl *allocaDecl, QualType origType, bool isInitSection) {
403 mlir::OpBuilder::InsertionGuard guardCase(builder);
404 builder.setInsertionPointToEnd(block);
405 CIRGenFunction::LexicalScope ls(cgf, loc, block);
406
407 CIRGenFunction::AutoVarEmission tempDeclEmission{*allocaDecl};
408 tempDeclEmission.emittedAsOffload = true;
409
410 // The init section is the only one of the handful that only has a single
411 // argument for the 'type', so we have to drop 1 for init, and future calls
412 // to this will need to drop 2.
414 block->getArguments().drop_front(isInitSection ? 1 : 2);
415
416 mlir::Value subscriptedValue = alloca;
417 for (mlir::BlockArgument boundArg : llvm::reverse(boundsRange))
418 subscriptedValue = createBoundsLoop(subscriptedValue, boundArg, loc,
419 /*inverse=*/false);
420
421 tempDeclEmission.setAllocatedAddress(
422 Address{subscriptedValue, cgf.convertType(origType),
423 cgf.getContext().getDeclAlign(allocaDecl)});
424 cgf.emitAutoVarInit(tempDeclEmission);
425}
426
427// TODO: OpenACC: when we start doing firstprivate for array/vlas/etc, we
428// probably need to do a little work about the 'init' calls to put it in 'copy'
429// region instead.
431 mlir::Location loc, mlir::Location locEnd, SourceRange exprRange,
432 mlir::Value mainOp, mlir::Region &recipeInitRegion, size_t numBounds,
433 llvm::ArrayRef<QualType> boundTypes, const VarDecl *allocaDecl,
434 QualType origType, bool emitInitExpr) {
435 assert(allocaDecl && "Required recipe variable not set?");
436 CIRGenFunction::DeclMapRevertingRAII declMapRAII{cgf, allocaDecl};
437
438 mlir::Block *block = createRecipeBlock(recipeInitRegion, mainOp.getType(),
439 loc, numBounds, /*isInit=*/true);
440 builder.setInsertionPointToEnd(&recipeInitRegion.back());
441 CIRGenFunction::LexicalScope ls(cgf, loc, block);
442
443 const Type *allocaPointeeType =
444 allocaDecl->getType()->getPointeeOrArrayElementType();
445 // We are OK with no init for builtins, arrays of builtins, or pointers,
446 // else we should NYI so we know to go look for these.
447 if (cgf.getContext().getLangOpts().CPlusPlus && !allocaDecl->getInit() &&
448 !allocaDecl->getType()->isPointerType() &&
449 !allocaPointeeType->isBuiltinType() &&
450 !allocaPointeeType->isPointerType()) {
451 // If we don't have any initialization recipe, we failed during Sema to
452 // initialize this correctly. If we disable the
453 // Sema::TentativeAnalysisScopes in SemaOpenACC::CreateInitRecipe, it'll
454 // emit an error to tell us. However, emitting those errors during
455 // production is a violation of the standard, so we cannot do them.
456 cgf.cgm.errorNYI(exprRange, "private/reduction default-init recipe");
457 }
458
459 if (!numBounds) {
460 // This is an 'easy' case, we just have to use the builtin init stuff to
461 // initialize this variable correctly.
462 CIRGenFunction::AutoVarEmission tempDeclEmission =
463 cgf.emitAutoVarAlloca(*allocaDecl, builder.saveInsertionPoint());
464 if (emitInitExpr)
465 cgf.emitAutoVarInit(tempDeclEmission);
466 } else {
467 mlir::Value alloca = makeBoundsAlloca(
468 block, exprRange, loc, allocaDecl->getName(), numBounds, boundTypes);
469
470 // If the initializer is trivial, there is nothing to do here, so save
471 // ourselves some effort.
472 if (emitInitExpr && allocaDecl->getInit() &&
473 (!cgf.isTrivialInitializer(allocaDecl->getInit()) ||
474 cgf.getContext().getLangOpts().getTrivialAutoVarInit() !=
476 makeBoundsInit(alloca, loc, block, allocaDecl, origType,
477 /*isInitSection=*/true);
478 }
479
480 ls.forceCleanup();
481 mlir::acc::YieldOp::create(builder, locEnd);
482}
483
485 mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp,
486 const VarDecl *allocaDecl, const VarDecl *temporary,
487 mlir::Region &copyRegion, size_t numBounds) {
488 mlir::Block *block = createRecipeBlock(copyRegion, mainOp.getType(), loc,
489 numBounds, /*isInit=*/false);
490 builder.setInsertionPointToEnd(&copyRegion.back());
491 CIRGenFunction::LexicalScope ls(cgf, loc, block);
492
493 mlir::Value fromArg = block->getArgument(0);
494 mlir::Value toArg = block->getArgument(1);
495
497 block->getArguments().drop_front(2);
498
499 for (mlir::BlockArgument boundArg : llvm::reverse(boundsRange))
500 std::tie(fromArg, toArg) =
501 createBoundsLoop(fromArg, toArg, boundArg, loc, /*inverse=*/false);
502
503 // Set up the 'to' address.
504 mlir::Type elementTy =
505 mlir::cast<cir::PointerType>(toArg.getType()).getPointee();
506 CIRGenFunction::AutoVarEmission tempDeclEmission(*allocaDecl);
507 tempDeclEmission.emittedAsOffload = true;
508 tempDeclEmission.setAllocatedAddress(
509 Address{toArg, elementTy, cgf.getContext().getDeclAlign(allocaDecl)});
510
511 // Set up the 'from' address from the temporary.
512 CIRGenFunction::DeclMapRevertingRAII declMapRAII{cgf, temporary};
513 cgf.setAddrOfLocalVar(
514 temporary,
515 Address{fromArg, elementTy, cgf.getContext().getDeclAlign(allocaDecl)});
516 cgf.emitAutoVarInit(tempDeclEmission);
517
518 builder.setInsertionPointToEnd(&copyRegion.back());
519 ls.forceCleanup();
520 mlir::acc::YieldOp::create(builder, locEnd);
521}
522
523// This function generates the 'combiner' section for a reduction recipe. Note
524// that this function is not 'insertion point' clean, in that it alters the
525// insertion point to be inside of the 'combiner' section of the recipe, but
526// doesn't restore it aftewards.
528 mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp,
529 mlir::acc::ReductionRecipeOp recipe, size_t numBounds, QualType origType,
531 mlir::Block *block =
532 createRecipeBlock(recipe.getCombinerRegion(), mainOp.getType(), loc,
533 numBounds, /*isInit=*/false);
534 builder.setInsertionPointToEnd(&recipe.getCombinerRegion().back());
535 CIRGenFunction::LexicalScope ls(cgf, loc, block);
536
537 mlir::Value lhsArg = block->getArgument(0);
538 mlir::Value rhsArg = block->getArgument(1);
540 block->getArguments().drop_front(2);
541
542 if (llvm::any_of(combinerRecipes, [](auto &r) { return r.Op == nullptr; })) {
543 cgf.cgm.errorNYI(loc, "OpenACC Reduction combiner not generated");
544 mlir::acc::YieldOp::create(builder, locEnd, block->getArgument(0));
545 return;
546 }
547
548 // apply the bounds so that we can get our bounds emitted correctly.
549 for (mlir::BlockArgument boundArg : llvm::reverse(boundsRange))
550 std::tie(lhsArg, rhsArg) =
551 createBoundsLoop(lhsArg, rhsArg, boundArg, loc, /*inverse=*/false);
552
553 // Emitter for when we know this isn't a struct or array we have to loop
554 // through. This should work for the 'field' once the get-element call has
555 // been made.
556 auto emitSingleCombiner =
557 [&](mlir::Value lhsArg, mlir::Value rhsArg,
559 mlir::Type elementTy =
560 mlir::cast<cir::PointerType>(lhsArg.getType()).getPointee();
561 CIRGenFunction::DeclMapRevertingRAII declMapRAIILhs{cgf, combiner.LHS};
562 cgf.setAddrOfLocalVar(
563 combiner.LHS, Address{lhsArg, elementTy,
564 cgf.getContext().getDeclAlign(combiner.LHS)});
565 CIRGenFunction::DeclMapRevertingRAII declMapRAIIRhs{cgf, combiner.RHS};
566 cgf.setAddrOfLocalVar(
567 combiner.RHS, Address{rhsArg, elementTy,
568 cgf.getContext().getDeclAlign(combiner.RHS)});
569
570 [[maybe_unused]] mlir::LogicalResult stmtRes =
571 cgf.emitStmt(combiner.Op, /*useCurrentScope=*/true);
572 };
573
574 // Emitter for when we know this is either a non-array or element of an array
575 // (which also shouldn't be an array type?). This function should generate the
576 // initialization code for an entire 'array-element'/non-array, including
577 // diving into each element of a struct (if necessary).
578 auto emitCombiner = [&](mlir::Value lhsArg, mlir::Value rhsArg, QualType ty) {
579 assert(!ty->isArrayType() && "Array type shouldn't get here");
580 if (const auto *rd = ty->getAsRecordDecl()) {
581 if (combinerRecipes.size() == 1 &&
582 cgf.getContext().hasSameType(ty, combinerRecipes[0].LHS->getType())) {
583 // If this is a 'top level' operator on the type we can just emit this
584 // as a simple one.
585 emitSingleCombiner(lhsArg, rhsArg, combinerRecipes[0]);
586 } else {
587 // else we have to handle each individual field after after a
588 // get-element.
589 const CIRGenRecordLayout &layout =
590 cgf.cgm.getTypes().getCIRGenRecordLayout(rd);
591 for (const auto &[field, combiner] :
592 llvm::zip_equal(rd->fields(), combinerRecipes)) {
593 mlir::Type fieldType = cgf.convertType(field->getType());
594 auto fieldPtr = cir::PointerType::get(fieldType);
595 unsigned fieldIndex = layout.getCIRFieldNo(field);
596
597 mlir::Value lhsField = builder.createGetMember(
598 loc, fieldPtr, lhsArg, field->getName(), fieldIndex);
599 mlir::Value rhsField = builder.createGetMember(
600 loc, fieldPtr, rhsArg, field->getName(), fieldIndex);
601
602 emitSingleCombiner(lhsField, rhsField, combiner);
603 }
604 }
605
606 } else {
607 // if this is a single-thing (because we should know this isn't an array,
608 // as Sema wouldn't let us get here), we can just do a normal emit call.
609 emitSingleCombiner(lhsArg, rhsArg, combinerRecipes[0]);
610 }
611 };
612
613 if (const auto *cat = cgf.getContext().getAsConstantArrayType(origType)) {
614 // If we're in an array, we have to emit the combiner for each element of
615 // the array.
616 auto itrTy = mlir::cast<cir::IntType>(cgf.ptrDiffTy);
617 auto itrPtrTy = cir::PointerType::get(itrTy);
618
619 mlir::Value zero =
620 builder.getConstInt(loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), 0);
621 mlir::Value itr = cir::AllocaOp::create(
622 builder, loc, itrPtrTy, "itr", cgf.cgm.getSize(cgf.getPointerAlign()));
623 builder.CIRBaseBuilderTy::createStore(loc, zero, itr);
624
625 builder.setInsertionPointAfter(builder.createFor(
626 loc,
627 /*condBuilder=*/
628 [&](mlir::OpBuilder &b, mlir::Location loc) {
629 auto loadItr = cir::LoadOp::create(builder, loc, {itr});
630 mlir::Value arraySize = builder.getConstInt(
631 loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), cat->getZExtSize());
632 auto cmp = builder.createCompare(loc, cir::CmpOpKind::lt, loadItr,
633 arraySize);
634 builder.createCondition(cmp);
635 },
636 /*bodyBuilder=*/
637 [&](mlir::OpBuilder &b, mlir::Location loc) {
638 auto loadItr = cir::LoadOp::create(builder, loc, {itr});
639 auto lhsElt = builder.getArrayElement(
640 loc, loc, lhsArg, cgf.convertType(cat->getElementType()), loadItr,
641 /*shouldDecay=*/true);
642 auto rhsElt = builder.getArrayElement(
643 loc, loc, rhsArg, cgf.convertType(cat->getElementType()), loadItr,
644 /*shouldDecay=*/true);
645
646 emitCombiner(lhsElt, rhsElt, cat->getElementType());
647 builder.createYield(loc);
648 },
649 /*stepBuilder=*/
650 [&](mlir::OpBuilder &b, mlir::Location loc) {
651 auto loadItr = cir::LoadOp::create(builder, loc, {itr});
652 auto inc = builder.createInc(loc, loadItr);
653 builder.CIRBaseBuilderTy::createStore(loc, inc, itr);
654 builder.createYield(loc);
655 }));
656
657 } else if (origType->isArrayType()) {
658 cgf.cgm.errorNYI(loc,
659 "OpenACC Reduction combiner non-constant array recipe");
660 } else {
661 emitCombiner(lhsArg, rhsArg, origType);
662 }
663
664 builder.setInsertionPointToEnd(&recipe.getCombinerRegion().back());
665 ls.forceCleanup();
666 mlir::acc::YieldOp::create(builder, locEnd, block->getArgument(0));
667}
668
669} // namespace clang::CIRGen
cir::ConditionOp createCondition(mlir::Value condition)
Create a loop condition.
cir::ForOp createFor(mlir::Location loc, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> condBuilder, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> bodyBuilder, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> stepBuilder)
Create a for operation.
cir::CmpOp createCompare(mlir::Location loc, cir::CmpOpKind kind, mlir::Value lhs, mlir::Value rhs)
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CanQualType UnsignedLongLongTy
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
void forceCleanup(ArrayRef< mlir::Value * > valuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
mlir::Type convertType(clang::QualType t)
void emitAutoVarInit(const AutoVarEmission &emission)
Emit the initializer for an allocated variable.
clang::ASTContext & getContext() const
mlir::Type convertType(clang::QualType type)
mlir::IntegerAttr getSize(CharUnits size)
This class handles record and union layout info while lowering AST types to CIR types.
unsigned getCIRFieldNo(const clang::FieldDecl *fd) const
Return cir::RecordType element number that corresponds to the field FD.
void createReductionRecipeCombiner(mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp, mlir::acc::ReductionRecipeOp recipe, size_t numBounds, QualType origType, llvm::ArrayRef< OpenACCReductionRecipe::CombinerRecipe > combinerRecipes)
void createInitRecipe(mlir::Location loc, mlir::Location locEnd, SourceRange exprRange, mlir::Value mainOp, mlir::Region &recipeInitRegion, size_t numBounds, llvm::ArrayRef< QualType > boundTypes, const VarDecl *allocaDecl, QualType origType, bool emitInitExpr)
void createFirstprivateRecipeCopy(mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp, const VarDecl *allocaDecl, const VarDecl *temporary, mlir::Region &copyRegion, size_t numBounds)
mlir::acc::ReductionOperator convertReductionOp(OpenACCReductionOperator op)
std::pair< mlir::Value, mlir::Value > createBoundsLoop(mlir::Value subscriptedValue, mlir::Value subscriptedValue2, mlir::Value bound, mlir::Location loc, bool inverse)
void createRecipeDestroySection(mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp, CharUnits alignment, QualType origType, size_t numBounds, QualType baseType, mlir::Region &destroyRegion)
mlir::Block * createRecipeBlock(mlir::Region &region, mlir::Type opTy, mlir::Location loc, size_t numBounds, bool isInit)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
A (possibly-)qualified type.
Definition TypeBase.h:937
A trivial tuple used to represent a source range.
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9237
bool isArrayType() const
Definition TypeBase.h:8783
bool isPointerType() const
Definition TypeBase.h:8684
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
const Expr * getInit() const
Definition Decl.h:1381
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
OpenACCReductionOperator
@ Invalid
Invalid Reduction Clause Kind.
bool isa(CodeGen::Address addr)
Definition Address.h:330
U cast(CodeGen::Address addr)
Definition Address.h:327
bool emittedAsOffload
True if the variable was emitted as an offload recipe, and thus doesn't have the same sort of alloca ...
Represents a scope, including function bodies, compound statements, and the substatements of if/while...