Debian Codegraph @

clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp

raw
1 //===- CIRGenExprAggregrate.cpp - Emit CIR Code from Aggregate Expressions ===//
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 contains code to emit Aggregate Expr nodes as CIR code.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "CIRGenBuilder.h"
14 #include "CIRGenFunction.h"
15 #include "CIRGenValue.h"
16 #include "clang/CIR/Dialect/IR/CIRAttrs.h"
17
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include <cstdint>
22
23 using namespace clang;
24 using namespace clang::CIRGen;
25
26 namespace {
27 // FIXME(cir): This should be a common helper between CIRGen
28 // and traditional CodeGen
29 /// Is the value of the given expression possibly a reference to or
30 /// into a __block variable?
31 static bool isBlockVarRef(const Expr *e) {
32 // Make sure we look through parens.
33 e = e->IgnoreParens();
34
35 // Check for a direct reference to a __block variable.
36 if (const DeclRefExpr *dre = dyn_cast<DeclRefExpr>(e)) {
37 const VarDecl *var = dyn_cast<VarDecl>(dre->getDecl());
38 return (var && var->hasAttr<BlocksAttr>());
39 }
40
41 // More complicated stuff.
42
43 // Binary operators.
44 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(e)) {
45 // For an assignment or pointer-to-member operation, just care
46 // about the LHS.
47 if (op->isAssignmentOp() || op->isPtrMemOp())
48 return isBlockVarRef(op->getLHS());
49
50 // For a comma, just care about the RHS.
51 if (op->getOpcode() == BO_Comma)
52 return isBlockVarRef(op->getRHS());
53
54 // FIXME: pointer arithmetic?
55 return false;
56
57 // Check both sides of a conditional operator.
58 } else if (const AbstractConditionalOperator *op =
59 dyn_cast<AbstractConditionalOperator>(e)) {
60 return isBlockVarRef(op->getTrueExpr()) ||
61 isBlockVarRef(op->getFalseExpr());
62
63 // OVEs are required to support BinaryConditionalOperators.
64 } else if (const OpaqueValueExpr *op = dyn_cast<OpaqueValueExpr>(e)) {
65 if (const Expr *src = op->getSourceExpr())
66 return isBlockVarRef(src);
67
68 // Casts are necessary to get things like (*(int*)&var) = foo().
69 // We don't really care about the kind of cast here, except
70 // we don't want to look through l2r casts, because it's okay
71 // to get the *value* in a __block variable.
72 } else if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
73 if (cast->getCastKind() == CK_LValueToRValue)
74 return false;
75 return isBlockVarRef(cast->getSubExpr());
76
77 // Handle unary operators. Again, just aggressively look through
78 // it, ignoring the operation.
79 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
80 return isBlockVarRef(uop->getSubExpr());
81
82 // Look into the base of a field access.
83 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
84 return isBlockVarRef(mem->getBase());
85
86 // Look into the base of a subscript.
87 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(e)) {
88 return isBlockVarRef(sub->getBase());
89 }
90
91 return false;
92 }
93
94 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
95
96 CIRGenFunction &cgf;
97 AggValueSlot dest;
98
99 // Calls `fn` with a valid return value slot, potentially creating a temporary
100 // to do so. If a temporary is created, an appropriate copy into `Dest` will
101 // be emitted, as will lifetime markers.
102 //
103 // The given function should take a ReturnValueSlot, and return an RValue that
104 // points to said slot.
105 void withReturnValueSlot(const Expr *e,
106 llvm::function_ref<RValue(ReturnValueSlot)> fn);
107
108 AggValueSlot ensureSlot(mlir::Location loc, QualType t) {
109 if (!dest.isIgnored())
110 return dest;
111 return cgf.createAggTemp(t, loc, "agg.tmp.ensured");
112 }
113
114 void ensureDest(mlir::Location loc, QualType ty) {
115 if (!dest.isIgnored())
116 return;
117 dest = cgf.createAggTemp(ty, loc, "agg.tmp.ensured");
118 }
119
120 public:
121 AggExprEmitter(CIRGenFunction &cgf, AggValueSlot dest)
122 : cgf(cgf), dest(dest) {}
123
124 /// Given an expression with aggregate type that represents a value lvalue,
125 /// this method emits the address of the lvalue, then loads the result into
126 /// DestPtr.
127 void emitAggLoadOfLValue(const Expr *e);
128
129 void emitArrayInit(Address destPtr, cir::ArrayType arrayTy, QualType arrayQTy,
130 Expr *exprToVisit, ArrayRef<Expr *> args,
131 Expr *arrayFiller);
132
133 void emitFinalDestCopy(QualType type, RValue src);
134
135 /// Perform the final copy to DestPtr, if desired.
136 void emitFinalDestCopy(QualType type, const LValue &src,
137 CIRGenFunction::ExprValueKind srcValueKind =
138 CIRGenFunction::EVK_NonRValue);
139
140 void emitCopy(QualType type, const AggValueSlot &dest,
141 const AggValueSlot &src);
142
143 void emitInitializationToLValue(Expr *e, LValue lv);
144
145 void emitNullInitializationToLValue(mlir::Location loc, LValue lv);
146
147 void Visit(Expr *e) { StmtVisitor<AggExprEmitter>::Visit(e); }
148
149 void VisitArraySubscriptExpr(ArraySubscriptExpr *e) {
150 emitAggLoadOfLValue(e);
151 }
152
153 void VisitCallExpr(const CallExpr *e);
154 void VisitStmtExpr(const StmtExpr *e) {
155 CIRGenFunction::StmtExprEvaluation eval(cgf);
156 Address retAlloca =
157 cgf.createMemTemp(e->getType(), cgf.getLoc(e->getSourceRange()));
158 (void)cgf.emitCompoundStmt(*e->getSubStmt(), &retAlloca, dest);
159 }
160
161 void VisitBinAssign(const BinaryOperator *e) {
162 // For an assignment to work, the value on the right has
163 // to be compatible with the value on the left.
164 assert(cgf.getContext().hasSameUnqualifiedType(e->getLHS()->getType(),
165 e->getRHS()->getType()) &&
166 "Invalid assignment");
167
168 if (isBlockVarRef(e->getLHS()) &&
169 e->getRHS()->HasSideEffects(cgf.getContext())) {
170 cgf.cgm.errorNYI(e->getSourceRange(),
171 "block var reference with side effects");
172 return;
173 }
174
175 LValue lhs = cgf.emitLValue(e->getLHS());
176
177 // If we have an atomic type, evaluate into the destination and then
178 // do an atomic copy.
179 assert(!cir::MissingFeatures::atomicTypes());
180
181 // Codegen the RHS so that it stores directly into the LHS.
182 assert(!cir::MissingFeatures::aggValueSlotGC());
183 AggValueSlot lhsSlot = AggValueSlot::forLValue(
184 lhs, AggValueSlot::IsDestructed, AggValueSlot::IsAliased,
185 AggValueSlot::MayOverlap);
186
187 // A non-volatile aggregate destination might have volatile member.
188 if (!lhsSlot.isVolatile() && cgf.hasVolatileMember(e->getLHS()->getType()))
189 lhsSlot.setVolatile(true);
190
191 cgf.emitAggExpr(e->getRHS(), lhsSlot);
192
193 // Copy into the destination if the assignment isn't ignored.
194 emitFinalDestCopy(e->getType(), lhs);
195
196 if (!dest.isIgnored() && !dest.isExternallyDestructed() &&
197 e->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
198 cgf.pushDestroy(QualType::DK_nontrivial_c_struct, dest.getAddress(),
199 e->getType());
200 }
201
202 void VisitDeclRefExpr(DeclRefExpr *e) { emitAggLoadOfLValue(e); }
203
204 void VisitInitListExpr(InitListExpr *e);
205 void VisitCXXConstructExpr(const CXXConstructExpr *e);
206
207 void visitCXXParenListOrInitListExpr(Expr *e, ArrayRef<Expr *> args,
208 FieldDecl *initializedFieldInUnion,
209 Expr *arrayFiller);
210 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *die) {
211 CIRGenFunction::CXXDefaultInitExprScope Scope(cgf, die);
212 Visit(die->getExpr());
213 }
214 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *e) {
215 // Ensure that we have a slot, but if we already do, remember
216 // whether it was externally destructed.
217 bool wasExternallyDestructed = dest.isExternallyDestructed();
218 ensureDest(cgf.getLoc(e->getSourceRange()), e->getType());
219
220 // We're going to push a destructor if there isn't already one.
221 dest.setExternallyDestructed();
222
223 Visit(e->getSubExpr());
224
225 // Push that destructor we promised.
226 if (!wasExternallyDestructed)
227 cgf.emitCXXTemporary(e->getTemporary(), e->getType(), dest.getAddress());
228 }
229 void VisitLambdaExpr(LambdaExpr *e);
230 void VisitExprWithCleanups(ExprWithCleanups *e);
231
232 // Stubs -- These should be moved up when they are implemented.
233 void VisitCastExpr(CastExpr *e) {
234 switch (e->getCastKind()) {
235 case CK_LValueToRValue:
236 // If we're loading from a volatile type, force the destination
237 // into existence.
238 if (e->getSubExpr()->getType().isVolatileQualified())
239 cgf.cgm.errorNYI(e->getSourceRange(),
240 "AggExprEmitter: volatile lvalue-to-rvalue cast");
241 [[fallthrough]];
242 case CK_NoOp:
243 case CK_UserDefinedConversion:
244 case CK_ConstructorConversion:
245 assert(cgf.getContext().hasSameUnqualifiedType(e->getSubExpr()->getType(),
246 e->getType()) &&
247 "Implicit cast types must be compatible");
248 Visit(e->getSubExpr());
249 break;
250 default:
251 cgf.cgm.errorNYI(e->getSourceRange(),
252 std::string("AggExprEmitter: VisitCastExpr: ") +
253 e->getCastKindName());
254 break;
255 }
256 }
257 void VisitStmt(Stmt *s) {
258 cgf.cgm.errorNYI(s->getSourceRange(),
259 std::string("AggExprEmitter::VisitStmt: ") +
260 s->getStmtClassName());
261 }
262 void VisitParenExpr(ParenExpr *pe) { Visit(pe->getSubExpr()); }
263 void VisitGenericSelectionExpr(GenericSelectionExpr *ge) {
264 Visit(ge->getResultExpr());
265 }
266 void VisitCoawaitExpr(CoawaitExpr *e) {
267 cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter: VisitCoawaitExpr");
268 }
269 void VisitCoyieldExpr(CoyieldExpr *e) {
270 cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter: VisitCoyieldExpr");
271 }
272 void VisitUnaryCoawait(UnaryOperator *e) {
273 cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter: VisitUnaryCoawait");
274 }
275 void VisitUnaryExtension(UnaryOperator *e) { Visit(e->getSubExpr()); }
276 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *e) {
277 cgf.cgm.errorNYI(e->getSourceRange(),
278 "AggExprEmitter: VisitSubstNonTypeTemplateParmExpr");
279 }
280 void VisitConstantExpr(ConstantExpr *e) {
281 cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter: VisitConstantExpr");
282 }
283 void VisitMemberExpr(MemberExpr *e) { emitAggLoadOfLValue(e); }
284 void VisitUnaryDeref(UnaryOperator *e) { emitAggLoadOfLValue(e); }
285 void VisitStringLiteral(StringLiteral *e) { emitAggLoadOfLValue(e); }
286 void VisitCompoundLiteralExpr(CompoundLiteralExpr *e);
287
288 void VisitPredefinedExpr(const PredefinedExpr *e) {
289 cgf.cgm.errorNYI(e->getSourceRange(),
290 "AggExprEmitter: VisitPredefinedExpr");
291 }
292 void VisitBinaryOperator(const BinaryOperator *e) {
293 cgf.cgm.errorNYI(e->getSourceRange(),
294 "AggExprEmitter: VisitBinaryOperator");
295 }
296 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *e) {
297 cgf.cgm.errorNYI(e->getSourceRange(),
298 "AggExprEmitter: VisitPointerToDataMemberBinaryOperator");
299 }
300 void VisitBinComma(const BinaryOperator *e) {
301 cgf.emitIgnoredExpr(e->getLHS());
302 Visit(e->getRHS());
303 }
304 void VisitBinCmp(const BinaryOperator *e) {
305 cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter: VisitBinCmp");
306 }
307 void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *e) {
308 cgf.cgm.errorNYI(e->getSourceRange(),
309 "AggExprEmitter: VisitCXXRewrittenBinaryOperator");
310 }
311 void VisitObjCMessageExpr(ObjCMessageExpr *e) {
312 cgf.cgm.errorNYI(e->getSourceRange(),
313 "AggExprEmitter: VisitObjCMessageExpr");
314 }
315 void VisitObjCIVarRefExpr(ObjCIvarRefExpr *e) {
316 cgf.cgm.errorNYI(e->getSourceRange(),
317 "AggExprEmitter: VisitObjCIVarRefExpr");
318 }
319
320 void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *e) {
321 AggValueSlot dest = ensureSlot(cgf.getLoc(e->getExprLoc()), e->getType());
322 LValue destLV = cgf.makeAddrLValue(dest.getAddress(), e->getType());
323 emitInitializationToLValue(e->getBase(), destLV);
324 VisitInitListExpr(e->getUpdater());
325 }
326 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *e) {
327 cgf.cgm.errorNYI(e->getSourceRange(),
328 "AggExprEmitter: VisitAbstractConditionalOperator");
329 }
330 void VisitChooseExpr(const ChooseExpr *e) { Visit(e->getChosenSubExpr()); }
331 void VisitCXXParenListInitExpr(CXXParenListInitExpr *e) {
332 visitCXXParenListOrInitListExpr(e, e->getInitExprs(),
333 e->getInitializedFieldInUnion(),
334 e->getArrayFiller());
335 }
336
337 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *e,
338 llvm::Value *outerBegin = nullptr) {
339 cgf.cgm.errorNYI(e->getSourceRange(),
340 "AggExprEmitter: VisitArrayInitLoopExpr");
341 }
342 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *e) {
343 cgf.cgm.errorNYI(e->getSourceRange(),
344 "AggExprEmitter: VisitImplicitValueInitExpr");
345 }
346 void VisitNoInitExpr(NoInitExpr *e) {
347 cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter: VisitNoInitExpr");
348 }
349 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *dae) {
350 CIRGenFunction::CXXDefaultArgExprScope scope(cgf, dae);
351 Visit(dae->getExpr());
352 }
353 void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *e) {
354 cgf.cgm.errorNYI(e->getSourceRange(),
355 "AggExprEmitter: VisitCXXInheritedCtorInitExpr");
356 }
357 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *e) {
358 cgf.cgm.errorNYI(e->getSourceRange(),
359 "AggExprEmitter: VisitCXXStdInitializerListExpr");
360 }
361 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *e) {
362 cgf.cgm.errorNYI(e->getSourceRange(),
363 "AggExprEmitter: VisitCXXScalarValueInitExpr");
364 }
365 void VisitCXXTypeidExpr(CXXTypeidExpr *e) {
366 cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter: VisitCXXTypeidExpr");
367 }
368 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *e) {
369 Visit(e->getSubExpr());
370 }
371 void VisitOpaqueValueExpr(OpaqueValueExpr *e) {
372 cgf.cgm.errorNYI(e->getSourceRange(),
373 "AggExprEmitter: VisitOpaqueValueExpr");
374 }
375
376 void VisitPseudoObjectExpr(PseudoObjectExpr *e) {
377 cgf.cgm.errorNYI(e->getSourceRange(),
378 "AggExprEmitter: VisitPseudoObjectExpr");
379 }
380
381 void VisitVAArgExpr(VAArgExpr *e) {
382 // emitVAArg returns an aggregate value (not a pointer) at the CIR level.
383 // ABI-specific pointer handling will be done later in LoweringPrepare.
384 mlir::Value vaArgValue = cgf.emitVAArg(e);
385
386 // Create a temporary alloca to hold the aggregate value.
387 mlir::Location loc = cgf.getLoc(e->getSourceRange());
388 Address tmpAddr = cgf.createMemTemp(e->getType(), loc, "vaarg.tmp");
389
390 // Store the va_arg result into the temporary.
391 cgf.emitAggregateStore(vaArgValue, tmpAddr);
392
393 // Create an LValue from the temporary address.
394 LValue tmpLValue = cgf.makeAddrLValue(tmpAddr, e->getType());
395
396 // Copy the aggregate value from temporary to destination.
397 emitFinalDestCopy(e->getType(), tmpLValue);
398 }
399
400 void VisitCXXThrowExpr(const CXXThrowExpr *e) {
401 cgf.cgm.errorNYI(e->getSourceRange(), "AggExprEmitter: VisitCXXThrowExpr");
402 }
403 void VisitAtomicExpr(AtomicExpr *e) {
404 RValue result = cgf.emitAtomicExpr(e);
405 emitFinalDestCopy(e->getType(), result);
406 }
407 };
408
409 } // namespace
410
411 static bool isTrivialFiller(Expr *e) {
412 if (!e)
413 return true;
414
415 if (isa<ImplicitValueInitExpr>(e))
416 return true;
417
418 if (auto *ile = dyn_cast<InitListExpr>(e)) {
419 if (ile->getNumInits())
420 return false;
421 return isTrivialFiller(ile->getArrayFiller());
422 }
423
424 if (const auto *cons = dyn_cast_or_null<CXXConstructExpr>(e))
425 return cons->getConstructor()->isDefaultConstructor() &&
426 cons->getConstructor()->isTrivial();
427
428 return false;
429 }
430
431 /// Given an expression with aggregate type that represents a value lvalue, this
432 /// method emits the address of the lvalue, then loads the result into DestPtr.
433 void AggExprEmitter::emitAggLoadOfLValue(const Expr *e) {
434 LValue lv = cgf.emitLValue(e);
435
436 // If the type of the l-value is atomic, then do an atomic load.
437 assert(!cir::MissingFeatures::opLoadStoreAtomic());
438
439 emitFinalDestCopy(e->getType(), lv);
440 }
441
442 void AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *e) {
443 if (dest.isPotentiallyAliased() && e->getType().isPODType(cgf.getContext())) {
444 // For a POD type, just emit a load of the lvalue + a copy, because our
445 // compound literal might alias the destination.
446 emitAggLoadOfLValue(e);
447 return;
448 }
449
450 AggValueSlot slot = ensureSlot(cgf.getLoc(e->getSourceRange()), e->getType());
451
452 // Block-scope compound literals are destroyed at the end of the enclosing
453 // scope in C.
454 bool destruct =
455 !cgf.getLangOpts().CPlusPlus && !slot.isExternallyDestructed();
456 if (destruct)
457 slot.setExternallyDestructed();
458
459 cgf.emitAggExpr(e->getInitializer(), slot);
460
461 if (destruct)
462 if ([[maybe_unused]] QualType::DestructionKind dtorKind =
463 e->getType().isDestructedType())
464 cgf.cgm.errorNYI(e->getSourceRange(), "compound literal with destructor");
465 }
466
467 void AggExprEmitter::emitArrayInit(Address destPtr, cir::ArrayType arrayTy,
468 QualType arrayQTy, Expr *e,
469 ArrayRef<Expr *> args, Expr *arrayFiller) {
470 CIRGenBuilderTy &builder = cgf.getBuilder();
471 const mlir::Location loc = cgf.getLoc(e->getSourceRange());
472
473 const uint64_t numInitElements = args.size();
474
475 const QualType elementType =
476 cgf.getContext().getAsArrayType(arrayQTy)->getElementType();
477
478 if (elementType.isDestructedType() && cgf.cgm.getLangOpts().Exceptions) {
479 cgf.cgm.errorNYI(loc, "initialized array requires destruction");
480 return;
481 }
482
483 const QualType elementPtrType = cgf.getContext().getPointerType(elementType);
484
485 const mlir::Type cirElementType = cgf.convertType(elementType);
486 const cir::PointerType cirElementPtrType =
487 builder.getPointerTo(cirElementType);
488
489 auto begin = cir::CastOp::create(builder, loc, cirElementPtrType,
490 cir::CastKind::array_to_ptrdecay,
491 destPtr.getPointer());
492
493 const CharUnits elementSize =
494 cgf.getContext().getTypeSizeInChars(elementType);
495 const CharUnits elementAlign =
496 destPtr.getAlignment().alignmentOfArrayElement(elementSize);
497
498 // The 'current element to initialize'. The invariants on this
499 // variable are complicated. Essentially, after each iteration of
500 // the loop, it points to the last initialized element, except
501 // that it points to the beginning of the array before any
502 // elements have been initialized.
503 mlir::Value element = begin;
504
505 // Don't build the 'one' before the cycle to avoid
506 // emmiting the redundant `cir.const 1` instrs.
507 mlir::Value one;
508
509 // Emit the explicit initializers.
510 for (uint64_t i = 0; i != numInitElements; ++i) {
511 // Advance to the next element.
512 if (i > 0) {
513 one = builder.getConstantInt(loc, cgf.ptrDiffTy, i);
514 element = builder.createPtrStride(loc, begin, one);
515 }
516
517 const Address address = Address(element, cirElementType, elementAlign);
518 const LValue elementLV = cgf.makeAddrLValue(address, elementType);
519 emitInitializationToLValue(args[i], elementLV);
520 }
521
522 const uint64_t numArrayElements = arrayTy.getSize();
523
524 // Check whether there's a non-trivial array-fill expression.
525 const bool hasTrivialFiller = isTrivialFiller(arrayFiller);
526
527 // Any remaining elements need to be zero-initialized, possibly
528 // using the filler expression. We can skip this if the we're
529 // emitting to zeroed memory.
530 if (numInitElements != numArrayElements &&
531 !(dest.isZeroed() && hasTrivialFiller &&
532 cgf.getTypes().isZeroInitializable(elementType))) {
533 // Advance to the start of the rest of the array.
534 if (numInitElements) {
535 one = builder.getConstantInt(loc, cgf.ptrDiffTy, 1);
536 element = cir::PtrStrideOp::create(builder, loc, cirElementPtrType,
537 element, one);
538 }
539
540 // Allocate the temporary variable
541 // to store the pointer to first unitialized element
542 const Address tmpAddr = cgf.createTempAlloca(
543 cirElementPtrType, cgf.getPointerAlign(), loc, "arrayinit.temp");
544 LValue tmpLV = cgf.makeAddrLValue(tmpAddr, elementPtrType);
545 cgf.emitStoreThroughLValue(RValue::get(element), tmpLV);
546
547 // Compute the end of array
548 cir::ConstantOp numArrayElementsConst = builder.getConstInt(
549 loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), numArrayElements);
550 mlir::Value end = cir::PtrStrideOp::create(builder, loc, cirElementPtrType,
551 begin, numArrayElementsConst);
552
553 builder.createDoWhile(
554 loc,
555 /*condBuilder=*/
556 [&](mlir::OpBuilder &b, mlir::Location loc) {
557 cir::LoadOp currentElement = builder.createLoad(loc, tmpAddr);
558 cir::CmpOp cmp = cir::CmpOp::create(builder, loc, cir::CmpOpKind::ne,
559 currentElement, end);
560 builder.createCondition(cmp);
561 },
562 /*bodyBuilder=*/
563 [&](mlir::OpBuilder &b, mlir::Location loc) {
564 cir::LoadOp currentElement = builder.createLoad(loc, tmpAddr);
565
566 assert(!cir::MissingFeatures::requiresCleanups());
567
568 // Emit the actual filler expression.
569 LValue elementLV = cgf.makeAddrLValue(
570 Address(currentElement, cirElementType, elementAlign),
571 elementType);
572 if (arrayFiller)
573 emitInitializationToLValue(arrayFiller, elementLV);
574 else
575 emitNullInitializationToLValue(loc, elementLV);
576
577 // Tell the EH cleanup that we finished with the last element.
578 if (cgf.cgm.getLangOpts().Exceptions) {
579 cgf.cgm.errorNYI(loc, "update destructed array element for EH");
580 return;
581 }
582
583 // Advance pointer and store them to temporary variable
584 cir::ConstantOp one = builder.getConstInt(
585 loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), 1);
586 auto nextElement = cir::PtrStrideOp::create(
587 builder, loc, cirElementPtrType, currentElement, one);
588 cgf.emitStoreThroughLValue(RValue::get(nextElement), tmpLV);
589
590 builder.createYield(loc);
591 });
592 }
593 }
594
595 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
596 void AggExprEmitter::emitFinalDestCopy(QualType type, RValue src) {
597 assert(src.isAggregate() && "value must be aggregate value!");
598 LValue srcLV = cgf.makeAddrLValue(src.getAggregateAddress(), type);
599 emitFinalDestCopy(type, srcLV, CIRGenFunction::EVK_RValue);
600 }
601
602 /// Perform the final copy to destPtr, if desired.
603 void AggExprEmitter::emitFinalDestCopy(
604 QualType type, const LValue &src,
605 CIRGenFunction::ExprValueKind srcValueKind) {
606 // If dest is ignored, then we're evaluating an aggregate expression
607 // in a context that doesn't care about the result. Note that loads
608 // from volatile l-values force the existence of a non-ignored
609 // destination.
610 if (dest.isIgnored())
611 return;
612
613 if (srcValueKind == CIRGenFunction::EVK_RValue) {
614 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
615 cgf.cgm.errorNYI("emitFinalDestCopy: EVK_RValue & PCK_Struct");
616 }
617 } else {
618 if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
619 cgf.cgm.errorNYI("emitFinalDestCopy: !EVK_RValue & PCK_Struct");
620 }
621 }
622
623 assert(!cir::MissingFeatures::aggValueSlotVolatile());
624 assert(!cir::MissingFeatures::aggEmitFinalDestCopyRValue());
625 assert(!cir::MissingFeatures::aggValueSlotGC());
626
627 AggValueSlot srcAgg = AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
628 AggValueSlot::IsAliased,
629 AggValueSlot::MayOverlap);
630 emitCopy(type, dest, srcAgg);
631 }
632
633 /// Perform a copy from the source into the destination.
634 ///
635 /// \param type - the type of the aggregate being copied; qualifiers are
636 /// ignored
637 void AggExprEmitter::emitCopy(QualType type, const AggValueSlot &dest,
638 const AggValueSlot &src) {
639 assert(!cir::MissingFeatures::aggValueSlotGC());
640
641 // If the result of the assignment is used, copy the LHS there also.
642 // It's volatile if either side is. Use the minimum alignment of
643 // the two sides.
644 LValue destLV = cgf.makeAddrLValue(dest.getAddress(), type);
645 LValue srcLV = cgf.makeAddrLValue(src.getAddress(), type);
646 assert(!cir::MissingFeatures::aggValueSlotVolatile());
647 cgf.emitAggregateCopy(destLV, srcLV, type, dest.mayOverlap(),
648 dest.isVolatile() || src.isVolatile());
649 }
650
651 void AggExprEmitter::emitInitializationToLValue(Expr *e, LValue lv) {
652 const QualType type = lv.getType();
653
654 if (isa<ImplicitValueInitExpr, CXXScalarValueInitExpr>(e)) {
655 const mlir::Location loc = e->getSourceRange().isValid()
656 ? cgf.getLoc(e->getSourceRange())
657 : *cgf.currSrcLoc;
658 return emitNullInitializationToLValue(loc, lv);
659 }
660
661 if (isa<NoInitExpr>(e))
662 return;
663
664 if (type->isReferenceType()) {
665 RValue rv = cgf.emitReferenceBindingToExpr(e);
666 return cgf.emitStoreThroughLValue(rv, lv);
667 }
668
669 switch (cgf.getEvaluationKind(type)) {
670 case cir::TEK_Complex:
671 cgf.emitComplexExprIntoLValue(e, lv, /*isInit*/ true);
672 break;
673 case cir::TEK_Aggregate:
674 cgf.emitAggExpr(e, AggValueSlot::forLValue(lv, AggValueSlot::IsDestructed,
675 AggValueSlot::IsNotAliased,
676 AggValueSlot::MayOverlap,
677 dest.isZeroed()));
678
679 return;
680 case cir::TEK_Scalar:
681 if (lv.isSimple())
682 cgf.emitScalarInit(e, cgf.getLoc(e->getSourceRange()), lv);
683 else
684 cgf.emitStoreThroughLValue(RValue::get(cgf.emitScalarExpr(e)), lv);
685 return;
686 }
687 }
688
689 void AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *e) {
690 AggValueSlot slot = ensureSlot(cgf.getLoc(e->getSourceRange()), e->getType());
691 cgf.emitCXXConstructExpr(e, slot);
692 }
693
694 void AggExprEmitter::emitNullInitializationToLValue(mlir::Location loc,
695 LValue lv) {
696 const QualType type = lv.getType();
697
698 // If the destination slot is already zeroed out before the aggregate is
699 // copied into it, we don't have to emit any zeros here.
700 if (dest.isZeroed() && cgf.getTypes().isZeroInitializable(type))
701 return;
702
703 if (cgf.hasScalarEvaluationKind(type)) {
704 // For non-aggregates, we can store the appropriate null constant.
705 mlir::Value null = cgf.cgm.emitNullConstant(type, loc);
706 if (lv.isSimple()) {
707 cgf.emitStoreOfScalar(null, lv, /* isInitialization */ true);
708 return;
709 }
710
711 cgf.emitStoreThroughBitfieldLValue(RValue::get(null), lv);
712 return;
713 }
714
715 // There's a potential optimization opportunity in combining
716 // memsets; that would be easy for arrays, but relatively
717 // difficult for structures with the current code.
718 cgf.emitNullInitialization(loc, lv.getAddress(), lv.getType());
719 }
720
721 void AggExprEmitter::VisitLambdaExpr(LambdaExpr *e) {
722 CIRGenFunction::SourceLocRAIIObject loc{cgf, cgf.getLoc(e->getSourceRange())};
723 AggValueSlot slot = ensureSlot(cgf.getLoc(e->getSourceRange()), e->getType());
724 [[maybe_unused]] LValue slotLV =
725 cgf.makeAddrLValue(slot.getAddress(), e->getType());
726
727 // We'll need to enter cleanup scopes in case any of the element
728 // initializers throws an exception or contains branch out of the expressions.
729 assert(!cir::MissingFeatures::opScopeCleanupRegion());
730
731 for (auto [curField, capture, captureInit] : llvm::zip(
732 e->getLambdaClass()->fields(), e->captures(), e->capture_inits())) {
733 // Pick a name for the field.
734 llvm::StringRef fieldName = curField->getName();
735 if (capture.capturesVariable()) {
736 assert(!curField->isBitField() && "lambdas don't have bitfield members!");
737 ValueDecl *v = capture.getCapturedVar();
738 fieldName = v->getName();
739 cgf.cgm.lambdaFieldToName[curField] = fieldName;
740 } else if (capture.capturesThis()) {
741 cgf.cgm.lambdaFieldToName[curField] = "this";
742 } else {
743 cgf.cgm.errorNYI(e->getSourceRange(), "Unhandled capture kind");
744 cgf.cgm.lambdaFieldToName[curField] = "unhandled-capture-kind";
745 }
746
747 // Emit initialization
748 LValue lv =
749 cgf.emitLValueForFieldInitialization(slotLV, curField, fieldName);
750 if (curField->hasCapturedVLAType())
751 cgf.cgm.errorNYI(e->getSourceRange(), "lambda captured VLA type");
752
753 emitInitializationToLValue(captureInit, lv);
754
755 // Push a destructor if necessary.
756 if ([[maybe_unused]] QualType::DestructionKind DtorKind =
757 curField->getType().isDestructedType())
758 cgf.cgm.errorNYI(e->getSourceRange(), "lambda with destructed field");
759 }
760 }
761
762 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *e) {
763 CIRGenFunction::RunCleanupsScope cleanups(cgf);
764 Visit(e->getSubExpr());
765 }
766
767 void AggExprEmitter::VisitCallExpr(const CallExpr *e) {
768 if (e->getCallReturnType(cgf.getContext())->isReferenceType()) {
769 cgf.cgm.errorNYI(e->getSourceRange(), "reference return type");
770 return;
771 }
772
773 withReturnValueSlot(
774 e, [&](ReturnValueSlot slot) { return cgf.emitCallExpr(e, slot); });
775 }
776
777 void AggExprEmitter::withReturnValueSlot(
778 const Expr *e, llvm::function_ref<RValue(ReturnValueSlot)> fn) {
779 QualType retTy = e->getType();
780
781 assert(!cir::MissingFeatures::aggValueSlotDestructedFlag());
782 bool requiresDestruction =
783 retTy.isDestructedType() == QualType::DK_nontrivial_c_struct;
784 if (requiresDestruction)
785 cgf.cgm.errorNYI(
786 e->getSourceRange(),
787 "withReturnValueSlot: return value requiring destruction is NYI");
788
789 // If it makes no observable difference, save a memcpy + temporary.
790 //
791 // We need to always provide our own temporary if destruction is required.
792 // Otherwise, fn will emit its own, notice that it's "unused", and end its
793 // lifetime before we have the chance to emit a proper destructor call.
794 assert(!cir::MissingFeatures::aggValueSlotAlias());
795 assert(!cir::MissingFeatures::aggValueSlotGC());
796
797 Address retAddr = dest.getAddress();
798 assert(!cir::MissingFeatures::emitLifetimeMarkers());
799
800 assert(!cir::MissingFeatures::aggValueSlotVolatile());
801 assert(!cir::MissingFeatures::aggValueSlotDestructedFlag());
802 fn(ReturnValueSlot(retAddr));
803 }
804
805 void AggExprEmitter::VisitInitListExpr(InitListExpr *e) {
806 if (e->hadArrayRangeDesignator())
807 llvm_unreachable("GNU array range designator extension");
808
809 if (e->isTransparent())
810 return Visit(e->getInit(0));
811
812 visitCXXParenListOrInitListExpr(
813 e, e->inits(), e->getInitializedFieldInUnion(), e->getArrayFiller());
814 }
815
816 void AggExprEmitter::visitCXXParenListOrInitListExpr(
817 Expr *e, ArrayRef<Expr *> args, FieldDecl *initializedFieldInUnion,
818 Expr *arrayFiller) {
819
820 const mlir::Location loc = cgf.getLoc(e->getSourceRange());
821 const AggValueSlot dest = ensureSlot(loc, e->getType());
822
823 if (e->getType()->isConstantArrayType()) {
824 cir::ArrayType arrayTy =
825 cast<cir::ArrayType>(dest.getAddress().getElementType());
826 emitArrayInit(dest.getAddress(), arrayTy, e->getType(), e, args,
827 arrayFiller);
828 return;
829 } else if (e->getType()->isVariableArrayType()) {
830 cgf.cgm.errorNYI(e->getSourceRange(),
831 "visitCXXParenListOrInitListExpr variable array type");
832 return;
833 }
834
835 if (e->getType()->isArrayType()) {
836 cgf.cgm.errorNYI(e->getSourceRange(),
837 "visitCXXParenListOrInitListExpr array type");
838 return;
839 }
840
841 assert(e->getType()->isRecordType() && "Only support structs/unions here!");
842
843 // Do struct initialization; this code just sets each individual member
844 // to the approprate value. This makes bitfield support automatic;
845 // the disadvantage is that the generated code is more difficult for
846 // the optimizer, especially with bitfields.
847 unsigned numInitElements = args.size();
848 auto *record = e->getType()->castAsRecordDecl();
849
850 // We'll need to enter cleanup scopes in case any of the element
851 // initializers throws an exception.
852 assert(!cir::MissingFeatures::requiresCleanups());
853
854 unsigned curInitIndex = 0;
855
856 // Emit initialization of base classes.
857 if (auto *cxxrd = dyn_cast<CXXRecordDecl>(record)) {
858 assert(numInitElements >= cxxrd->getNumBases() &&
859 "missing initializer for base class");
860 for (auto &base : cxxrd->bases()) {
861 assert(!base.isVirtual() && "should not see vbases here");
862 CXXRecordDecl *baseRD = base.getType()->getAsCXXRecordDecl();
863 Address address = cgf.getAddressOfDirectBaseInCompleteClass(
864 loc, dest.getAddress(), cxxrd, baseRD,
865 /*baseIsVirtual=*/false);
866 assert(!cir::MissingFeatures::aggValueSlotGC());
867 AggValueSlot aggSlot = AggValueSlot::forAddr(
868 address, Qualifiers(), AggValueSlot::IsDestructed,
869 AggValueSlot::IsNotAliased,
870 cgf.getOverlapForBaseInit(cxxrd, baseRD, false));
871 cgf.emitAggExpr(args[curInitIndex++], aggSlot);
872 if (base.getType().isDestructedType()) {
873 cgf.cgm.errorNYI(e->getSourceRange(),
874 "push deferred deactivation cleanup");
875 return;
876 }
877 }
878 }
879
880 // Prepare a 'this' for CXXDefaultInitExprs.
881 CIRGenFunction::FieldConstructionScope fcScope(cgf, dest.getAddress());
882
883 LValue destLV = cgf.makeAddrLValue(dest.getAddress(), e->getType());
884
885 if (record->isUnion()) {
886 cgf.cgm.errorNYI(e->getSourceRange(),
887 "visitCXXParenListOrInitListExpr union type");
888 return;
889 }
890
891 // Here we iterate over the fields; this makes it simpler to both
892 // default-initialize fields and skip over unnamed fields.
893 for (const FieldDecl *field : record->fields()) {
894 // We're done once we hit the flexible array member.
895 if (field->getType()->isIncompleteArrayType())
896 break;
897
898 // Always skip anonymous bitfields.
899 if (field->isUnnamedBitField())
900 continue;
901
902 // We're done if we reach the end of the explicit initializers, we
903 // have a zeroed object, and the rest of the fields are
904 // zero-initializable.
905 if (curInitIndex == numInitElements && dest.isZeroed() &&
906 cgf.getTypes().isZeroInitializable(e->getType()))
907 break;
908 LValue lv =
909 cgf.emitLValueForFieldInitialization(destLV, field, field->getName());
910 // We never generate write-barriers for initialized fields.
911 assert(!cir::MissingFeatures::setNonGC());
912
913 if (curInitIndex < numInitElements) {
914 // Store the initializer into the field.
915 CIRGenFunction::SourceLocRAIIObject loc{
916 cgf, cgf.getLoc(record->getSourceRange())};
917 emitInitializationToLValue(args[curInitIndex++], lv);
918 } else {
919 // We're out of initializers; default-initialize to null
920 emitNullInitializationToLValue(cgf.getLoc(e->getSourceRange()), lv);
921 }
922
923 // Push a destructor if necessary.
924 // FIXME: if we have an array of structures, all explicitly
925 // initialized, we can end up pushing a linear number of cleanups.
926 if (field->getType().isDestructedType()) {
927 cgf.cgm.errorNYI(e->getSourceRange(),
928 "visitCXXParenListOrInitListExpr destructor");
929 return;
930 }
931
932 // From classic codegen, maybe not useful for CIR:
933 // If the GEP didn't get used because of a dead zero init or something
934 // else, clean it up for -O0 builds and general tidiness.
935 }
936 }
937
938 // TODO(cir): This could be shared with classic codegen.
939 AggValueSlot::Overlap_t CIRGenFunction::getOverlapForBaseInit(
940 const CXXRecordDecl *rd, const CXXRecordDecl *baseRD, bool isVirtual) {
941 // If the most-derived object is a field declared with [[no_unique_address]],
942 // the tail padding of any virtual base could be reused for other subobjects
943 // of that field's class.
944 if (isVirtual)
945 return AggValueSlot::MayOverlap;
946
947 // If the base class is laid out entirely within the nvsize of the derived
948 // class, its tail padding cannot yet be initialized, so we can issue
949 // stores at the full width of the base class.
950 const ASTRecordLayout &layout = getContext().getASTRecordLayout(rd);
951 if (layout.getBaseClassOffset(baseRD) +
952 getContext().getASTRecordLayout(baseRD).getSize() <=
953 layout.getNonVirtualSize())
954 return AggValueSlot::DoesNotOverlap;
955
956 // The tail padding may contain values we need to preserve.
957 return AggValueSlot::MayOverlap;
958 }
959
960 void CIRGenFunction::emitAggExpr(const Expr *e, AggValueSlot slot) {
961 AggExprEmitter(*this, slot).Visit(const_cast<Expr *>(e));
962 }
963
964 void CIRGenFunction::emitAggregateCopy(LValue dest, LValue src, QualType ty,
965 AggValueSlot::Overlap_t mayOverlap,
966 bool isVolatile) {
967 // TODO(cir): this function needs improvements, commented code for now since
968 // this will be touched again soon.
969 assert(!ty->isAnyComplexType() && "Unexpected copy of complex");
970
971 Address destPtr = dest.getAddress();
972 Address srcPtr = src.getAddress();
973
974 if (getLangOpts().CPlusPlus) {
975 if (auto *record = ty->getAsCXXRecordDecl()) {
976 assert((record->hasTrivialCopyConstructor() ||
977 record->hasTrivialCopyAssignment() ||
978 record->hasTrivialMoveConstructor() ||
979 record->hasTrivialMoveAssignment() ||
980 record->hasAttr<TrivialABIAttr>() || record->isUnion()) &&
981 "Trying to aggregate-copy a type without a trivial copy/move "
982 "constructor or assignment operator");
983 // Ignore empty classes in C++.
984 if (record->isEmpty())
985 return;
986 }
987 }
988
989 assert(!cir::MissingFeatures::cudaSupport());
990
991 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
992 // C99 6.5.16.1p3, which states "If the value being stored in an object is
993 // read from another object that overlaps in anyway the storage of the first
994 // object, then the overlap shall be exact and the two objects shall have
995 // qualified or unqualified versions of a compatible type."
996 //
997 // memcpy is not defined if the source and destination pointers are exactly
998 // equal, but other compilers do this optimization, and almost every memcpy
999 // implementation handles this case safely. If there is a libc that does not
1000 // safely handle this, we can add a target hook.
1001
1002 // Get data size info for this aggregate. Don't copy the tail padding if this
1003 // might be a potentially-overlapping subobject, since the tail padding might
1004 // be occupied by a different object. Otherwise, copying it is fine.
1005 TypeInfoChars typeInfo;
1006 if (mayOverlap)
1007 typeInfo = getContext().getTypeInfoDataSizeInChars(ty);
1008 else
1009 typeInfo = getContext().getTypeInfoInChars(ty);
1010
1011 assert(!cir::MissingFeatures::aggValueSlotVolatile());
1012
1013 // NOTE(cir): original codegen would normally convert destPtr and srcPtr to
1014 // i8* since memcpy operates on bytes. We don't need that in CIR because
1015 // cir.copy will operate on any CIR pointer that points to a sized type.
1016
1017 // Don't do any of the memmove_collectable tests if GC isn't set.
1018 if (cgm.getLangOpts().getGC() != LangOptions::NonGC)
1019 cgm.errorNYI("emitAggregateCopy: GC");
1020
1021 [[maybe_unused]] cir::CopyOp copyOp =
1022 builder.createCopy(destPtr.getPointer(), srcPtr.getPointer(), isVolatile);
1023
1024 assert(!cir::MissingFeatures::opTBAA());
1025 }
1026
1027 // TODO(cir): This could be shared with classic codegen.
1028 AggValueSlot::Overlap_t
1029 CIRGenFunction::getOverlapForFieldInit(const FieldDecl *fd) {
1030 if (!fd->hasAttr<NoUniqueAddressAttr>() || !fd->getType()->isRecordType())
1031 return AggValueSlot::DoesNotOverlap;
1032
1033 // If the field lies entirely within the enclosing class's nvsize, its tail
1034 // padding cannot overlap any already-initialized object. (The only subobjects
1035 // with greater addresses that might already be initialized are vbases.)
1036 const RecordDecl *classRD = fd->getParent();
1037 const ASTRecordLayout &layout = getContext().getASTRecordLayout(classRD);
1038 if (layout.getFieldOffset(fd->getFieldIndex()) +
1039 getContext().getTypeSize(fd->getType()) <=
1040 (uint64_t)getContext().toBits(layout.getNonVirtualSize()))
1041 return AggValueSlot::DoesNotOverlap;
1042
1043 // The tail padding may contain values we need to preserve.
1044 return AggValueSlot::MayOverlap;
1045 }
1046
1047 LValue CIRGenFunction::emitAggExprToLValue(const Expr *e) {
1048 assert(hasAggregateEvaluationKind(e->getType()) && "Invalid argument!");
1049 Address temp = createMemTemp(e->getType(), getLoc(e->getSourceRange()));
1050 LValue lv = makeAddrLValue(temp, e->getType());
1051 emitAggExpr(e, AggValueSlot::forLValue(lv, AggValueSlot::IsNotDestructed,
1052 AggValueSlot::IsNotAliased,
1053 AggValueSlot::DoesNotOverlap));
1054 return lv;
1055 }