31class ConditionalEvaluationFinder
33 bool foundConditional =
false;
38 bool shouldVisitImplicitCode()
const {
return true; }
40 bool found()
const {
return foundConditional; }
42 bool VisitAbstractConditionalOperator(AbstractConditionalOperator *) {
43 foundConditional =
true;
47 bool VisitBinaryOperator(BinaryOperator *e) {
49 foundConditional =
true;
55 bool VisitCXXNewExpr(CXXNewExpr *e) {
60 foundConditional =
true;
70 if (init && !TraverseStmt(init))
74 bool TraverseBlockExpr(BlockExpr *) {
return true; }
75 bool TraverseStmtExpr(StmtExpr *) {
return true; }
79 bool TraverseCoawaitExpr(CoawaitExpr *e) {
83 bool TraverseDependentCoawaitExpr(DependentCoawaitExpr *e) {
87 bool TraverseCoyieldExpr(CoyieldExpr *e) {
106 mlir::Location loc = builder.getUnknownLoc();
119 mlir::OpBuilder::InsertionGuard guard(builder);
122 builder.createFlagStore(loc,
false, active.
getPointer());
127 builder.createFlagStore(loc,
true, active.
getPointer());
138 assert(!cleanup.hasActiveFlag() &&
"cleanup already has active flag?");
139 cleanup.setActiveFlag(activeFlag);
141 cleanup.setTestFlagInNormalCleanup(cleanup.isNormalCleanup());
142 cleanup.setTestFlagInEHCleanup(cleanup.isEHCleanup());
147 : cgf(cgf), cleanups(cgf), scope(
nullptr),
152 assert(subExpr &&
"ExprWithCleanups always has a sub-expression");
153 ConditionalEvaluationFinder finder;
154 finder.TraverseStmt(
const_cast<Expr *
>(subExpr));
155 if (finder.found()) {
156 mlir::Location loc = cgf.builder.getUnknownLoc();
157 cir::CleanupKind cleanupKind = cgf.getLangOpts().Exceptions
158 ? cir::CleanupKind::All
159 : cir::CleanupKind::Normal;
160 scope = cir::CleanupScopeOp::create(
161 cgf.builder, loc, cleanupKind,
163 [&](mlir::OpBuilder &b, mlir::Location loc) {},
165 [&](mlir::OpBuilder &b, mlir::Location loc) {});
166 cgf.builder.setInsertionPointToEnd(&scope.getBodyRegion().front());
171 cgf.currentFullExprCleanupScope = scope;
178 cir::CleanupScopeOp scope) {
185 auto cur = alloca->getParentOfType<cir::CleanupScopeOp>();
186 while (cur && cur != scope)
187 cur = cur->getParentOfType<cir::CleanupScopeOp>();
194 mlir::Block *parentBlock = scope->getBlock();
195 mlir::OpBuilder::InsertPoint ip =
197 alloca->moveBefore(parentBlock, ip.getPoint());
206 for (mlir::Operation *cur = ptr.getDefiningOp(); cur && cur != alloca;) {
207 auto cast = mlir::dyn_cast<cir::CastOp>(cur);
210 casts.push_back(
cast);
211 cur =
cast.getSrc().getDefiningOp();
214 mlir::Operation *prev = alloca;
215 for (cir::CastOp
cast : llvm::reverse(casts)) {
216 cast->moveAfter(prev);
229 cir::CleanupScopeOp scope = condScope.
scope;
232 bool hasDeferredCleanups = stack.size() > base;
236 mlir::OpBuilder::InsertionGuard guard(builder);
237 mlir::Block &lastBodyBlock = scope.getBodyRegion().back();
238 builder.setInsertionPointToEnd(&lastBodyBlock);
239 if (lastBodyBlock.empty() ||
240 !lastBodyBlock.back().hasTrait<mlir::OpTrait::IsTerminator>())
248 if (hasDeferredCleanups) {
250 llvm::make_range(stack.begin() + base, stack.end()))
255 mlir::OpBuilder::InsertionGuard guard(builder);
256 mlir::Block &cleanupBlock = scope.getCleanupRegion().front();
257 builder.setInsertionPointToEnd(&cleanupBlock);
260 llvm::reverse(llvm::make_range(stack.begin() + base, stack.end()))) {
261 if (entry.activeFlag.isValid()) {
269 assert(entry.addr.getUnderlyingAllocaOp() &&
270 (entry.addr.getUnderlyingAllocaOp()->getBlock() ==
271 entry.addr.getPointer().getDefiningOp()->getBlock()) &&
272 "alloca and cast are in different blocks");
273 mlir::Value flag = builder.
createLoad(scope.getLoc(), entry.activeFlag);
274 cir::IfOp::create(builder, scope.getLoc(), flag,
276 [&](mlir::OpBuilder &b, mlir::Location loc) {
277 cgf.emitDestroy(entry.addr, entry.type,
279 builder.createYield(loc);
282 cgf.
emitDestroy(entry.addr, entry.type, entry.destroyer);
288 stack.truncate(base);
294 mlir::Block *insertBlock = builder.getInsertionBlock();
296 scope.getBodyRegion().findAncestorBlockInRegion(*insertBlock))
297 builder.setInsertionPointAfter(scope);
302 assert(!exited &&
"FullExprCleanupScope::exit called twice");
305 cgf.currentFullExprCleanupScope = oldFullExprCleanupScope;
307 size_t oldSize = deferredCleanupStackSize;
310 assert(cgf.conditionalCleanupScopes.size() == conditionalScopeDepth &&
311 "conditional cleanup scope opened without one to close it");
312 cgf.deferredConditionalCleanupStack.truncate(oldSize);
313 cleanups.forceCleanup(valuesToReload);
319 for (mlir::Value *valPtr : valuesToReload) {
320 mlir::Value val = *valPtr;
325 Address temp = cgf.createDefaultAlignTempAlloca(val.getType(), val.getLoc(),
327 tempAllocas.push_back(temp);
328 cgf.builder.createStore(val.getLoc(), val, temp);
334 while (cgf.conditionalCleanupScopes.size() > conditionalScopeDepth)
336 cgf.conditionalCleanupScopes.pop_back_val());
341 cleanups.forceCleanupExceptLifetimeExtended();
345 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
346 mlir::Block &lastBodyBlock = scope.getBodyRegion().back();
347 cgf.builder.setInsertionPointToEnd(&lastBodyBlock);
348 if (lastBodyBlock.empty() ||
349 !lastBodyBlock.back().hasTrait<mlir::OpTrait::IsTerminator>())
350 cgf.builder.createYield(scope.getLoc());
357 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
358 mlir::Block &cleanupBlock = scope.getCleanupRegion().front();
359 cgf.builder.setInsertionPointToEnd(&cleanupBlock);
360 cgf.builder.createYield(scope.getLoc());
363 assert(cgf.deferredConditionalCleanupStack.size() == oldSize &&
364 "deferred cleanups were not consumed by a conditional scope");
365 cgf.builder.setInsertionPointAfter(scope);
371 cleanups.forceLifetimeExtendedCleanups();
374 for (
auto [addr, valPtr] : llvm::zip(tempAllocas, valuesToReload)) {
377 *valPtr = cgf.builder.createLoad(valPtr->getLoc(), addr);
385void EHScopeStack::Cleanup::anchor() {}
389 stable_iterator si = getInnermostNormalCleanup();
390 stable_iterator se = stable_end();
393 if (cleanup.isActive())
395 si = cleanup.getEnclosingNormalCleanup();
401char *EHScopeStack::allocate(
size_t size) {
402 size = llvm::alignTo(size, ScopeStackAlignment);
403 if (!startOfBuffer) {
404 unsigned capacity = llvm::PowerOf2Ceil(std::max<size_t>(size, 1024ul));
405 startOfBuffer = std::make_unique<char[]>(capacity);
406 startOfData = endOfBuffer = startOfBuffer.get() + capacity;
407 }
else if (
static_cast<size_t>(startOfData - startOfBuffer.get()) < size) {
408 unsigned currentCapacity = endOfBuffer - startOfBuffer.get();
409 unsigned usedCapacity =
410 currentCapacity - (startOfData - startOfBuffer.get());
411 unsigned requiredCapacity = usedCapacity + size;
414 unsigned newCapacity = llvm::PowerOf2Ceil(requiredCapacity);
416 std::unique_ptr<char[]> newStartOfBuffer =
417 std::make_unique<char[]>(newCapacity);
418 char *newEndOfBuffer = newStartOfBuffer.get() + newCapacity;
419 char *newStartOfData = newEndOfBuffer - usedCapacity;
420 memcpy(newStartOfData, startOfData, usedCapacity);
421 startOfBuffer.swap(newStartOfBuffer);
422 endOfBuffer = newEndOfBuffer;
423 startOfData = newStartOfData;
426 assert(startOfBuffer.get() + size <= startOfData);
431void EHScopeStack::deallocate(
size_t size) {
432 startOfData += llvm::alignTo(size, ScopeStackAlignment);
440 bool skipCleanupScope =
false;
442 cir::CleanupKind cleanupKind = cir::CleanupKind::All;
443 if (isEHCleanup && cgf->getLangOpts().Exceptions) {
445 isNormalCleanup ? cir::CleanupKind::All : cir::CleanupKind::EH;
451 cleanupKind = cir::CleanupKind::Normal;
453 skipCleanupScope =
true;
459 if (capturingCleanups)
460 skipCleanupScope =
true;
462 cir::CleanupScopeOp cleanupScope =
nullptr;
463 if (!skipCleanupScope) {
464 CIRGenBuilderTy &builder = cgf->getBuilder();
465 mlir::Location loc = builder.getUnknownLoc();
466 cleanupScope = cir::CleanupScopeOp::create(
467 builder, loc, cleanupKind,
469 [&](mlir::OpBuilder &b, mlir::Location loc) {
473 [&](mlir::OpBuilder &b, mlir::Location loc) {
477 builder.setInsertionPointToEnd(&cleanupScope.getBodyRegion().back());
484 if (innermostEHScope != stable_end() &&
488 EHCleanupScope *scope =
new (buffer)
489 EHCleanupScope(isNormalCleanup, isEHCleanup, size, cleanupScope,
490 innermostNormalCleanup, innermostEHScope);
493 innermostNormalCleanup = stable_begin();
496 innermostEHScope = stable_begin();
498 if (isLifetimeMarker)
502 if (cgf->getLangOpts().EHAsynch && isEHCleanup && !isLifetimeMarker &&
503 cgf->getTarget().getCXXABI().isMicrosoft())
504 cgf->cgm.errorNYI(
"push seh cleanup");
510 assert(!empty() &&
"popping exception stack when not empty");
514 innermostNormalCleanup =
cleanup.getEnclosingNormalCleanup();
515 innermostEHScope =
cleanup.getEnclosingEHScope();
516 deallocate(
cleanup.getAllocatedSize());
518 cir::CleanupScopeOp cleanupScope =
cleanup.getCleanupScopeOp();
520 auto *block = &cleanupScope.getBodyRegion().back();
521 if (!block->mightHaveTerminator()) {
522 mlir::OpBuilder::InsertionGuard guard(cgf->getBuilder());
523 cgf->getBuilder().setInsertionPointToEnd(block);
524 cir::YieldOp::create(cgf->getBuilder(),
525 cgf->getBuilder().getUnknownLoc());
529 mlir::Block *insertBlock = cgf->getBuilder().getInsertionBlock();
531 cleanupScope.getBodyRegion().findAncestorBlockInRegion(*insertBlock))
532 cgf->getBuilder().setInsertionPointAfter(cleanupScope);
540 for (stable_iterator si = getInnermostEHScope(); si != stable_end();) {
541 if (
auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si))) {
542 if (
cleanup->isLifetimeMarker()) {
544 si =
cleanup->getEnclosingEHScope();
557 mlir::Operation *dominatingIP) {
576 if (!var.isValid()) {
577 mlir::Location loc = builder.getUnknownLoc();
580 loc,
"cleanup.isactive");
583 assert(dominatingIP &&
"no existing variable and no dominating IP!");
586 mlir::Value val = builder.
getBool(
true, loc);
589 mlir::OpBuilder::InsertionGuard guard(builder);
590 builder.setInsertionPoint(dominatingIP);
598 mlir::Location loc = builder.getUnknownLoc();
604 mlir::Operation *dominatingIP) {
605 assert(c !=
ehStack.stable_end() &&
"deactivating bottom of stack?");
607 assert(scope.
isActive() &&
"double deactivation");
611 if (c ==
ehStack.stable_begin() &&
625 Address activeFlag, mlir::Location loc) {
633 cir::IfOp::create(builder, loc, isActive,
636 [&](mlir::OpBuilder &, mlir::Location) {
637 cleanup->emit(cgf, flags);
639 "cleanup ended with no insertion point?");
643 cleanup->emit(cgf, flags);
644 assert(cgf.
haveInsertPoint() &&
"cleanup ended with no insertion point?");
649 EHScopeStack::Cleanup *cleanup,
653 mlir::Block &block = cleanupScope.getCleanupRegion().back();
655 mlir::OpBuilder::InsertionGuard guard(builder);
656 builder.setInsertionPointToStart(&block);
658 emitCleanupBody(cgf, cleanup, flags, activeFlag, cleanupScope.getLoc());
660 mlir::Block &cleanupRegionLastBlock = cleanupScope.getCleanupRegion().back();
661 if (cleanupRegionLastBlock.empty() ||
662 !cleanupRegionLastBlock.back().hasTrait<mlir::OpTrait::IsTerminator>()) {
663 mlir::OpBuilder::InsertionGuard guardCase(builder);
664 builder.setInsertionPointToEnd(&cleanupRegionLastBlock);
675 .walk([&](mlir::Operation *op) {
677 return mlir::WalkResult::interrupt();
678 return mlir::WalkResult::advance();
688 assert(!
ehStack.empty() &&
"cleanup stack is empty!");
698 "missing cir.cleanup.scope for active cleanup");
720 if (forDeactivation && requiresNormalCleanup) {
727 mlir::Location loc = builder.getUnknownLoc();
734 mlir::OpBuilder::InsertionGuard guard(builder);
735 builder.setInsertionPoint(cleanupScope);
736 builder.createFlagStore(loc,
true, activeFlag.
getPointer());
740 assert(builder.getInsertionBlock() ==
741 &cleanupScope.getBodyRegion().back() &&
742 "expected insertion point in cleanup body");
743 builder.createFlagStore(loc,
false, activeFlag.
getPointer());
750 if (requiresEHCleanup)
751 cleanupScope.setCleanupKind(cir::CleanupKind::EH);
752 requiresNormalCleanup =
false;
764 if (!requiresNormalCleanup && !requiresEHCleanup) {
769 mlir::Block &cleanupBlock = cleanupScope.getCleanupRegion().back();
770 if (!cleanupBlock.mightHaveTerminator()) {
771 mlir::OpBuilder::InsertionGuard guard(builder);
772 builder.setInsertionPointToEnd(&cleanupBlock);
773 cir::YieldOp::create(builder, builder.getUnknownLoc());
786 cleanupBufferStack[8 *
sizeof(
void *)];
787 std::unique_ptr<char[]> cleanupBufferHeap;
793 if (cleanupSize <=
sizeof(cleanupBufferStack)) {
794 memcpy(cleanupBufferStack, cleanupSource, cleanupSize);
797 cleanupBufferHeap.reset(
new char[cleanupSize]);
798 memcpy(cleanupBufferHeap.get(), cleanupSource, cleanupSize);
810 Address cleanupActiveFlag = normalActiveFlag.
isValid() ? normalActiveFlag
811 : ehActiveFlag.
isValid() ? ehActiveFlag
819 emitCleanup(*
this, cleanupScope, cleanup, cleanupFlags, cleanupActiveFlag);
823 mlir::Location loc) {
828 while (
ehStack.stable_begin() != depth) {
832 "captured cleanup should not own a cleanup scope");
854 cleanupBufferStack[8 *
sizeof(
void *)];
855 std::unique_ptr<char[]> cleanupBufferHeap;
858 if (cleanupSize <=
sizeof(cleanupBufferStack)) {
859 memcpy(cleanupBufferStack, cleanupSource, cleanupSize);
862 cleanupBufferHeap.reset(
new char[cleanupSize]);
863 memcpy(cleanupBufferHeap.get(), cleanupSource, cleanupSize);
880 bool requiresCleanup =
false;
881 for (
auto it =
ehStack.begin(), ie =
ehStack.find(oldCleanupStackDepth);
884 requiresCleanup =
true;
893 if (requiresCleanup) {
894 for (mlir::Value *valPtr : valuesToReload) {
895 mlir::Value val = *valPtr;
903 tempAllocas.push_back(temp);
904 builder.createStore(val.getLoc(), val, temp);
910 while (
ehStack.stable_begin() != oldCleanupStackDepth)
914 if (requiresCleanup) {
915 for (
auto [addr, valPtr] : llvm::zip(tempAllocas, valuesToReload)) {
916 mlir::Location loc = valPtr->getLoc();
917 *valPtr = builder.createLoad(loc, addr);
static void setupCleanupBlockDeactivation(CIRGenFunction &cgf, EHScopeStack::stable_iterator c, mlir::Operation *dominatingIP)
The given cleanup block is being deactivated.
static bool bodyHasBranchThroughExits(mlir::Region &bodyRegion)
Check whether a cleanup scope body contains any non-yield exits that branch through the cleanup.
static void closeConditionalCleanupScope(CIRGenFunction &cgf, const CIRGenFunction::ConditionalCleanupScope &condScope)
Close a cleanup scope opened by a ConditionalEvaluation.
static void hoistAllocaOutOfCleanupScope(CIRGenFunction &cgf, Address addr, cir::CleanupScopeOp scope)
If the alloca that backs addr is currently nested inside the body region of scope,...
static void emitCleanupBody(CIRGenFunction &cgf, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag, mlir::Location loc)
static void emitCleanup(CIRGenFunction &cgf, cir::CleanupScopeOp cleanupScope, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag)
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
cir::ConstantOp getBool(bool state, mlir::Location loc)
cir::StoreOp createFlagStore(mlir::Location loc, bool val, mlir::Value dst)
static OpBuilder::InsertPoint getBestAllocaInsertPoint(mlir::Block *block)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
cir::LoadOp createFlagLoad(mlir::Location loc, mlir::Value addr)
Emit a load from an boolean flag variable.
cir::BoolType getBoolTy()
static bool isLogicalOp(Opcode Opc)
mlir::Value getPointer() const
cir::AllocaOp getUnderlyingAllocaOp() const
Return the underlying alloca for this address, if any.
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false, bool isNontemporal=false)
FullExprCleanupScope(CIRGenFunction &cgf, const Expr *subExpr)
void exit(ArrayRef< mlir::Value * > valuesToReload={})
llvm::SmallVector< PendingCleanupEntry > lifetimeExtendedCleanupStack
void initFullExprCleanup()
Set up the last cleanup that was pushed as a conditional full-expression cleanup.
void emitCapturedCleanups(EHScopeStack::stable_iterator depth, mlir::Location loc)
Emit the captured cleanups (those pushed above depth while EHScopeStack was capturing cleanups) at th...
mlir::Block * getCurFunctionEntryBlock()
bool isInConditionalBranch() const
void setBeforeOutermostConditional(mlir::Value value, Address addr)
ConditionalEvaluation * outermostConditional
EHScopeStack ehStack
Tracks function scope overall cleanup handling.
llvm::SmallVector< PendingCleanupEntry > deferredConditionalCleanupStack
Cleanups for temporaries constructed inside a conditional.
llvm::SmallVector< ConditionalCleanupScope > conditionalCleanupScopes
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Push the standard destructor for the given type as at least a normal cleanup.
static Destroyer destroyCXXObject
void initFullExprCleanupWithFlag(Address activeFlag)
Address createCleanupActiveFlag()
Create an active flag variable for use with conditional cleanups.
void deactivateCleanupBlock(EHScopeStack::stable_iterator cleanup, mlir::Operation *dominatingIP)
Deactivates the given cleanup block.
bool haveInsertPoint() const
True if an insertion point is defined.
void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType, Address ptr)
Emits all the code to cause the given temporary to be cleaned up.
void popCleanupBlocks(EHScopeStack::stable_iterator oldCleanupStackDepth, ArrayRef< mlir::Value * > valuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
CIRGenBuilderTy & getBuilder()
void emitDestroy(Address addr, QualType type, Destroyer *destroyer)
Immediately perform the destruction of the given object.
void pushPendingCleanupToEHStack(const PendingCleanupEntry &entry)
Promote a single pending cleanup entry onto the EH scope stack.
void popCleanupBlock(bool forDeactivation=false)
Pop a cleanup block from the stack.
cir::CleanupScopeOp currentFullExprCleanupScope
The cir.cleanup.scope of the innermost FullExprCleanupScope that materialized one,...
EHScopeStack::stable_iterator currentCleanupStackDepth
CIRGenFunction(CIRGenModule &cgm, CIRGenBuilderTy &builder, bool suppressNewContext=false)
Address createTempAllocaWithoutCast(mlir::Type ty, CharUnits align, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, mlir::OpBuilder::InsertPoint ip={})
This creates a alloca and inserts it into the entry block of the current region.
Address createDefaultAlignTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name)
CreateDefaultAlignTempAlloca - This creates an alloca with the default alignment of the corresponding...
A cleanup scope which generates the cleanup blocks lazily.
void setTestFlagInEHCleanup(bool value)
void setTestFlagInNormalCleanup(bool value)
Address getActiveFlag() const
size_t getCleanupSize() const
cir::CleanupScopeOp getCleanupScopeOp()
bool shouldTestFlagInEHCleanup() const
static size_t getSizeForCleanupSize(size_t size)
Gets the size required for a lazy cleanup scope with the given cleanup-data requirements.
bool isNormalCleanup() const
void setActiveFlag(Address var)
void * getCleanupBuffer()
bool shouldTestFlagInNormalCleanup() const
void setActive(bool isActive)
void setIsEHCleanupKind()
void setIsNormalCleanupKind()
Information for lazily generating a cleanup.
A saved depth on the scope stack.
void popCleanup()
Pops a cleanup scope off the stack. This is private to CIRGenCleanup.cpp.
iterator find(stable_iterator savePoint) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
bool requiresCatchOrCleanup() const
stable_iterator getInnermostActiveNormalCleanup() const
bool hasInitializer() const
Whether this new-expression has any initializer at all.
bool shouldNullCheckAllocation() const
True if the allocation result needs to be null-checked.
Represents a C++ temporary.
static CharUnits One()
Construct a CharUnits quantity of one.
Expr * getOperand() const
Expr * getOperand() const
This represents one expression.
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
A (possibly-)qualified type.
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)
static bool coroAwaitFullExprCleanups()
One record per cir.cleanup.scope opened by a ConditionalEvaluation, as described above.
size_t deferredCleanupStackSize
The size of deferredConditionalCleanupStack when this scope was opened.
cir::CleanupScopeOp scope
A cleanup whose destructor call is not emitted where the cleanup is registered.