clang 24.0.0git
CIRGenFunction.h
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// Internal per-function state used for AST-to-ClangIR code gen
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef CLANG_LIB_CIR_CODEGEN_CIRGENFUNCTION_H
14#define CLANG_LIB_CIR_CODEGEN_CIRGENFUNCTION_H
15
16#include "CIRGenBuilder.h"
17#include "CIRGenCall.h"
18#include "CIRGenModule.h"
19#include "CIRGenTypeCache.h"
20#include "CIRGenValue.h"
21#include "EHScopeStack.h"
22
23#include "Address.h"
24
27#include "clang/AST/CharUnits.h"
29#include "clang/AST/Decl.h"
30#include "clang/AST/ExprCXX.h"
31#include "clang/AST/Stmt.h"
32#include "clang/AST/Type.h"
42#include "llvm/ADT/ScopedHashTable.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/Intrinsics.h"
45
46namespace mlir {
47namespace acc {
48class LoopOp;
49} // namespace acc
50} // namespace mlir
51
52namespace clang {
53class OutlinedFunctionDecl;
54class SYCLKernelCallStmt;
55} // namespace clang
56
57namespace clang::CIRGen {
58
59struct CGCoroData;
60
62public:
64
65private:
66 /// The builder is a helper class to create IR inside a function. The
67 /// builder is stateful, in particular it keeps an "insertion point": this
68 /// is where the next operations will be introduced.
69 CIRGenBuilderTy &builder;
70
71 /// Saves the builder's constrained floating-point configuration on
72 /// construction and restores it on destruction. The builder is shared
73 /// across all functions in the module, so its constrained-FP state must be
74 /// scoped to each function's emission.
75 ///
76 /// Note that the similarly named CIRGenFunction::CIRGenFPOptionsRAII
77 /// intentionally avoids restoring the "isFPConstrained" state because that
78 /// state is function-wide, but this object does restore the state so that
79 /// any CIRGenFunction instance created while we are in the process of
80 /// emitting another function cannot corrupt the prior functions state.
81 struct ConstrainedFPRAII {
82 CIRGenBuilderTy &builder;
83 bool savedIsFPConstrained;
85 llvm::RoundingMode savedRounding;
86 cir::FastMathFlags savedFastMathFlags;
87
88 explicit ConstrainedFPRAII(CIRGenBuilderTy &builder)
89 : builder(builder), savedIsFPConstrained(builder.getIsFPConstrained()),
90 savedExcept(builder.getDefaultConstrainedExcept()),
91 savedRounding(builder.getDefaultConstrainedRounding()),
92 savedFastMathFlags(builder.getFastMathFlags()) {}
93 ~ConstrainedFPRAII() {
94 builder.setIsFPConstrained(savedIsFPConstrained);
95 builder.setDefaultConstrainedExcept(savedExcept);
96 builder.setDefaultConstrainedRounding(savedRounding);
97 builder.setFastMathFlags(savedFastMathFlags);
98 }
99 } constrainedFPState{builder};
100
101public:
102 /// The GlobalDecl for the current function being compiled or the global
103 /// variable currently being initialized.
105
107
108 /// The compiler-generated variable that holds the return value.
109 std::optional<mlir::Value> fnRetAlloca;
110
111 // Holds coroutine data if the current function is a coroutine. We use a
112 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
113 // in this header.
114 struct CGCoroInfo {
115 std::unique_ptr<CGCoroData> data;
116 CGCoroInfo();
117 ~CGCoroInfo();
118 };
120
121 bool isCoroutine() const { return curCoro.data != nullptr; }
122
123 /// The temporary alloca to hold the return value. This is
124 /// invalid iff the function has no return value.
126
127 /// Tracks function scope overall cleanup handling.
129
130 typedef void Destroyer(CIRGenFunction &cgf, Address addr, QualType ty);
131
132 class CapturedCleanups;
133
134 /// A cleanup whose destructor call is not emitted where the cleanup is
135 /// registered. Used by the lifetime-extended cleanup stack, whose entries
136 /// are later promoted onto the EH scope stack, and by the deferred
137 /// conditional cleanup stack, whose entries are emitted directly into a
138 /// conditional scope's cleanup region.
139 ///
140 /// A valid \c activeFlag means the cleanup is conditional. The flag tracks
141 /// at run time whether the object has been constructed, and guards the
142 /// destructor call.
143 ///
144 /// Currently only DestroyObject cleanups use this. When other cleanup types
145 /// are needed (e.g., CallLifetimeEnd), this struct can be extended with a
146 /// std::variant of cleanup data types.
153 /// If set, the cleanup is captured by this owner instead of opening a
154 /// cir.cleanup.scope when it is pushed onto the EH stack.
156 };
157
159
160 /// Cleanups for temporaries constructed inside a conditional.
161 ///
162 /// Temporaries are destroyed in reverse order of construction at the end of
163 /// the full expression. A cleanup lives in the cleanup region of a
164 /// cir.cleanup.scope, and those scopes nest, so nesting is what encodes the
165 /// order.
166 ///
167 /// For an unconditionally constructed temporary, EHScopeStack::pushCleanup
168 /// opens a scope where the temporary is constructed and leaves the builder in
169 /// its body, so each later temporary nests one level deeper and is destroyed
170 /// first.
171 ///
172 /// For a temporary constructed inside a conditional, pushFullExprCleanup
173 /// records the cleanup on this stack, paired with an active flag that is
174 /// cleared ahead of the conditional and set once the object is constructed.
175 /// The destructor call is emitted guarded by that flag, so it runs only on
176 /// the paths that constructed the object.
177 ///
178 /// ConditionalEvaluation opens the region holding those calls where the
179 /// conditional begins, nesting it inside the scopes of earlier temporaries
180 /// and outside later ones. Its body stays open for the rest of the full
181 /// expression, so its cleanup region runs at the end of it.
182 /// FullExprCleanupScope::exit closes these innermost first, then pops the
183 /// enclosing EH-stack cleanups.
185
186 /// One record per cir.cleanup.scope opened by a ConditionalEvaluation, as
187 /// described above. These are bookkeeping owned by CIRGenFunction, not RAII
188 /// objects. The scope outlives the ConditionalEvaluation that opened it,
189 /// and the enclosing FullExprCleanupScope is what closes it.
191 cir::CleanupScopeOp scope;
192
193 /// The size of deferredConditionalCleanupStack when this scope was
194 /// opened. Every open conditional scope shares that one stack, so the
195 /// entries from this index onward are the ones deferred from inside this
196 /// conditional. They are emitted into this scope's cleanup region, in
197 /// reverse, when it is closed.
199 };
201
202 /// The cir.cleanup.scope of the innermost FullExprCleanupScope that
203 /// materialized one, or null. ConditionalEvaluation opens a conditional
204 /// cleanup scope only while this is set, since a FullExprCleanupScope is
205 /// what closes those scopes.
206 cir::CleanupScopeOp currentFullExprCleanupScope = nullptr;
207
208 /// Set by emitAutoVarDeclWithCapturedCleanups while it emits the initializer
209 /// of a variable, such as a loop condition variable, that lifetime-extends
210 /// temporaries with a destructor.
211 /// The cleanups of the temporaries that \c extendingDecl extends are
212 /// captured by \c cleanups, e.g. for the loop's cleanup region, and guarded
213 /// by \c activeFlag, instead of opening cir.cleanup.scope operations around
214 /// the code that follows the declaration.
221
222 /// A cleanup that was pushed to the EH stack but whose deactivation is
223 /// deferred until the enclosing CleanupDeactivationScope exits. Used to
224 /// protect partially-constructed aggregates (e.g. lambda captures) so that
225 /// already-initialized sub-objects are destroyed if a later initializer
226 /// throws, while avoiding double-destruction after full construction.
232
233 /// Scope that deactivates all enclosed deferred cleanups on exit.
234 /// Mirrors CodeGenFunction::CleanupDeactivationScope in classic codegen.
238 bool deactivated = false;
239
243
245 assert(!deactivated && "Deactivating already deactivated scope");
246 auto &stack = cgf.deferredDeactivationCleanupStack;
247 for (size_t i = stack.size(); i > oldDeactivateCleanupStackSize; i--) {
248 cgf.deactivateCleanupBlock(stack[i - 1].cleanup,
249 stack[i - 1].dominatingIP);
250 stack[i - 1].dominatingIP->erase();
251 }
252 stack.resize(oldDeactivateCleanupStackSize);
253 deactivated = true;
254 }
255
260 };
261
263
264 /// If a ParmVarDecl had the pass_object_size attribute, this will contain a
265 /// mapping from said ParmVarDecl to its implicit "object_size" parameter.
266 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *>
268
269 /// A mapping from NRVO variables to the flags used to indicate
270 /// when the NRVO has been applied to this variable.
271 llvm::DenseMap<const VarDecl *, mlir::Value> nrvoFlags;
272
273 llvm::DenseMap<const clang::ValueDecl *, clang::FieldDecl *>
276
277 /// CXXThisDecl - When generating code for a C++ member function,
278 /// this will hold the implicit 'this' declaration.
280 mlir::Value cxxabiThisValue = nullptr;
281 mlir::Value cxxThisValue = nullptr;
284
285 /// When generating code for a constructor or destructor, this will hold the
286 /// implicit argument (e.g. VTT).
289
290 /// The value of 'this' to sue when evaluating CXXDefaultInitExprs within this
291 /// expression.
293
294 /// The values of function arguments to use when evaluating
295 /// CXXInheritedCtorInitExprs within this context.
297
298 /// The current array initialization index when evaluating an
299 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
300 mlir::Value arrayInitIndex = nullptr;
301
302 // Holds the Decl for the current outermost non-closure context
303 const clang::Decl *curFuncDecl = nullptr;
304 /// This is the inner-most code context, which includes blocks.
305 const clang::Decl *curCodeDecl = nullptr;
308
309 /// The current function or global initializer that is generated code for.
310 /// This is usually a cir::FuncOp, but it can also be a cir::GlobalOp for
311 /// global initializers.
312 mlir::Operation *curFn = nullptr;
313
314 /// Save Parameter Decl for coroutine.
316
317 using DeclMapTy = llvm::DenseMap<const clang::Decl *, Address>;
318 /// This keeps track of the CIR allocas or globals for local C
319 /// declarations.
321
322 /// The type of the condition for the emitting switch statement.
324
325 clang::ASTContext &getContext() const { return cgm.getASTContext(); }
326
327 CIRGenBuilderTy &getBuilder() { return builder; }
328
330 const CIRGenModule &getCIRGenModule() const { return cgm; }
331
333 // We currently assume this isn't called for a global initializer.
334 auto fn = mlir::cast<cir::FuncOp>(curFn);
335 return &fn.getRegion().front();
336 }
337
338 /// Sanitizers enabled for this function.
340
342 public:
346
347 private:
348 void ConstructorHelper(clang::FPOptions FPFeatures);
349 CIRGenFunction &cgf;
350 clang::FPOptions oldFPFeatures;
352 llvm::RoundingMode oldRounding;
353 std::optional<cir::FastMathFlags> oldFastMathFlags;
354 };
356
357 void setFastMathFlags(FPOptions fpFeatures);
358
359 /// Convert the active Clang floating-point options to CIR fast-math flags.
360 cir::FastMathFlags getCurrentFastMathFlags() const;
361
362 /// Create a CIR fast-math attribute from the specified flags.
363 cir::FastMathFlagsAttr getFastMathFlagsAttr(cir::FastMathFlags fastMathFlags);
364
365 /// The symbol table maps a variable name to a value in the current scope.
366 /// Entering a function creates a new scope, and the function arguments are
367 /// added to the mapping. When the processing of a function is terminated,
368 /// the scope is destroyed and the mappings created in this scope are
369 /// dropped.
370 using SymTableTy = llvm::ScopedHashTable<const clang::Decl *, mlir::Value>;
372
373 /// Whether a cir.stacksave operation has been added. Used to avoid
374 /// inserting cir.stacksave for multiple VLAs in the same scope.
375 bool didCallStackSave = false;
376
377 /// Whether or not a Microsoft-style asm block has been processed within
378 /// this fuction. These can potentially set the return value.
379 bool sawAsmBlock = false;
380
381 /// In C++, whether we are code generating a thunk. This controls whether we
382 /// should emit cleanups.
383 bool curFuncIsThunk = false;
384
385 mlir::Type convertTypeForMem(QualType t);
386
387 mlir::Type convertType(clang::QualType t);
388 mlir::Type convertType(const TypeDecl *t) {
389 return convertType(getContext().getTypeDeclType(t));
390 }
391
392 /// Get integer from a mlir::Value that is an int constant or a constant op.
393 static int64_t getSExtIntValueFromConstOp(mlir::Value val) {
394 auto constOp = val.getDefiningOp<cir::ConstantOp>();
395 assert(constOp && "getSExtIntValueFromConstOp call with non ConstantOp");
396 return constOp.getIntValue().getSExtValue();
397 }
398
399 /// Get zero-extended integer from a mlir::Value that is an int constant or a
400 /// constant op.
401 static int64_t getZExtIntValueFromConstOp(mlir::Value val) {
402 auto constOp = val.getDefiningOp<cir::ConstantOp>();
403 assert(constOp && "getZExtIntValueFromConstOp call with non ConstantOp");
404 return constOp.getIntValue().getZExtValue();
405 }
406
407 /// Return the cir::TypeEvaluationKind of QualType \c type.
409
413
417
419 bool suppressNewContext = false);
421
422 CIRGenTypes &getTypes() const { return cgm.getTypes(); }
423
424 const TargetInfo &getTarget() const { return cgm.getTarget(); }
425 mlir::MLIRContext &getMLIRContext() { return cgm.getMLIRContext(); }
426
428 return cgm.getTargetCIRGenInfo();
429 }
430
431 // ---------------------
432 // Opaque value handling
433 // ---------------------
434
435 /// Keeps track of the current set of opaque value expressions.
436 llvm::DenseMap<const OpaqueValueExpr *, LValue> opaqueLValues;
437 llvm::DenseMap<const OpaqueValueExpr *, RValue> opaqueRValues;
438
439 // This keeps track of the associated size for each VLA type.
440 // We track this by the size expression rather than the type itself because
441 // in certain situations, like a const qualifier applied to an VLA typedef,
442 // multiple VLA types can share the same size expression.
443 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
444 // enter/leave scopes.
445 llvm::DenseMap<const Expr *, mlir::Value> vlaSizeMap;
446
447public:
448 /// A non-RAII class containing all the information about a bound
449 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
450 /// this which makes individual mappings very simple; using this
451 /// class directly is useful when you have a variable number of
452 /// opaque values or don't want the RAII functionality for some
453 /// reason.
454 class OpaqueValueMappingData {
455 const OpaqueValueExpr *opaqueValue;
456 bool boundLValue;
457
458 OpaqueValueMappingData(const OpaqueValueExpr *ov, bool boundLValue)
459 : opaqueValue(ov), boundLValue(boundLValue) {}
460
461 public:
462 OpaqueValueMappingData() : opaqueValue(nullptr) {}
463
464 static bool shouldBindAsLValue(const Expr *expr) {
465 // gl-values should be bound as l-values for obvious reasons.
466 // Records should be bound as l-values because IR generation
467 // always keeps them in memory. Expressions of function type
468 // act exactly like l-values but are formally required to be
469 // r-values in C.
470 return expr->isGLValue() || expr->getType()->isFunctionType() ||
472 }
473
475 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const Expr *e) {
476 if (shouldBindAsLValue(ov))
477 return bind(cgf, ov, cgf.emitLValue(e));
478 return bind(cgf, ov, cgf.emitAnyExpr(e));
479 }
480
482 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const LValue &lv) {
483 assert(shouldBindAsLValue(ov));
484 cgf.opaqueLValues.insert(std::make_pair(ov, lv));
485 return OpaqueValueMappingData(ov, true);
486 }
487
489 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const RValue &rv) {
490 assert(!shouldBindAsLValue(ov));
491 cgf.opaqueRValues.insert(std::make_pair(ov, rv));
492
493 OpaqueValueMappingData data(ov, false);
494
495 // Work around an extremely aggressive peephole optimization in
496 // EmitScalarConversion which assumes that all other uses of a
497 // value are extant.
499 return data;
500 }
501
502 bool isValid() const { return opaqueValue != nullptr; }
503 void clear() { opaqueValue = nullptr; }
504
506 assert(opaqueValue && "no data to unbind!");
507
508 if (boundLValue) {
509 cgf.opaqueLValues.erase(opaqueValue);
510 } else {
511 cgf.opaqueRValues.erase(opaqueValue);
513 }
514 }
515 };
516
517 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
519 CIRGenFunction &cgf;
521
522 public:
526
527 /// Build the opaque value mapping for the given conditional
528 /// operator if it's the GNU ?: extension. This is a common
529 /// enough pattern that the convenience operator is really
530 /// helpful.
531 ///
534 : cgf(cgf) {
535 if (mlir::isa<ConditionalOperator>(op))
536 // Leave Data empty.
537 return;
538
540 mlir::cast<BinaryConditionalOperator>(op);
542 e->getCommon());
543 }
544
545 /// Build the opaque value mapping for an OpaqueValueExpr whose source
546 /// expression is set to the expression the OVE represents.
548 : cgf(cgf) {
549 if (ov) {
550 assert(ov->getSourceExpr() && "wrong form of OpaqueValueMapping used "
551 "for OVE with no source expression");
552 data = OpaqueValueMappingData::bind(cgf, ov, ov->getSourceExpr());
553 }
554 }
555
557 LValue lvalue)
558 : cgf(cgf),
559 data(OpaqueValueMappingData::bind(cgf, opaqueValue, lvalue)) {}
560
562 RValue rvalue)
563 : cgf(cgf),
564 data(OpaqueValueMappingData::bind(cgf, opaqueValue, rvalue)) {}
565
566 void pop() {
567 data.unbind(cgf);
568 data.clear();
569 }
570
572 if (data.isValid())
573 data.unbind(cgf);
574 }
575 };
576
577private:
578 /// Declare a variable in the current scope, return success if the variable
579 /// wasn't declared yet.
580 void declare(mlir::Value addrVal, const clang::Decl *var, clang::QualType ty,
581 mlir::Location loc, clang::CharUnits alignment,
582 bool isParam = false);
583
584public:
585 mlir::Value createDummyValue(mlir::Location loc, clang::QualType qt);
586
587 void emitNullInitialization(mlir::Location loc, Address destPtr, QualType ty);
588
589private:
590 // Track current variable initialization (if there's one)
591 const clang::VarDecl *currVarDecl = nullptr;
592 class VarDeclContext {
594 const clang::VarDecl *oldVal = nullptr;
595
596 public:
597 VarDeclContext(CIRGenFunction &p, const VarDecl *value) : p(p) {
598 if (p.currVarDecl)
599 oldVal = p.currVarDecl;
600 p.currVarDecl = value;
601 }
602
603 /// Can be used to restore the state early, before the dtor
604 /// is run.
605 void restore() { p.currVarDecl = oldVal; }
606 ~VarDeclContext() { restore(); }
607 };
608
609public:
610 /// Use to track source locations across nested visitor traversals.
611 /// Always use a `SourceLocRAIIObject` to change currSrcLoc.
612 std::optional<SourceRange> currSrcLoc;
613
615 CIRGenFunction &cgf;
616 std::optional<SourceRange> oldLoc;
617
618 public:
620 if (cgf.currSrcLoc)
621 oldLoc = cgf.currSrcLoc;
622 cgf.currSrcLoc = value;
623 }
624
625 /// Can be used to restore the state early, before the dtor
626 /// is run.
627 void restore() { cgf.currSrcLoc = oldLoc; }
629 };
630
632 llvm::ScopedHashTableScope<const clang::Decl *, mlir::Value>;
633
634 /// Hold counters for incrementally naming temporaries
635 unsigned counterRefTmp = 0;
636 unsigned counterAggTmp = 0;
637 std::string getCounterRefTmpAsString();
638 std::string getCounterAggTmpAsString();
639
640 /// Helpers to convert Clang's SourceLocation to a MLIR Location.
641 mlir::Location getLoc(clang::SourceLocation srcLoc);
642 mlir::Location getLoc(clang::SourceRange srcLoc);
643 mlir::Location getLoc(mlir::Location lhs, mlir::Location rhs);
644
645 const clang::LangOptions &getLangOpts() const { return cgm.getLangOpts(); }
646
648 if (cgm.getCodeGenOpts().getFiniteLoops() ==
650 return false;
651
652 // C++11 and later guarantees that a thread eventually will do one of the
653 // following (C++11 [intro.multithread]p24 and C++17 [intro.progress]p1):
654 // - terminate,
655 // - make a call to a library I/O function,
656 // - perform an access through a volatile glvalue, or
657 // - perform a synchronization operation or an atomic operation.
658 //
659 // Hence each function is 'mustprogress' in C++11 or later.
660 return getLangOpts().CPlusPlus11;
661 }
662
663 // [C++26][intro.progress] (DR)
664 // The implementation may assume that any thread will eventually do one of
665 // the following:
666 // [...]
667 // - continue execution of a trivial infinite loop ([stmt.iter.general]).
668 //
669 // A trivial infinite loop with no side effects (e.g. `while (true) {}`)
670 // is therefore exempt from the forward-progress guarantee. If such a loop
671 // is found in a function that was speculatively marked 'mustprogress',
672 // that attribute must be removed: otherwise the optimizer would be
673 // licensed to assume the loop terminates and could delete it.
674 bool checkIfLoopMustProgress(const clang::Expr *controllingExpression,
675 bool hasEmptyBody) {
677 getLangOpts(), cgm.getCodeGenOpts(), getContext(),
678 controllingExpression, hasEmptyBody, [this] {
679 curFn->removeAttr(cir::CIRDialect::getMustProgressAttrName());
680 });
681 }
682
683 /// True if an insertion point is defined. If not, this indicates that the
684 /// current code being emitted is unreachable.
685 /// FIXME(cir): we need to inspect this and perhaps use a cleaner mechanism
686 /// since we don't yet force null insertion point to designate behavior (like
687 /// LLVM's codegen does) and we probably shouldn't.
688 bool haveInsertPoint() const {
689 return builder.getInsertionBlock() != nullptr;
690 }
691
692 /// True if code emitted at the builder's insertion point can be reached.
693 /// After emitting a terminator CIRGen opens a fresh block to continue in, so
694 /// the insertion block holds unreachable code whenever it is neither its
695 /// region's entry block nor the target of a branch.
697 mlir::Block *block = builder.getInsertionBlock();
698 return block && (block->isEntryBlock() || !block->hasNoPredecessors());
699 }
700
701 // Wrapper for function prototype sources. Wraps either a FunctionProtoType or
702 // an ObjCMethodDecl.
704 llvm::PointerUnion<const clang::FunctionProtoType *,
705 const clang::ObjCMethodDecl *>
707
710 };
711
713
715
718 RValue emitAtomicLoad(LValue lvalue, SourceLocation loc, cir::MemOrder order,
719 bool isVolatile = false,
721
722 /// An abstract representation of regular/ObjC call/message targets.
724 /// The function declaration of the callee.
725 [[maybe_unused]] const clang::Decl *calleeDecl;
726
727 public:
728 AbstractCallee() : calleeDecl(nullptr) {}
729 AbstractCallee(const clang::FunctionDecl *fd) : calleeDecl(fd) {}
730
731 bool hasFunctionDecl() const {
732 return llvm::isa_and_nonnull<clang::FunctionDecl>(calleeDecl);
733 }
734
735 const clang::Decl *getDecl() const { return calleeDecl; }
736
737 unsigned getNumParams() const {
738 if (const auto *fd = llvm::dyn_cast<clang::FunctionDecl>(calleeDecl))
739 return fd->getNumParams();
740 return llvm::cast<clang::ObjCMethodDecl>(calleeDecl)->param_size();
741 }
742
743 const clang::ParmVarDecl *getParamDecl(unsigned I) const {
744 if (const auto *fd = llvm::dyn_cast<clang::FunctionDecl>(calleeDecl))
745 return fd->getParamDecl(I);
746 return *(llvm::cast<clang::ObjCMethodDecl>(calleeDecl)->param_begin() +
747 I);
748 }
749 };
750
751 /// True if the current statement has noinline attribute.
753
754 /// True if the current statement has always_inline attribute.
756
757 // The CallExpr within the current statement that the musttail attribute
758 // applies to. nullptr if there is no 'musttail' on the current statement.
759 const CallExpr *mustTailCall = nullptr;
760
761 struct VlaSizePair {
762 mlir::Value numElts;
764
765 VlaSizePair(mlir::Value num, QualType ty) : numElts(num), type(ty) {}
766 };
767
768 /// Return the number of elements for a single dimension
769 /// for the given array type.
770 VlaSizePair getVLAElements1D(const VariableArrayType *vla);
771
772 /// Returns an MLIR::Value+QualType pair that corresponds to the size,
773 /// in non-variably-sized elements, of a variable length array type,
774 /// plus that largest non-variably-sized element type. Assumes that
775 /// the type has already been emitted with emitVariablyModifiedType.
776 VlaSizePair getVLASize(const VariableArrayType *type);
777 VlaSizePair getVLASize(QualType type);
778
780
784
785 void finishFunction(SourceLocation endLoc);
786
787 /// Determine whether the given initializer is trivial in the sense
788 /// that it requires no code to be generated.
789 bool isTrivialInitializer(const Expr *init);
790
791 /// If the specified expression does not fold to a constant, or if it does but
792 /// contains a label, return false. If it constant folds return true and set
793 /// the boolean result in Result.
794 bool constantFoldsToBool(const clang::Expr *cond, bool &resultBool,
795 bool allowLabels = false);
797 llvm::APSInt &resultInt,
798 bool allowLabels = false);
799
800 /// Return true if the statement contains a label in it. If
801 /// this statement is not executed normally, it not containing a label means
802 /// that we can just remove the code.
803 bool containsLabel(const clang::Stmt *s, bool ignoreCaseStmts = false);
804
805 Address emitExtVectorElementLValue(LValue lv, mlir::Location loc);
806
807 class ConstantEmission {
808 // Cannot use mlir::TypedAttr directly here because of bit availability.
809 llvm::PointerIntPair<mlir::Attribute, 1, bool> valueAndIsReference;
810 ConstantEmission(mlir::TypedAttr c, bool isReference)
811 : valueAndIsReference(c, isReference) {}
812
813 public:
815 static ConstantEmission forReference(mlir::TypedAttr c) {
816 return ConstantEmission(c, true);
817 }
818 static ConstantEmission forValue(mlir::TypedAttr c) {
819 return ConstantEmission(c, false);
820 }
821
822 explicit operator bool() const {
823 return valueAndIsReference.getOpaqueValue() != nullptr;
824 }
825
826 bool isReference() const { return valueAndIsReference.getInt(); }
827 LValue getReferenceLValue(CIRGenFunction &cgf, const Expr *refExpr) const {
828 assert(isReference());
829 mlir::Value addr = cgf.getBuilder().getConstant(
830 cgf.getLoc(refExpr->getSourceRange()),
831 mlir::cast<mlir::TypedAttr>(valueAndIsReference.getPointer()));
832 return cgf.makeNaturalAlignAddrLValue(addr, refExpr->getType());
833 }
834
835 mlir::TypedAttr getValue() const {
836 assert(!isReference());
837 return mlir::cast<mlir::TypedAttr>(valueAndIsReference.getPointer());
838 }
839 };
840
841 ConstantEmission tryEmitAsConstant(const DeclRefExpr *refExpr);
842 ConstantEmission tryEmitAsConstant(const MemberExpr *me);
843
846 /// The address of the alloca for languages with explicit address space
847 /// (e.g. OpenCL) or alloca casted to generic pointer for address space
848 /// agnostic languages (e.g. C++). Invalid if the variable was emitted
849 /// as a global constant.
851
852 /// True if the variable is of aggregate type and has a constant
853 /// initializer.
855
856 /// True if the variable is a __block variable that is captured by an
857 /// escaping block.
858 bool isEscapingByRef = false;
859
860 /// True if the variable was emitted as an offload recipe, and thus doesn't
861 /// have the same sort of alloca initialization.
862 bool emittedAsOffload = false;
863
864 /// True if lifetime op should be used.
865 bool useLifetimeMarkers = false;
866
867 mlir::Value nrvoFlag{};
868
869 struct Invalid {};
871
874
876
877 bool wasEmittedAsGlobal() const { return !addr.isValid(); }
878
880
881 /// Returns the raw, allocated address, which is not necessarily
882 /// the address of the object itself. It is casted to default
883 /// address space for address space agnostic languages.
884 Address getAllocatedAddress() const { return addr; }
885
886 // Changes the stored address for the emission. This function should only
887 // be used in extreme cases, and isn't required to model normal AST
888 // initialization/variables.
890
891 /// Returns the address of the object within this declaration.
892 /// Note that this does not chase the forwarding pointer for
893 /// __block decls.
895 if (!isEscapingByRef)
896 return addr;
897
899 return Address::invalid();
900 }
901 };
902
903 /// Perform the usual unary conversions on the specified expression and
904 /// compare the result against zero, returning an Int1Ty value.
905 mlir::Value evaluateExprAsBool(const clang::Expr *e);
906
907 cir::GlobalOp addInitializerToStaticVarDecl(const VarDecl &d,
908 cir::GlobalOp gv,
909 cir::GetGlobalOp gvAddr);
910
911 /// Enter the cleanups necessary to complete the given phase of destruction
912 /// for a destructor. The end result should call destructors on members and
913 /// base classes in reverse order of their construction.
915
916 /// Return the pointer to pass to the operator delete of the given
917 /// destructor, converted to the type of its first parameter if needed.
918 mlir::Value loadThisForDtorDelete(const CXXDestructorDecl *dd);
919
920 /// Determines whether an EH cleanup is required to destroy a type
921 /// with the given destruction kind.
922 /// TODO(cir): could be shared with Clang LLVM codegen
924 switch (kind) {
926 return false;
930 return getLangOpts().Exceptions;
932 return getLangOpts().Exceptions &&
933 cgm.getCodeGenOpts().ObjCAutoRefCountExceptions;
934 }
935 llvm_unreachable("bad destruction kind");
936 }
937
941
943
944 /// Set the address of a local variable.
946 assert(!localDeclMap.count(vd) && "Decl already exists in LocalDeclMap!");
947 localDeclMap.insert({vd, addr});
948
949 // Add to the symbol table if not there already.
950 if (symbolTable.count(vd))
951 return;
952 symbolTable.insert(vd, addr.getPointer());
953 }
954
955 // Replaces the address of the local variable, if it exists. Else does the
956 // same thing as setAddrOfLocalVar.
958 localDeclMap.insert_or_assign(vd, addr);
959 }
960
961 // A class to allow reverting changes to a var-decl's registration to the
962 // localDeclMap. This is used in cases where things are being inserted into
963 // the variable list but don't follow normal lookup/search rules, like in
964 // OpenACC recipe generation.
966 CIRGenFunction &cgf;
967 const VarDecl *vd;
968 bool shouldDelete = false;
969 Address oldAddr = Address::invalid();
970
971 public:
973 : cgf(cgf), vd(vd) {
974 auto mapItr = cgf.localDeclMap.find(vd);
975
976 if (mapItr != cgf.localDeclMap.end())
977 oldAddr = mapItr->second;
978 else
979 shouldDelete = true;
980 }
981
983 if (shouldDelete)
984 cgf.localDeclMap.erase(vd);
985 else
986 cgf.localDeclMap.insert_or_assign(vd, oldAddr);
987 }
988 };
989
991
994
995 static bool
997
1004
1007
1011 const clang::CXXRecordDecl *nearestVBase,
1012 clang::CharUnits offsetFromNearestVBase,
1013 bool baseIsNonVirtualPrimaryBase,
1014 const clang::CXXRecordDecl *vtableClass,
1015 VisitedVirtualBasesSetTy &vbases, VPtrsVector &vptrs);
1016 /// Return the Value of the vtable pointer member pointed to by thisAddr.
1017 mlir::Value getVTablePtr(mlir::Location loc, Address thisAddr,
1018 const clang::CXXRecordDecl *vtableClass);
1019
1020 /// Returns whether we should perform a type checked load when loading a
1021 /// virtual function for virtual calls to members of RD. This is generally
1022 /// true when both vcall CFI and whole-program-vtables are enabled.
1024
1025 /// Source location information about the default argument or member
1026 /// initializer expression we're evaluating, if any.
1030
1031 /// A scope within which we are constructing the fields of an object which
1032 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use if
1033 /// we need to evaluate the CXXDefaultInitExpr within the evaluation.
1035 public:
1037 : cgf(cgf), oldCXXDefaultInitExprThis(cgf.cxxDefaultInitExprThis) {
1038 cgf.cxxDefaultInitExprThis = thisAddr;
1039 }
1041 cgf.cxxDefaultInitExprThis = oldCXXDefaultInitExprThis;
1042 }
1043
1044 private:
1045 CIRGenFunction &cgf;
1046 Address oldCXXDefaultInitExprThis;
1047 };
1048
1049 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1050 /// is overridden to be the object under construction.
1052 public:
1057 cgf.cxxThisValue = cgf.cxxDefaultInitExprThis.getPointer();
1058 cgf.cxxThisAlignment = cgf.cxxDefaultInitExprThis.getAlignment();
1059 }
1061 cgf.cxxThisValue = oldCXXThisValue;
1062 cgf.cxxThisAlignment = oldCXXThisAlignment;
1063 }
1064
1065 public:
1067 mlir::Value oldCXXThisValue;
1070 };
1071
1076
1077 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1078 /// current loop index is overridden. In order to encourage re-use of existing
1079 /// array initialization, this uses a flag to determine if it is a 'no-op' or
1080 /// not.
1082 public:
1083 ArrayInitLoopExprScope(CIRGenFunction &cgf, bool setIdx, mlir::Value index)
1084 : cgf(cgf),
1085 oldArrayInitIndex(setIdx
1086 ? std::optional<mlir::Value>(cgf.arrayInitIndex)
1087 : std::nullopt) {
1088 if (setIdx)
1089 cgf.arrayInitIndex = index;
1090 }
1092 if (oldArrayInitIndex.has_value())
1093 cgf.arrayInitIndex = *oldArrayInitIndex;
1094 }
1095
1096 private:
1097 CIRGenFunction &cgf;
1098 std::optional<mlir::Value> oldArrayInitIndex;
1099 };
1100
1101 /// Get the index of the current ArrayInitLoopExpr, if any.
1102 mlir::Value getArrayInitIndex() { return arrayInitIndex; }
1103
1105 LValue makeNaturalAlignAddrLValue(mlir::Value val, QualType ty);
1106
1107 /// Construct an address with the natural alignment of T. If a pointer to T
1108 /// is expected to be signed, the pointer passed to this function must have
1109 /// been signed, and the returned Address will have the pointer authentication
1110 /// information needed to authenticate the signed pointer.
1112 CharUnits alignment,
1113 bool forPointeeType = false,
1114 LValueBaseInfo *baseInfo = nullptr) {
1115 if (alignment.isZero())
1116 alignment = cgm.getNaturalTypeAlignment(t, baseInfo);
1117 return Address(ptr, convertTypeForMem(t), alignment);
1118 }
1119
1121 Address value, const CXXRecordDecl *derived,
1122 llvm::iterator_range<CastExpr::path_const_iterator> path,
1123 bool nullCheckValue, SourceLocation loc);
1124
1126 mlir::Location loc, Address baseAddr, const CXXRecordDecl *derived,
1127 llvm::iterator_range<CastExpr::path_const_iterator> path,
1128 bool nullCheckValue);
1129
1130 /// Return the VTT parameter that should be passed to a base
1131 /// constructor/destructor with virtual bases.
1132 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
1133 /// to ItaniumCXXABI.cpp together with all the references to VTT.
1134 mlir::Value getVTTParameter(GlobalDecl gd, bool forVirtualBase,
1135 bool delegating);
1136
1139 return makeAddrLValue(addr, ty, LValueBaseInfo(source));
1140 }
1141
1143 return LValue::makeAddr(addr, ty, baseInfo);
1144 }
1145
1146 void initializeVTablePointers(mlir::Location loc,
1147 const clang::CXXRecordDecl *rd);
1148 void initializeVTablePointer(mlir::Location loc, const VPtr &vptr);
1149
1151
1152 /// Return the address of a local variable.
1154 auto it = localDeclMap.find(vd);
1155 assert(it != localDeclMap.end() &&
1156 "Invalid argument to getAddrOfLocalVar(), no decl!");
1157 return it->second;
1158 }
1159
1161 mlir::Type fieldType, unsigned index);
1162
1163 /// Given an opaque value expression, return its LValue mapping if it exists,
1164 /// otherwise create one.
1166
1167 /// Given an opaque value expression, return its RValue mapping if it exists,
1168 /// otherwise create one.
1170
1171 /// Load the value for 'this'. This function is only valid while generating
1172 /// code for an C++ member function.
1173 /// FIXME(cir): this should return a mlir::Value!
1174 mlir::Value loadCXXThis() {
1175 assert(cxxThisValue && "no 'this' value for this function");
1176 return cxxThisValue;
1177 }
1179
1180 /// Load the VTT parameter to base constructors/destructors have virtual
1181 /// bases. FIXME: Every place that calls LoadCXXVTT is something that needs to
1182 /// be abstracted properly.
1183 mlir::Value loadCXXVTT() {
1184 assert(cxxStructorImplicitParamValue && "no VTT value for this function");
1186 }
1187
1188 /// Convert the given pointer to a complete class to the given direct base.
1190 Address value,
1191 const CXXRecordDecl *derived,
1192 const CXXRecordDecl *base,
1193 bool baseIsVirtual);
1194
1195 /// Determine whether a return value slot may overlap some other object.
1197 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
1198 // class subobjects. These cases may need to be revisited depending on the
1199 // resolution of the relevant core issue.
1201 }
1202
1203 /// Determine whether a base class initialization may overlap some other
1204 /// object.
1206 const CXXRecordDecl *baseRD,
1207 bool isVirtual);
1208
1209 /// Return a CIR constant for an undefined value of \p cirTy.
1210 mlir::Value getUndefConstant(mlir::Location loc, mlir::Type cirTy);
1211
1212 /// Get an appropriate 'undef' rvalue for the given type.
1214
1215 cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn,
1216 cir::FuncType funcType);
1217
1219 FunctionArgList &args);
1220
1221 /// Emit the function prologue: initialize the return value of an
1222 /// implicit-return-zero function and declare function arguments in the
1223 /// symbol table.
1224 void emitFunctionProlog(const FunctionArgList &args, mlir::Block *entryBB,
1225 const FunctionDecl *fd, SourceLocation bodyBeginLoc);
1226
1227 /// Emit code for the start of a function.
1228 /// \param loc The location to be associated with the function.
1229 /// \param startLoc The location of the function body.
1231 cir::FuncOp fn, cir::FuncType funcType,
1233 clang::SourceLocation startLoc);
1234
1235 /// Wrap the function body in a `cir.try` that enforces the exception
1236 /// specification of \p d: a filter handler for a dynamic specification
1237 /// (`throw(T...)` or pre-C++17 `throw()`), or a terminate handler for a
1238 /// specification that permits nothing to escape.
1239 void emitStartEHSpec(const clang::Decl *d);
1240
1241 /// Close the `cir.try` opened by emitStartEHSpec.
1242 void emitEndEHSpec(const clang::Decl *d);
1243
1244 /// returns true if aggregate type has a volatile member.
1246 if (const auto *rd = t->getAsRecordDecl())
1247 return rd->hasVolatileMember();
1248 return false;
1249 }
1250
1251 void addCatchHandlerAttr(const CXXCatchStmt *catchStmt,
1252 SmallVector<mlir::Attribute> &handlerAttrs);
1253
1254 /// The cleanup depth enclosing all the cleanups associated with the
1255 /// parameters.
1257
1258 /// The `cir.try` wrapping a function whose exception specification has to be
1259 /// enforced. Null when the current function needs no such wrapper.
1260 cir::TryOp ehSpecTryOp;
1261
1262 /// Whether the wrapper opened by emitStartEHSpec is a terminate scope, whose
1263 /// handler calls std::terminate() for any escaping exception, rather than the
1264 /// filter of a dynamic exception specification.
1266 return ehSpecTryOp &&
1267 mlir::isa<cir::CatchAllAttr>(ehSpecTryOp.getHandlerTypes()[0]);
1268 }
1269
1271
1272 /// Takes the old cleanup stack size and emits the cleanup blocks
1273 /// that have been added.
1274 void popCleanupBlocks(EHScopeStack::stable_iterator oldCleanupStackDepth,
1275 ArrayRef<mlir::Value *> valuesToReload = {});
1276
1277 /// Pops cleanup blocks until the given savepoint is reached, then adds the
1278 /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
1279 void popCleanupBlocks(EHScopeStack::stable_iterator oldCleanupStackDepth,
1280 size_t oldLifetimeExtendedSize,
1281 ArrayRef<mlir::Value *> valuesToReload = {});
1282 void popCleanupBlock(bool forDeactivation = false);
1283
1284 /// Emit the captured cleanups (those pushed above \p depth while EHScopeStack
1285 /// was capturing cleanups) at the current insertion point, which must be
1286 /// inside the cleanup region of the op that owns them, and pop them off the
1287 /// EH stack. Every cleanup above \p depth must have been captured.
1288 void emitCapturedCleanups(EHScopeStack::stable_iterator depth,
1289 mlir::Location loc);
1290
1291 /// Like emitCapturedCleanups, but push the captured cleanups again as
1292 /// ordinary cleanups, the first captured one outermost, and pop them, so that
1293 /// each one is emitted as a cir.cleanup.scope around the ones captured after
1294 /// it. An exception from one of them then still runs the ones captured
1295 /// before it. None of them may have an active flag.
1296 void emitCapturedCleanupsAsScopes(EHScopeStack::stable_iterator depth,
1297 mlir::Location loc);
1298
1299 void terminateStructuredRegionBody(mlir::Region &r, mlir::Location loc);
1300
1301 /// Deactivates the given cleanup block. The block cannot be reactivated. Pops
1302 /// it if it's the top of the stack.
1303 ///
1304 /// \param DominatingIP - An instruction which is known to
1305 /// dominate the current IP (if set) and which lies along
1306 /// all paths of execution between the current IP and the
1307 /// the point at which the cleanup comes into scope.
1308 void deactivateCleanupBlock(EHScopeStack::stable_iterator cleanup,
1309 mlir::Operation *dominatingIP);
1310
1311 /// Create an active flag variable for use with conditional cleanups. The
1312 /// flag is initialized to false before the outermost conditional and set to
1313 /// true at the current insertion point (inside the conditional branch).
1314 Address createCleanupActiveFlag();
1315
1316 /// Set up the last cleanup that was pushed as a conditional
1317 /// full-expression cleanup.
1318 void initFullExprCleanup();
1319 void initFullExprCleanupWithFlag(Address activeFlag);
1320
1321 /// Promote a single pending cleanup entry onto the EH scope stack. If the
1322 /// entry has a valid activeFlag, the cleanup is configured as conditional.
1323 /// Defined in CIRGenDecl.cpp where the concrete cleanup types are visible.
1324 void pushPendingCleanupToEHStack(const PendingCleanupEntry &entry);
1325
1326 /// Push a cleanup to be run at the end of the current full-expression. Safe
1327 /// against the possibility that we're currently inside a
1328 /// conditionally-evaluated expression.
1329 template <class T, class... As>
1331 // Outside a conditional the EH stack opens a scope here.
1332 if (!isInConditionalBranch())
1333 return ehStack.pushCleanup<T>(kind, a...);
1334
1335 // Inside a conditional, record the cleanup for the scope that
1336 // ConditionalEvaluation opened where the conditional began, guarded by a
1337 // flag set only where the object is constructed.
1338 Address activeFlag = createCleanupActiveFlag();
1340 PendingCleanupEntry{kind, a..., activeFlag});
1341 }
1342
1343 /// Push a cleanup and record it for deferred deactivation. The cleanup will
1344 /// be deactivated when the enclosing CleanupDeactivationScope exits.
1345 template <class T, class... As>
1347 mlir::Location loc = builder.getUnknownLoc();
1348 mlir::Operation *dominatingIP = builder.getBool(false, loc).getOperation();
1349 ehStack.pushCleanup<T>(kind, a...);
1351 {ehStack.stable_begin(), dominatingIP});
1352 }
1353
1355 Address addr, QualType type);
1357 QualType type, Destroyer *destroyer,
1358 bool useEHCleanupForArray);
1359
1360 /// Queue a cleanup to be pushed after finishing the current full-expression.
1361 /// When the enclosing RunCleanupsScope exits, popCleanupBlocks promotes these
1362 /// entries onto the EH scope stack for the enclosing scope.
1364 Destroyer *destroyer) {
1365 lifetimeExtendedCleanupStack.push_back({kind, addr, type, destroyer});
1366 }
1367
1368 /// Enters a new scope for capturing cleanups, all of which
1369 /// will be executed once the scope is exited.
1370 class RunCleanupsScope {
1371 EHScopeStack::stable_iterator cleanupStackDepth, oldCleanupStackDepth;
1372 size_t lifetimeExtendedCleanupStackSize;
1373 CleanupDeactivationScope deactivateCleanups;
1374 bool deferLifetimeExtended = false;
1375
1376 size_t oldLifetimeExtendedSize() const {
1377 return deferLifetimeExtended ? cgf.lifetimeExtendedCleanupStack.size()
1378 : lifetimeExtendedCleanupStackSize;
1379 }
1380
1381 protected:
1384
1385 private:
1386 RunCleanupsScope(const RunCleanupsScope &) = delete;
1387 void operator=(const RunCleanupsScope &) = delete;
1388
1389 protected:
1391
1392 public:
1393 /// Enter a new cleanup scope.
1395 : deactivateCleanups(cgf), performCleanup(true), cgf(cgf) {
1396 cleanupStackDepth = cgf.ehStack.stable_begin();
1397 lifetimeExtendedCleanupStackSize =
1398 cgf.lifetimeExtendedCleanupStack.size();
1399 oldDidCallStackSave = cgf.didCallStackSave;
1400 cgf.didCallStackSave = false;
1401 oldCleanupStackDepth = cgf.currentCleanupStackDepth;
1402 cgf.currentCleanupStackDepth = cleanupStackDepth;
1403 }
1404
1405 /// Exit this cleanup scope, emitting any accumulated cleanups.
1407 if (performCleanup)
1408 forceCleanup();
1409 }
1410
1411 /// Force the emission of cleanups now, instead of waiting
1412 /// until this object is destroyed.
1413 void forceCleanup(ArrayRef<mlir::Value *> valuesToReload = {}) {
1414 assert(performCleanup && "Already forced cleanup");
1416
1417 // forceDeactivate() can pop cleanup scopes that were pushed with
1418 // deferred deactivation, which moves the insertion point out of the
1419 // cleanup body region. Any caller value defined inside such a body
1420 // would no longer dominate uses past the scope. The downstream
1421 // popCleanupBlocks() handles the spill for any cleanups it pops
1422 // itself, but it cannot help with cleanups that forceDeactivate has
1423 // already popped. Spill those values here, while the insertion point
1424 // is still inside the body, so we can reload them after all popping
1425 // is done. We only spill values whose defining op lives inside a
1426 // cir.cleanup.scope, since values defined outside any cleanup scope
1427 // (e.g. allocas in the entry block) already dominate the post-scope
1428 // insertion point.
1429 const bool hasPendingDeactivations =
1431 deactivateCleanups.oldDeactivateCleanupStackSize;
1432
1433 llvm::SmallVector<Address> tempAllocas;
1434 bool didSpillAny = false;
1435 if (hasPendingDeactivations) {
1436 tempAllocas.reserve(valuesToReload.size());
1437 for (mlir::Value *valPtr : valuesToReload) {
1438 mlir::Value val = *valPtr;
1439 if (!val || !val.getDefiningOp() ||
1440 !val.getDefiningOp()->getParentOfType<cir::CleanupScopeOp>()) {
1441 tempAllocas.push_back(Address::invalid());
1442 continue;
1443 }
1445 val.getType(), val.getLoc(), "tmp.exprcleanup");
1446 tempAllocas.push_back(temp);
1447 cgf.builder.createStore(val.getLoc(), val, temp);
1448 didSpillAny = true;
1449 }
1450 }
1451
1452 deactivateCleanups.forceDeactivate();
1453 // If we already spilled some of the caller's values, don't ask
1454 // popCleanupBlocks to spill them again. Values we did not pre-spill
1455 // are not inside any cir.cleanup.scope, so they cannot be invalidated
1456 // by either forceDeactivate's or popCleanupBlocks's pops (both only
1457 // pop cir.cleanup.scope ops); they already dominate the post-scope
1458 // insertion point on their own.
1459 if (didSpillAny) {
1460 cgf.popCleanupBlocks(cleanupStackDepth, oldLifetimeExtendedSize());
1461
1462 // Reload the spilled values now that all cleanup popping (and
1463 // promotion of any lifetime-extended cleanups onto the EH stack) is
1464 // done.
1465 for (auto [addr, valPtr] : llvm::zip(tempAllocas, valuesToReload)) {
1466 if (!addr.isValid())
1467 continue;
1468 *valPtr = cgf.builder.createLoad(valPtr->getLoc(), addr);
1469 }
1470 } else {
1471 cgf.popCleanupBlocks(cleanupStackDepth, oldLifetimeExtendedSize(),
1472 valuesToReload);
1473 }
1474
1475 performCleanup = false;
1476 cgf.currentCleanupStackDepth = oldCleanupStackDepth;
1477 }
1478
1479 /// Force the emission of EH cleanups now, but defer promoting any
1480 /// lifetime-extended cleanup entries onto the EH scope stack. The caller
1481 /// must subsequently call forceLifetimeExtendedCleanups() to finalize the
1482 /// scope.
1484 assert(performCleanup && "Already forced cleanup");
1485 cgf.didCallStackSave = oldDidCallStackSave;
1486 deactivateCleanups.forceDeactivate();
1487 cgf.popCleanupBlocks(cleanupStackDepth);
1488 }
1489
1490 /// Promote any pending lifetime-extended cleanup entries onto the EH scope
1491 /// stack at the current insertion point and finalize this scope. This must
1492 /// be paired with a prior call to forceCleanupExceptLifetimeExtended().
1494 assert(performCleanup && "Already forced cleanup");
1495 assert(deactivateCleanups.deactivated &&
1496 "forceCleanupExceptLifetimeExtended() must be called first");
1497 cgf.popCleanupBlocks(cleanupStackDepth, oldLifetimeExtendedSize());
1498 performCleanup = false;
1499 cgf.currentCleanupStackDepth = oldCleanupStackDepth;
1500 }
1501
1502 /// Whether there are any pending cleanups that have been pushed since
1503 /// this scope was entered.
1504 bool hasPendingCleanups() const {
1505 return cgf.ehStack.stable_begin() != cleanupStackDepth;
1506 }
1507
1508 /// Leave the cleanups of lifetime-extended temporaries created in this
1509 /// scope to the enclosing scope instead of pushing them onto the EH stack
1510 /// when this scope ends. This is for a scope that ends in the body of a
1511 /// loop, such as the construction of an array element: the cleanup scope
1512 /// of such a temporary ends with that of the variable that extends its
1513 /// lifetime, after the loop.
1514 void deferLifetimeExtendedCleanups() { deferLifetimeExtended = true; }
1515 };
1516
1517 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
1519
1521
1523 CIRGenFunction &cgf;
1524 RunCleanupsScope cleanups;
1525 cir::CleanupScopeOp scope;
1526 cir::CleanupScopeOp oldFullExprCleanupScope;
1527 ConditionalEvaluation *oldOutermostConditional;
1528 ConditionalEvaluation *oldHiddenOutermostConditional;
1529 size_t deferredCleanupStackSize;
1530 size_t conditionalScopeDepth;
1531 bool exited = false;
1532
1533 public:
1534 /// \p s is the AST root for one cleanup boundary: a full-expression, an
1535 /// asm statement, or the construction of one array element.
1537
1538 void exit(ArrayRef<mlir::Value *> valuesToReload = {});
1539
1541 cleanups.deferLifetimeExtendedCleanups();
1542 }
1543
1545 if (!exited)
1546 exit();
1547 }
1548
1549 private:
1551 void operator=(const FullExprCleanupScope &) = delete;
1552 };
1553
1554 /// Whether the resume expression of \p s contains a construct that defers
1555 /// cleanups to the end of the enclosing full-expression: a temporary with a
1556 /// destructor, other than the result of await_resume(), or a conditional.
1557 static bool resumeExprDefersCleanups(const CoroutineSuspendExpr &s);
1558
1559 /// Captures cleanups for variables whose lifetime ends in a region owned by
1560 /// an enclosing op rather than at the end of a cir.cleanup.scope, so that
1561 /// they can be emitted into that region later. Examples for uses are:
1562 /// * A loop condition variable's cleanups in the loop op's per-iteration
1563 /// cleanup region.
1564 /// * Coroutine parameters and promises, which are cleaned up in a separate
1565 /// destroy region
1567 CIRGenFunction &cgf;
1569 bool active;
1570
1571 public:
1573 : cgf(cgf), depth(cgf.ehStack.stable_begin()), active(active) {}
1574
1575 /// An RAII class that suppresses cir.cleanup.scope creation for cleanups
1576 /// pushed onto the EH stack while such a variable is being emitted and
1577 /// instead captures these cleanups so that they can be emitted into the
1578 /// owning op's cleanup region later.
1580 EHScopeStack &ehStack;
1581
1582 public:
1584 : ehStack(scope.cgf.ehStack) {
1585 // Capture scopes deliberately wrap individual cleanup-producing
1586 // operations, so they must never nest.
1587 assert(!ehStack.isCapturingCleanups() &&
1588 "cleanup capturing should not nest");
1589 if (scope.active)
1590 ehStack.setCapturingCleanups(true);
1591 }
1592 ~CaptureScope() { ehStack.setCapturingCleanups(false); }
1593
1594 CaptureScope(const CaptureScope &) = delete;
1595 void operator=(const CaptureScope &) = delete;
1596 };
1597
1598 /// Emit the captured cleanups into the current insertion point, which must
1599 /// be inside the owning op's cleanup region.
1600 void emitIntoCleanupRegion(mlir::Location loc) {
1601 if (active)
1602 cgf.emitCapturedCleanups(depth, loc);
1603 }
1604
1605 /// Emit the captured cleanups at the current insertion point as nested
1606 /// cir.cleanup.scope operations, so that an exception from one of them
1607 /// still runs the ones captured before it.
1608 void emitAsNestedScopes(mlir::Location loc) {
1609 if (active)
1610 cgf.emitCapturedCleanupsAsScopes(depth, loc);
1611 }
1612
1613 private:
1614 CapturedCleanups(const CapturedCleanups &) = delete;
1615 void operator=(const CapturedCleanups &) = delete;
1616 };
1617
1618public:
1619 /// Represents a scope, including function bodies, compound statements, and
1620 /// the substatements of if/while/do/for/switch/try statements. This class
1621 /// handles any automatic cleanup, along with the return value.
1622 struct LexicalScope : public RunCleanupsScope {
1623 private:
1624 // Points to the scope entry block. This is useful, for instance, for
1625 // helping to insert allocas before finalizing any recursive CodeGen from
1626 // switches.
1627 mlir::Block *entryBlock;
1628
1629 LexicalScope *parentScope = nullptr;
1630
1631 // Holds the actual value for ScopeKind::Try
1632 cir::TryOp tryOp = nullptr;
1633
1634 // On a coroutine body, the OnFallthrough sub stmt holds the handler
1635 // (CoreturnStmt) for control flow falling off the body. Keep track
1636 // of a co_return emitted in this scope and not followed by a label, and
1637 // allow OnFallthrough to be skipped.
1638 bool hasCoreturnSinceLastLabel = false;
1639
1640 // Only Regular is used at the moment. Support for other kinds will be
1641 // added as the relevant statements/expressions are upstreamed.
1642 enum Kind {
1643 Regular, // cir.if, cir.scope, if_regions
1644 Ternary, // cir.ternary
1645 Switch, // cir.switch
1646 Try, // cir.try
1647 GlobalInit // cir.global initialization code
1648 };
1649 Kind scopeKind = Kind::Regular;
1650
1651 // The scope return value.
1652 mlir::Value retVal = nullptr;
1653
1654 mlir::Location beginLoc;
1655 mlir::Location endLoc;
1656
1657 public:
1658 unsigned depth = 0;
1659
1660 LexicalScope(CIRGenFunction &cgf, mlir::Location loc, mlir::Block *eb)
1661 : RunCleanupsScope(cgf), entryBlock(eb), parentScope(cgf.curLexScope),
1662 beginLoc(loc), endLoc(loc) {
1663
1664 assert(entryBlock && "LexicalScope requires an entry block");
1665 cgf.curLexScope = this;
1666 if (parentScope)
1667 ++depth;
1668
1669 if (const auto fusedLoc = mlir::dyn_cast<mlir::FusedLoc>(loc)) {
1670 assert(fusedLoc.getLocations().size() == 2 && "too many locations");
1671 beginLoc = fusedLoc.getLocations()[0];
1672 endLoc = fusedLoc.getLocations()[1];
1673 }
1674 }
1675
1676 void setRetVal(mlir::Value v) { retVal = v; }
1677
1678 void cleanup();
1679 void restore() { cgf.curLexScope = parentScope; }
1680
1683 cleanup();
1684 restore();
1685 }
1686
1687 // ---
1688 // Coroutine tracking
1689 // ---
1690 bool hasCoreturn() const { return hasCoreturnSinceLastLabel; }
1691 // Record an emitted co_return for fallthrough tracking.
1692 // A later label clears this state.
1693 void markCoreturnEmitted() { hasCoreturnSinceLastLabel = true; }
1694 // A goto can reach a label after a co_return, and the code after it, so
1695 // the end of this scope and of the enclosing ones may be reachable again.
1697 for (LexicalScope *s = this; s; s = s->parentScope)
1698 s->hasCoreturnSinceLastLabel = false;
1699 }
1700
1701 // ---
1702 // Kind
1703 // ---
1704 bool isGlobalInit() { return scopeKind == Kind::GlobalInit; }
1705 bool isRegular() { return scopeKind == Kind::Regular; }
1706 bool isSwitch() { return scopeKind == Kind::Switch; }
1707 bool isTernary() { return scopeKind == Kind::Ternary; }
1708 bool isTry() { return scopeKind == Kind::Try; }
1709 cir::TryOp getClosestTryParent();
1710 void setAsGlobalInit() { scopeKind = Kind::GlobalInit; }
1711 void setAsSwitch() { scopeKind = Kind::Switch; }
1712 void setAsTernary() { scopeKind = Kind::Ternary; }
1713 void setAsTry(cir::TryOp op) {
1714 scopeKind = Kind::Try;
1715 tryOp = op;
1716 }
1717
1718 cir::TryOp getTry() {
1719 assert(isTry());
1720 return tryOp;
1721 }
1722
1723 // ---
1724 // Return handling.
1725 // ---
1726
1727 private:
1728 // On switches we need one return block per region, since cases don't
1729 // have their own scopes but are distinct regions nonetheless.
1730
1731 // TODO: This implementation should change once we have support for early
1732 // exits in MLIR structured control flow (llvm-project#161575)
1734 llvm::DenseMap<mlir::Block *, mlir::Location> retLocs;
1735 llvm::DenseMap<cir::CaseOp, unsigned> retBlockInCaseIndex;
1736 std::optional<unsigned> normalRetBlockIndex;
1737
1738 // There's usually only one ret block per scope, but this needs to be
1739 // get or create because of potential unreachable return statements, note
1740 // that for those, all source location maps to the first one found.
1741 mlir::Block *createRetBlock(CIRGenFunction &cgf, mlir::Location loc) {
1742 assert((isa_and_nonnull<cir::CaseOp>(
1743 cgf.builder.getBlock()->getParentOp()) ||
1744 retBlocks.size() == 0) &&
1745 "only switches can hold more than one ret block");
1746
1747 // Create the return block but don't hook it up just yet.
1748 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
1749 auto *b = cgf.builder.createBlock(cgf.builder.getBlock()->getParent());
1750 retBlocks.push_back(b);
1751 updateRetLoc(b, loc);
1752 return b;
1753 }
1754
1755 cir::ReturnOp emitReturn(mlir::Location loc);
1756 void emitImplicitReturn();
1757
1758 public:
1760 mlir::Location getRetLoc(mlir::Block *b) { return retLocs.at(b); }
1761 void updateRetLoc(mlir::Block *b, mlir::Location loc) {
1762 retLocs.insert_or_assign(b, loc);
1763 }
1764
1765 mlir::Block *getOrCreateRetBlock(CIRGenFunction &cgf, mlir::Location loc) {
1766 // Check if we're inside a case region
1767 if (auto caseOp = mlir::dyn_cast_if_present<cir::CaseOp>(
1768 cgf.builder.getBlock()->getParentOp())) {
1769 auto iter = retBlockInCaseIndex.find(caseOp);
1770 if (iter != retBlockInCaseIndex.end()) {
1771 // Reuse existing return block
1772 mlir::Block *ret = retBlocks[iter->second];
1773 updateRetLoc(ret, loc);
1774 return ret;
1775 }
1776 // Create new return block
1777 mlir::Block *ret = createRetBlock(cgf, loc);
1778 retBlockInCaseIndex[caseOp] = retBlocks.size() - 1;
1779 return ret;
1780 }
1781
1782 if (normalRetBlockIndex) {
1783 mlir::Block *ret = retBlocks[*normalRetBlockIndex];
1784 updateRetLoc(ret, loc);
1785 return ret;
1786 }
1787
1788 mlir::Block *ret = createRetBlock(cgf, loc);
1789 normalRetBlockIndex = retBlocks.size() - 1;
1790 return ret;
1791 }
1792
1793 mlir::Block *getEntryBlock() { return entryBlock; }
1794 };
1795
1797
1799
1801 QualType type);
1802
1803 void pushDestroy(QualType::DestructionKind dtorKind, Address addr,
1804 QualType type);
1805
1807 Destroyer *destroyer);
1808
1810 QualType type, Destroyer *destroyer,
1811 bool useEHCleanupForArray,
1812 const clang::ValueDecl *extendingDecl);
1813
1815
1816 void pushIrregularPartialArrayCleanup(mlir::Value arrayBegin,
1817 Address arrayEndPointer,
1818 QualType elementType,
1819 CharUnits elementAlign,
1820 Destroyer *destroyer);
1821
1822 /// Start generating a thunk function.
1823 void startThunk(cir::FuncOp fn, GlobalDecl gd,
1824 const CIRGenFunctionInfo &fnInfo, bool isUnprototyped);
1825
1826 /// Finish generating a thunk function.
1827 void finishThunk();
1828
1829 /// Generate code for a thunk function.
1830 void generateThunk(cir::FuncOp fn, SourceRange fnLoc,
1831 const CIRGenFunctionInfo &fnInfo, GlobalDecl gd,
1832 const ThunkInfo &thunk, bool isUnprototyped);
1833
1834 /// ----------------------
1835 /// CIR emit functions
1836 /// ----------------------
1837public:
1838 bool getAArch64SVEProcessedOperands(unsigned builtinID, const CallExpr *expr,
1840 clang::SVETypeFlags typeFlags);
1841 mlir::Value emitSVEPredicateCast(mlir::Value pred, unsigned minNumElts,
1842 mlir::Location loc);
1843 std::optional<mlir::Value>
1844 emitAArch64BuiltinExpr(unsigned builtinID, const CallExpr *expr,
1846 llvm::Triple::ArchType arch);
1847 std::optional<mlir::Value> emitAArch64SMEBuiltinExpr(unsigned builtinID,
1848 const CallExpr *expr);
1849 std::optional<mlir::Value> emitAArch64SVEBuiltinExpr(unsigned builtinID,
1850 const CallExpr *expr);
1851 cir::VectorType getSVEType(const SVETypeFlags &typeFlags);
1852
1853 mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, QualType ty,
1854 SourceLocation loc,
1855 SourceLocation assumptionLoc,
1856 int64_t alignment,
1857 mlir::Value offsetValue = nullptr);
1858
1859 mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, const Expr *expr,
1860 SourceLocation assumptionLoc,
1861 int64_t alignment,
1862 mlir::Value offsetValue = nullptr);
1863
1864 bool emitLifetimeStartOp(mlir::Location loc, mlir::Value addr);
1865 void emitLifetimeEndOp(mlir::Location loc, mlir::Value addr);
1866
1867private:
1868 void emitAndUpdateRetAlloca(clang::QualType type, mlir::Location loc,
1869 clang::CharUnits alignment);
1870
1871 CIRGenCallee emitDirectCallee(const GlobalDecl &gd);
1872
1873public:
1875 llvm::StringRef fieldName,
1876 unsigned fieldIndex);
1877
1878 mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty,
1879 mlir::Location loc, clang::CharUnits alignment,
1880 bool insertIntoFnEntryBlock,
1881 mlir::Value arraySize = nullptr);
1882 mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty,
1883 mlir::Location loc, clang::CharUnits alignment,
1884 mlir::OpBuilder::InsertPoint ip,
1885 mlir::Value arraySize = nullptr);
1886
1887 void emitAggregateStore(mlir::Value value, Address dest);
1888
1889 void emitAggExpr(const clang::Expr *e, AggValueSlot slot);
1890
1892
1894
1895 /// Emit an aggregate copy.
1896 ///
1897 /// \param isVolatile \c true iff either the source or the destination is
1898 /// volatile.
1899 /// \param MayOverlap Whether the tail padding of the destination might be
1900 /// occupied by some other object. More efficient code can often be
1901 /// generated if not.
1902 void emitAggregateCopy(LValue dest, LValue src, QualType eltTy,
1903 AggValueSlot::Overlap_t mayOverlap,
1904 bool isVolatile = false);
1905
1906 /// Emit code to compute the specified expression which can have any type. The
1907 /// result is returned as an RValue struct. If this is an aggregate
1908 /// expression, the aggloc/agglocvolatile arguments indicate where the result
1909 /// should be returned.
1912 bool ignoreResult = false);
1913
1914 /// Emits the code necessary to evaluate an arbitrary expression into the
1915 /// given memory location.
1916 void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals,
1917 bool isInitializer);
1918
1919 /// Similarly to emitAnyExpr(), however, the result will always be accessible
1920 /// even if no aggregate location is provided.
1922
1923 void emitAnyExprToExn(const Expr *e, Address addr);
1924
1925 void emitArrayDestroy(mlir::Value begin, mlir::Value numElements,
1926 QualType elementType, CharUnits elementAlign,
1927 Destroyer *destroyer);
1928
1929 mlir::Value emitArrayLength(const clang::ArrayType *arrayType,
1930 QualType &baseType, Address &addr);
1933
1935
1937
1939 LValueBaseInfo *baseInfo = nullptr);
1940
1941 std::pair<mlir::Value, mlir::Type>
1943 QualType inputType, std::string &constraintString,
1944 SourceLocation loc);
1945 std::pair<mlir::Value, mlir::Type>
1946 emitAsmInput(const TargetInfo::ConstraintInfo &info, const Expr *inputExpr,
1947 std::string &constraintString);
1948 mlir::LogicalResult emitAsmStmt(const clang::AsmStmt &s);
1949
1951 void emitAtomicInit(Expr *init, LValue dest);
1952 void emitAtomicStore(RValue rvalue, LValue dest, bool isInit);
1953 void emitAtomicStore(RValue rvalue, LValue dest, cir::MemOrder order,
1954 bool isVolatile, bool isInit);
1955
1956 /// An emitted atomic order or scope value with optional constant evaluation.
1958 mlir::Value value;
1959 std::optional<Expr::EvalResult> eval;
1960
1963 : value(cgf.emitScalarExpr(expr)) {
1964 Expr::EvalResult evalResult;
1965 if (expr->EvaluateAsInt(evalResult, cgf.getContext()))
1966 eval.emplace(std::move(evalResult));
1967 }
1968 };
1969
1971 const EmittedOrderOrScope &order, bool isStore, bool isLoad, bool isFence,
1972 llvm::function_ref<void(cir::MemOrder)> emitAtomicOp);
1974 const AtomicScopeModel *scopeModel, const EmittedOrderOrScope &scope,
1975 llvm::function_ref<void(cir::SyncScopeKind)> emitAtomicOp);
1976
1977 mlir::Value makeBinaryAtomicValue(
1978 cir::AtomicFetchKind kind, const clang::CallExpr *expr,
1979 mlir::Type *originalArgType = nullptr,
1980 mlir::Value *emittedArgValue = nullptr,
1981 cir::MemOrder ordering = cir::MemOrder::SequentiallyConsistent);
1982
1983 /// Emit `cir.atomic.cmpxchg`. Returns the old value, or the success flag
1984 /// when `returnBool` is true.
1985 mlir::Value emitAtomicCmpXchg(
1986 const clang::CallExpr *expr, bool returnBool,
1987 cir::MemOrder successOrder = cir::MemOrder::SequentiallyConsistent,
1988 cir::MemOrder failureOrder = cir::MemOrder::SequentiallyConsistent,
1989 cir::SyncScopeKind scope = cir::SyncScopeKind::System);
1990
1991 mlir::LogicalResult emitAttributedStmt(const AttributedStmt &s);
1992
1993 AutoVarEmission emitAutoVarAlloca(const clang::VarDecl &d,
1994 mlir::OpBuilder::InsertPoint ip = {});
1995
1997 AggValueSlot slot = AggValueSlot::ignored());
1999
2000 /// Emit code and set up symbol table for a variable declaration with auto,
2001 /// register, or no storage class specifier. These turn into simple stack
2002 /// objects, globals depending on target.
2003 void emitAutoVarDecl(const clang::VarDecl &d);
2004
2005 void emitAutoVarCleanups(const AutoVarEmission &emission);
2006
2007 /// Emit a loop's condition-variable declaration. This needs special handling
2008 /// so that we can manage per-iteration cleanups for the loop condition.
2009 /// \p extendedTemporaries are the types of the temporaries with a destructor
2010 /// that its initializer lifetime-extends (see
2011 /// getLifetimeExtendedTemporariesWithDestructor).
2013 CapturedCleanups &condCleanup,
2014 llvm::ArrayRef<QualType> extendedTemporaries);
2015
2016 /// The types of the temporaries with a destructor that the initializer of
2017 /// the variable \p d, which has automatic storage duration, lifetime-extends.
2020
2021 /// Whether destroying an object of type \p type, or its elements if it is an
2022 /// array, may throw an exception.
2023 static bool destructorMayThrow(QualType type);
2024
2025 /// Emit \p d with captured cleanups. Set \p guardDestruction if the cleanup
2026 /// region covers initialization. Otherwise it must be reached only after
2027 /// initialization. The cleanups of \p extendedTemporaries (see
2028 /// emitLoopConditionVariable) are captured too; they need
2029 /// \p guardDestruction.
2031 const clang::VarDecl &d, CapturedCleanups &cleanups,
2032 bool guardDestruction = false,
2033 llvm::ArrayRef<QualType> extendedTemporaries = {});
2034
2035 /// Emit the initializer for an allocated variable. If this call is not
2036 /// associated with the call to emitAutoVarAlloca (as the address of the
2037 /// emission is not directly an alloca), the allocatedSeparately parameter can
2038 /// be used to suppress the assertions. However, this should only be used in
2039 /// extreme cases, as it doesn't properly reflect the language/AST.
2040 void emitAutoVarInit(const AutoVarEmission &emission);
2041 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2043
2044 void maybeEmitDeferredVarDeclInit(const VarDecl *vd);
2045
2046 void emitBaseInitializer(mlir::Location loc, const CXXRecordDecl *classDecl,
2047 CXXCtorInitializer *baseInit);
2048
2049 LValue emitBinaryOperatorLValue(const BinaryOperator *e);
2050
2051 mlir::LogicalResult emitBreakStmt(const clang::BreakStmt &s);
2052
2053 RValue emitBuiltinExpr(const clang::GlobalDecl &gd, unsigned builtinID,
2054 const clang::CallExpr *e, ReturnValueSlot returnValue);
2055
2056 /// Returns a Value corresponding to the size of the given expression by
2057 /// emitting a `cir.objsize` operation.
2058 ///
2059 /// \param e The expression whose object size to compute
2060 /// \param type Determines the semantics of the object size computation.
2061 /// The type parameter is a 2-bit value where:
2062 /// bit 0 (type & 1): 0 = whole object, 1 = closest subobject
2063 /// bit 1 (type & 2): 0 = maximum size, 2 = minimum size
2064 /// \param resType The result type for the size value
2065 /// \param emittedE Optional pre-emitted pointer value. If non-null, we'll
2066 /// call `cir.objsize` on this value rather than emitting e.
2067 /// \param isDynamic If true, allows runtime evaluation via dynamic mode
2068 mlir::Value emitBuiltinObjectSize(const clang::Expr *e, unsigned type,
2069 cir::IntType resType, mlir::Value emittedE,
2070 bool isDynamic);
2071
2072 mlir::Value evaluateOrEmitBuiltinObjectSize(const clang::Expr *e,
2073 unsigned type,
2074 cir::IntType resType,
2075 mlir::Value emittedE,
2076 bool isDynamic);
2077
2078 int64_t getAccessedFieldNo(unsigned idx, mlir::ArrayAttr elts);
2079
2080 /// Return the CIR signature of the LLVM intrinsic \p id, resolving its
2081 /// overloaded types to \p overloadTys. Integer types are returned signed.
2082 cir::FuncType getIntrinsicType(llvm::Intrinsic::ID id,
2083 llvm::ArrayRef<mlir::Type> overloadTys = {});
2084
2085 /// Emit a simple LLVM intrinsic that takes N scalar arguments. The intrinsic
2086 /// name is used verbatim; any overload mangling (e.g. `.f32`, `.p1`) must be
2087 /// baked into \p intrinName by the caller. The result type defaults to the
2088 /// type of the first argument; pass \p resultType for intrinsics whose result
2089 /// differs from the operand, such as a vector reduction that returns the
2090 /// element type. Unlike classic CodeGen, CIR has no intrinsic registry to
2091 /// derive the result type from the operand, so it must be supplied here.
2092 template <unsigned N>
2093 [[maybe_unused]] RValue
2095 llvm::StringRef intrinName,
2096 mlir::Type resultType = {}) {
2097 static_assert(N, "expect non-empty argument");
2098 mlir::Type cirTy =
2099 resultType ? resultType : convertType(e->getArg(0)->getType());
2101 for (unsigned i = 0; i < N; ++i)
2102 args.push_back(emitScalarExpr(e->getArg(i)));
2103 const auto call = cir::LLVMIntrinsicCallOp::create(
2104 builder, getLoc(e->getExprLoc()), builder.getStringAttr(intrinName),
2105 cirTy, args);
2106 return RValue::get(call->getResult(0));
2107 }
2108
2109 RValue emitCall(const CIRGenFunctionInfo &funcInfo,
2110 const CIRGenCallee &callee, ReturnValueSlot returnValue,
2111 const CallArgList &args, cir::CIRCallOpInterface *callOp,
2112 bool isMustTail, SourceRange clangLoc);
2115 const CallArgList &args, bool isMustTail,
2116 cir::CIRCallOpInterface *callOrTryCall = nullptr) {
2117 assert(currSrcLoc && "source location must have been set");
2118 return emitCall(funcInfo, callee, returnValue, args, callOrTryCall,
2119 isMustTail, *currSrcLoc);
2120 }
2121
2122 RValue emitCall(clang::QualType calleeTy, const CIRGenCallee &callee,
2124
2125 /// Emit the call and return for a thunk function.
2126 void emitCallAndReturnForThunk(cir::FuncOp callee, SourceRange fnLoc,
2127 const ThunkInfo *thunk, bool isUnprototyped);
2128
2129 void emitCallArg(CallArgList &args, const clang::Expr *e,
2130 clang::QualType argType);
2131 void emitCallArgs(
2132 CallArgList &args, PrototypeWrapper prototype,
2133 llvm::iterator_range<clang::CallExpr::const_arg_iterator> argRange,
2134 AbstractCallee callee = AbstractCallee(), unsigned paramsToSkip = 0,
2135 EvaluationOrder order = EvaluationOrder::Default);
2139
2143
2144 template <typename T>
2145 mlir::LogicalResult emitCaseDefaultCascade(const T *stmt, mlir::Type condType,
2146 mlir::ArrayAttr value,
2147 cir::CaseOpKind kind,
2148 bool buildingTopLevelCase);
2149
2151
2152 mlir::LogicalResult emitCaseStmt(const clang::CaseStmt &s,
2153 mlir::Type condType,
2154 bool buildingTopLevelCase);
2155
2156 LValue emitCastLValue(const CastExpr *e);
2157
2158 /// Emits an argument for a call to a `__builtin_assume`. If the builtin
2159 /// sanitizer is enabled, a runtime check is also emitted.
2160 mlir::Value emitCheckedArgForAssume(const Expr *e);
2161
2162 /// Emit a conversion from the specified complex type to the specified
2163 /// destination type, where the destination type is an LLVM scalar type.
2164 mlir::Value emitComplexToScalarConversion(mlir::Value src, QualType srcTy,
2165 QualType dstTy, SourceLocation loc);
2166
2169
2171
2172 mlir::LogicalResult emitCoroutineBody(const CoroutineBodyStmt &s);
2173 cir::CoroEndOp emitCoroEndBuiltinCall(const CallExpr *e);
2174 cir::CoroIdOp emitCoroIDBuiltinCall(const CallExpr *e);
2175 cir::CoroAllocOp emitCoroAllocBuiltinCall(const CallExpr *e);
2176 cir::CoroBeginOp emitCoroBeginBuiltinCall(const CallExpr *e);
2177 cir::CoroPromiseOp emitCoroPromiseBuiltinCall(const CallExpr *e);
2178 cir::CoroDoneOp emitCoroDoneBuiltinCall(const CallExpr *e);
2179 cir::CoroResumeOp emitCoroResumeBuiltinCall(const CallExpr *e);
2180 cir::CoroDestroyOp emitCoroDestroyBuiltinCall(const CallExpr *e);
2181 cir::CoroNoopOp emitCoroNoopBuiltinCall(const CallExpr *e);
2182 cir::CoroSuspendOp emitCoroSuspendBuiltinCall(const CallExpr *e);
2183
2184 cir::CoroSizeOp emitCoroSizeBuiltinCall(const CallExpr *e);
2185 cir::CoroAlignOp emitCoroAlignBuiltinCall(const CallExpr *e);
2186 cir::CoroFreeOp emitCoroFreeBuiltin(const CallExpr *e);
2188
2189 void emitDestroy(Address addr, QualType type, Destroyer *destroyer);
2190
2192
2193 mlir::LogicalResult emitContinueStmt(const clang::ContinueStmt &s);
2194
2195 mlir::LogicalResult emitCoreturnStmt(const CoreturnStmt &s);
2196
2198 AggValueSlot dest);
2199
2202 Address arrayBegin, const CXXConstructExpr *e,
2203 bool newPointerIsChecked,
2204 bool zeroInitialize = false);
2206 mlir::Value numElements, Address arrayBase,
2207 const CXXConstructExpr *e,
2208 bool newPointerIsChecked, bool zeroInitialize,
2209 Address endOfInit);
2211 clang::CXXCtorType type, bool forVirtualBase,
2212 bool delegating, AggValueSlot thisAVS,
2213 const clang::CXXConstructExpr *e);
2214
2216 clang::CXXCtorType type, bool forVirtualBase,
2217 bool delegating, Address thisAddr,
2219
2221 bool forVirtualBase, Address thisAddr,
2222 bool inheritedFromVBase,
2223 const CXXInheritedCtorInitExpr *e);
2224
2226 SourceLocation loc, const CXXConstructorDecl *d, CXXCtorType ctorType,
2227 bool forVirtualBase, bool delegating, CallArgList &args);
2228
2229 void emitCXXDeleteExpr(const CXXDeleteExpr *e);
2230
2232 bool forVirtualBase, bool delegating,
2233 Address thisAddr, QualType thisTy);
2234
2236 mlir::Value thisVal, QualType thisTy,
2237 mlir::Value implicitParam,
2238 QualType implicitParamTy, const CallExpr *e);
2239
2240 mlir::LogicalResult emitCXXForRangeStmt(const CXXForRangeStmt &s,
2242
2245
2247 const Expr *e, Address base, mlir::Value memberPtr,
2248 const MemberPointerType *memberPtrType, LValueBaseInfo *baseInfo);
2249
2251 const clang::CXXMethodDecl *md, const CIRGenCallee &callee,
2252 ReturnValueSlot returnValue, mlir::Value thisPtr,
2253 mlir::Value implicitParam, clang::QualType implicitParamTy,
2254 const clang::CallExpr *ce, CallArgList *rtlArgs);
2255
2257 const clang::CallExpr *ce, const clang::CXXMethodDecl *md,
2258 ReturnValueSlot returnValue, bool hasQualifier,
2259 clang::NestedNameSpecifier qualifier, bool isArrow,
2260 const clang::Expr *base);
2261
2264
2265 mlir::Value emitCXXNewExpr(const CXXNewExpr *e);
2266
2267 void emitNewArrayInitializer(const CXXNewExpr *e, QualType elementType,
2268 mlir::Type elementTy, Address beginPtr,
2269 mlir::Value numElements,
2270 mlir::Value allocSizeWithoutCookie);
2271
2272 /// Create a check for a function parameter that may potentially be
2273 /// declared as non-null.
2274 void emitNonNullArgCheck(RValue rv, QualType argType, SourceLocation argLoc,
2275 AbstractCallee ac, unsigned paramNum);
2276
2278 const CXXMethodDecl *md,
2280
2283
2285
2287 const CallExpr *callExpr,
2289
2290 void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType,
2291 Address ptr);
2292
2293 void emitCXXThrowExpr(const CXXThrowExpr *e);
2294
2296 virtual mlir::LogicalResult operator()(CIRGenFunction &cgf) = 0;
2297 virtual ~cxxTryBodyEmitter() = default;
2298 };
2299
2300 void emitBeginCatch(const CXXCatchStmt *catchStmt, mlir::Value ehToken);
2301
2302 mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s,
2303 cxxTryBodyEmitter &bodyCallback,
2304 bool isFnTryBlock = false);
2305 mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s);
2306
2308 clang::CXXCtorType ctorType, FunctionArgList &args);
2309
2310 // It's important not to confuse this and emitDelegateCXXConstructorCall.
2311 // Delegating constructors are the C++11 feature. The constructor delegate
2312 // optimization is used to reduce duplication in the base and complete
2313 // constructors where they are substantially the same.
2315 const FunctionArgList &args);
2316
2317 void emitDeleteCall(const FunctionDecl *deleteFD, mlir::Value ptr,
2318 QualType deleteTy);
2319
2320 mlir::LogicalResult emitDoStmt(const clang::DoStmt &s,
2321 llvm::ArrayRef<const Attr *> attrs = {});
2322
2323 mlir::Value emitCXXTypeidExpr(const CXXTypeidExpr *e);
2324 mlir::Value emitDynamicCast(Address thisAddr, const CXXDynamicCastExpr *dce);
2325
2326 /// Emit an expression as an initializer for an object (variable, field, etc.)
2327 /// at the given location. The expression is not necessarily the normal
2328 /// initializer for the object, and the address is not necessarily
2329 /// its normal location.
2330 ///
2331 /// \param init the initializing expression
2332 /// \param d the object to act as if we're initializing
2333 /// \param lvalue the lvalue to initialize
2334 /// \param capturedByInit true if \p d is a __block variable whose address is
2335 /// potentially changed by the initializer
2336 void emitExprAsInit(const clang::Expr *init, const clang::ValueDecl *d,
2337 LValue lvalue, bool capturedByInit = false);
2338
2339 mlir::LogicalResult emitFunctionBody(const clang::Stmt *body);
2340
2341 mlir::LogicalResult emitGotoStmt(const clang::GotoStmt &s);
2342
2343 mlir::LogicalResult emitIndirectGotoStmt(const IndirectGotoStmt &s);
2344
2346
2348 clang::Expr *init);
2349
2351
2352 mlir::Value emitPromotedComplexExpr(const Expr *e, QualType promotionType);
2353
2354 mlir::Value emitPromotedScalarExpr(const Expr *e, QualType promotionType);
2355
2356 mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType);
2357
2358 void emitReturnOfRValue(mlir::Location loc, RValue rv, QualType ty);
2359
2360 mlir::Value emitRuntimeCall(mlir::Location loc, cir::FuncOp callee,
2362 mlir::NamedAttrList attrs = {});
2363
2364 void emitInvariantStart(CharUnits size, mlir::Value addr, mlir::Location loc);
2365
2366 /// Emit the computation of the specified expression of scalar type.
2367 mlir::Value emitScalarExpr(const clang::Expr *e,
2368 bool ignoreResultAssign = false);
2369
2370 mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv);
2371
2372 /// Build a debug stoppoint if we are emitting debug info.
2373 void emitStopPoint(const Stmt *s);
2374
2375 // Build CIR for a statement. useCurrentScope should be true if no
2376 // new scopes need be created when finding a compound statement.
2377 mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope,
2378 llvm::ArrayRef<const Attr *> attrs = {});
2379
2380 mlir::LogicalResult emitSimpleStmt(const clang::Stmt *s,
2381 bool useCurrentScope);
2382
2383 mlir::LogicalResult emitForStmt(const clang::ForStmt &s,
2384 llvm::ArrayRef<const Attr *> attrs = {});
2385
2386 void emitForwardingCallToLambda(const CXXMethodDecl *lambdaCallOperator,
2387 CallArgList &callArgs);
2388
2389 RValue emitCoawaitExpr(const CoawaitExpr &e,
2390 AggValueSlot aggSlot = AggValueSlot::ignored(),
2391 bool ignoreResult = false);
2392 LValue emitCoawaitLValue(const CoawaitExpr *e);
2393
2394 RValue emitCoyieldExpr(const CoyieldExpr &e,
2395 AggValueSlot aggSlot = AggValueSlot::ignored(),
2396 bool ignoreResult = false);
2397 LValue emitCoyieldLValue(const CoyieldExpr *e);
2398 /// Emit the computation of the specified expression of complex type,
2399 /// returning the result.
2400 mlir::Value emitComplexExpr(const Expr *e);
2401
2402 void emitComplexExprIntoLValue(const Expr *e, LValue dest, bool isInit);
2403
2404 mlir::Value emitComplexPrePostIncDec(const UnaryOperator *e, LValue lv);
2405
2406 LValue emitComplexAssignmentLValue(const BinaryOperator *e);
2407 LValue emitComplexCompoundAssignmentLValue(const CompoundAssignOperator *e);
2408 LValue emitScalarCompoundAssignWithComplex(const CompoundAssignOperator *e,
2409 mlir::Value &result);
2410
2411 mlir::LogicalResult
2412 emitCompoundStmt(const clang::CompoundStmt &s, Address *lastValue = nullptr,
2413 AggValueSlot slot = AggValueSlot::ignored());
2414
2415 mlir::LogicalResult
2417 Address *lastValue = nullptr,
2418 AggValueSlot slot = AggValueSlot::ignored());
2419
2420 void emitDecl(const clang::Decl &d, bool evaluateConditionDecl = false);
2421 mlir::LogicalResult emitDeclStmt(const clang::DeclStmt &s);
2422 LValue emitDeclRefLValue(const clang::DeclRefExpr *e);
2423
2424 mlir::LogicalResult emitDefaultStmt(const clang::DefaultStmt &s,
2425 mlir::Type condType,
2426 bool buildingTopLevelCase);
2427
2428 void emitDelegateCXXConstructorCall(const clang::CXXConstructorDecl *ctor,
2429 clang::CXXCtorType ctorType,
2430 const FunctionArgList &args,
2431 clang::SourceLocation loc);
2432
2433 /// We are performing a delegate call; that is, the current function is
2434 /// delegating to another one. Produce a r-value suitable for passing the
2435 /// given parameter.
2436 void emitDelegateCallArg(CallArgList &args, const clang::VarDecl *param,
2437 clang::SourceLocation loc);
2438
2439 /// Emit an `if` on a boolean condition to the specified blocks.
2440 /// FIXME: Based on the condition, this might try to simplify the codegen of
2441 /// the conditional based on the branch.
2442 /// In the future, we may apply code generation simplifications here,
2443 /// similar to those used in classic LLVM codegen
2444 /// See `EmitBranchOnBoolExpr` for inspiration.
2445 mlir::LogicalResult emitIfOnBoolExpr(const clang::Expr *cond,
2446 const clang::Stmt *thenS,
2447 const clang::Stmt *elseS);
2448 cir::IfOp emitIfOnBoolExpr(const clang::Expr *cond,
2449 BuilderCallbackRef thenBuilder,
2450 mlir::Location thenLoc,
2451 BuilderCallbackRef elseBuilder,
2452 std::optional<mlir::Location> elseLoc = {});
2453
2454 /// Build the cir.if for an already-emitted condition value.
2455 cir::IfOp emitIfOnBoolValue(mlir::Value condV, mlir::Location loc,
2456 BuilderCallbackRef thenBuilder,
2457 mlir::Location thenLoc,
2458 BuilderCallbackRef elseBuilder,
2459 std::optional<mlir::Location> elseLoc = {});
2460
2461 mlir::Value emitOpOnBoolExpr(mlir::Location loc, const clang::Expr *cond);
2462
2463 LValue emitPointerToDataMemberBinaryExpr(const BinaryOperator *e);
2464
2465 mlir::LogicalResult emitLabel(const clang::LabelDecl &d);
2466 mlir::LogicalResult emitLabelStmt(const clang::LabelStmt &s);
2467
2468 void emitLambdaDelegatingInvokeBody(const CXXMethodDecl *md);
2469 void emitLambdaStaticInvokeBody(const CXXMethodDecl *md);
2470
2471 mlir::LogicalResult emitIfStmt(const clang::IfStmt &s);
2472
2473 /// Emit code to compute the specified expression,
2474 /// ignoring the result.
2475 void emitIgnoredExpr(const clang::Expr *e);
2476
2477 RValue emitLoadOfBitfieldLValue(LValue lv, SourceLocation loc);
2478
2479 /// Load a complex number from the specified l-value.
2480 mlir::Value emitLoadOfComplex(LValue src, SourceLocation loc);
2481
2482 RValue emitLoadOfExtVectorElementLValue(LValue lv);
2483
2484 /// Given an expression that represents a value lvalue, this method emits
2485 /// the address of the lvalue, then loads the result as an rvalue,
2486 /// returning the rvalue.
2487 RValue emitLoadOfLValue(LValue lv, SourceLocation loc);
2488
2489 Address emitLoadOfReference(LValue refLVal, mlir::Location loc,
2490 LValueBaseInfo *pointeeBaseInfo);
2491 LValue emitLoadOfReferenceLValue(Address refAddr, mlir::Location loc,
2492 QualType refTy, AlignmentSource source);
2493
2494 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2495 /// care to appropriately convert from the memory representation to
2496 /// the LLVM value representation. The l-value must be a simple
2497 /// l-value.
2498 mlir::Value emitLoadOfScalar(LValue lvalue, SourceLocation loc);
2499 mlir::Value emitLoadOfScalar(Address addr, bool isVolatile, QualType ty,
2500 SourceLocation loc, LValueBaseInfo baseInfo,
2501 bool isNontemporal = false);
2502
2503 /// Emit code to compute a designator that specifies the location
2504 /// of the expression.
2505 /// FIXME: document this function better.
2506 LValue emitLValue(const clang::Expr *e);
2507 LValue emitLValueForBitField(LValue base, const FieldDecl *field);
2508 LValue emitLValueForField(LValue base, const clang::FieldDecl *field);
2509
2510 /// Annotate the address of `field`; accesses must use the result.
2511 Address emitFieldAnnotations(const clang::FieldDecl *field, Address addr);
2512
2513 /// Annotate the storage of `d` at `addr`.
2514 void emitVarAnnotations(const clang::VarDecl *d, mlir::Value addr);
2515
2516 LValue emitLValueForLambdaField(const FieldDecl *field);
2517 LValue emitLValueForLambdaField(const FieldDecl *field,
2518 mlir::Value thisValue);
2519
2521 mlir::Value size = vlaSizeMap[vat->getSizeExpr()];
2523 }
2524
2525 /// Like emitLValueForField, excpet that if the Field is a reference, this
2526 /// will return the address of the reference and not the address of the value
2527 /// stored in the reference.
2529 const clang::FieldDecl *field,
2530 llvm::StringRef fieldName);
2531
2533
2536
2537 /// Emit a musttail call for a thunk with a potentially different ABI.
2538 void emitMustTailThunk(GlobalDecl gd, mlir::Value adjustedThisPtr,
2539 cir::FuncOp callee);
2540
2541 /// Emit a call to an AMDGPU builtin function.
2542 std::optional<mlir::Value> emitAMDGPUBuiltinExpr(unsigned builtinID,
2543 const CallExpr *expr);
2544
2545 /// Emit a call to an NVPTX builtin function.
2546 std::optional<mlir::Value> emitNVPTXBuiltinExpr(unsigned builtinID,
2547 const CallExpr *expr);
2548
2549 /// Emit a call to a SPIR-V builtin function.
2550 std::optional<mlir::Value> emitSPIRVBuiltinExpr(unsigned builtinID,
2551 const CallExpr *expr);
2552
2553 /// Emit a device-side printf call for GPU targets.
2554 mlir::Value emitDevicePrintfCallExpr(const CallExpr *expr);
2555
2557
2559
2560 /// Given an expression with a pointer type, emit the value and compute our
2561 /// best estimate of the alignment of the pointee.
2562 ///
2563 /// One reasonable way to use this information is when there's a language
2564 /// guarantee that the pointer must be aligned to some stricter value, and
2565 /// we're simply trying to ensure that sufficiently obvious uses of under-
2566 /// aligned objects don't get miscompiled; for example, a placement new
2567 /// into the address of a local variable. In such a case, it's quite
2568 /// reasonable to just ignore the returned alignment when it isn't from an
2569 /// explicit source.
2571 LValueBaseInfo *baseInfo = nullptr);
2572
2573 /// Emits a reference binding to the passed in expression.
2575
2576 mlir::LogicalResult emitReturnStmt(const clang::ReturnStmt &s);
2577
2578 RValue emitRotate(const CallExpr *e, bool isRotateLeft);
2579
2580 mlir::Value emitScalarConstant(const ConstantEmission &constant, Expr *e);
2581
2582 /// Emit a conversion from the specified type to the specified destination
2583 /// type, both of which are CIR scalar types.
2584 mlir::Value emitScalarConversion(mlir::Value src, clang::QualType srcType,
2585 clang::QualType dstType,
2587
2588 void emitScalarInit(const clang::Expr *init, LValue lvalue,
2589 bool capturedByInit = false);
2590
2591 mlir::Value emitScalarOrConstFoldImmArg(unsigned iceArguments, unsigned idx,
2592 const Expr *argExpr);
2593
2594 void emitStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage);
2595
2596 /// Emit a guarded initializer for a static local variable.
2597 void emitCXXGuardedInit(const VarDecl &varDecl, cir::GlobalOp globalOp,
2598 bool performInit);
2599
2600 void emitStoreOfComplex(mlir::Location loc, mlir::Value v, LValue dest,
2601 bool isInit);
2602
2603 void emitStoreOfScalar(mlir::Value value, Address addr, bool isVolatile,
2604 clang::QualType ty, LValueBaseInfo baseInfo,
2605 bool isInit = false, bool isNontemporal = false);
2606 void emitStoreOfScalar(mlir::Value value, LValue lvalue, bool isInit);
2607
2609
2610 /// Store the specified rvalue into the specified
2611 /// lvalue, where both are guaranteed to the have the same type, and that
2612 /// type is 'Ty'.
2613 void emitStoreThroughLValue(RValue src, LValue dst, bool isInit = false);
2614
2615 mlir::Value emitStoreThroughBitfieldLValue(RValue src, LValue dstresult);
2616
2618 llvm::StringRef name = ".str");
2619
2620 mlir::LogicalResult emitSwitchBody(const clang::Stmt *s);
2621 mlir::LogicalResult emitSwitchCase(const clang::SwitchCase &s,
2622 bool buildingTopLevelCase);
2623 mlir::LogicalResult emitSwitchStmt(const clang::SwitchStmt &s);
2624
2625 mlir::LogicalResult emitSYCLKernelCallStmt(const SYCLKernelCallStmt &s);
2626
2627 void emitSYCLKernelCaller(const clang::OutlinedFunctionDecl *outlinedFnDecl,
2628 cir::FuncOp funcOp, cir::FuncType funcType,
2629 FunctionArgList &args);
2630
2631 /// Remove leftover empty and unreachable blocks from an emitted function.
2632 static void eraseEmptyAndUnusedBlocks(cir::FuncOp func);
2633
2634 std::optional<mlir::Value>
2635 emitTargetBuiltinExpr(unsigned builtinID, const clang::CallExpr *e,
2637
2638 /// Emit a diagnostic if the target features required by \p targetDecl are
2639 /// not available in the calling function. Mirrors CodeGenFunction behavior.
2641 const clang::FunctionDecl *targetDecl);
2643 const clang::FunctionDecl *targetDecl);
2644
2645 /// Given a value and its clang type, returns the value casted to its memory
2646 /// representation.
2647 /// Note: CIR defers most of the special casting to the final lowering passes
2648 /// to conserve the high level information.
2649 mlir::Value emitToMemory(mlir::Value value, clang::QualType ty);
2650
2651 /// EmitFromMemory - Change a scalar value from its memory
2652 /// representation to its value representation.
2653 mlir::Value emitFromMemory(mlir::Value value, clang::QualType ty);
2654
2655 /// Emit a trap instruction, which is used to abort the program in an abnormal
2656 /// way, usually for debugging purposes.
2657 /// \p createNewBlock indicates whether to create a new block for the IR
2658 /// builder. Since the `cir.trap` operation is a terminator, operations that
2659 /// follow a trap cannot be emitted after `cir.trap` in the same block. To
2660 /// ensure these operations get emitted successfully, you need to create a new
2661 /// dummy block and set the insertion point there before continuing from the
2662 /// trap operation.
2663 void emitTrap(mlir::Location loc, bool createNewBlock);
2664
2666
2667 mlir::Value emitUnPromotedValue(mlir::Value result, QualType unPromotionType);
2668
2669 /// Emit a reached-unreachable diagnostic if \p loc is valid and runtime
2670 /// checking is enabled. Otherwise, just emit an unreachable instruction.
2671 /// \p createNewBlock indicates whether to create a new block for the IR
2672 /// builder. Since the `cir.unreachable` operation is a terminator, operations
2673 /// that follow an unreachable point cannot be emitted after `cir.unreachable`
2674 /// in the same block. To ensure these operations get emitted successfully,
2675 /// you need to create a dummy block and set the insertion point there before
2676 /// continuing from the unreachable point.
2677 void emitUnreachable(clang::SourceLocation loc, bool createNewBlock);
2678
2679 /// This method handles emission of any variable declaration
2680 /// inside a function, including static vars etc.
2681 void emitVarDecl(const clang::VarDecl &d);
2682
2684
2685 mlir::LogicalResult emitWhileStmt(const clang::WhileStmt &s,
2686 llvm::ArrayRef<const Attr *> attrs = {});
2687
2688 /// Build the hints that get attached to a loop, or a null attribute
2689 /// if there is nothing to say about it.
2690 cir::LoopHintAttr getLoopHints(llvm::ArrayRef<const Attr *> attrs,
2691 bool mustProgress);
2692
2693 std::optional<mlir::Value> emitRISCVBuiltinExpr(unsigned builtinID,
2694 const CallExpr *expr);
2695 cir::GetGlobalOp createGetCpuModel(mlir::Location loc);
2696 cir::GetGlobalOp createGetCpuFeatures2(mlir::Location loc);
2697 mlir::Value emitX86CpuIs(const CallExpr *expr);
2698 mlir::Value emitX86CpuIs(mlir::Location loc, StringRef cpuStr);
2699 mlir::Value emitX86CpuSupports(const CallExpr *expr);
2700 mlir::Value emitX86CpuSupports(mlir::Location loc,
2701 ArrayRef<StringRef> FeatureStrs);
2702 mlir::Value emitX86CpuSupports(mlir::Location loc,
2703 std::array<uint32_t, 4> FeatureMask);
2704 mlir::Value emitX86CpuInit(mlir::Location loc);
2706 mlir::Value emitX86MSVCIntrin(MSVCIntrin builtinID, const CallExpr *E);
2707 std::optional<mlir::Value> emitX86BuiltinExpr(unsigned builtinID,
2708 const CallExpr *expr);
2709
2710 /// Given an assignment `*lhs = rhs`, emit a test that checks if \p rhs is
2711 /// nonnull, if 1\p LHS is marked _Nonnull.
2712 void emitNullabilityCheck(LValue lhs, mlir::Value rhs,
2714
2715 /// An object to manage conditionally-evaluated expressions.
2717 CIRGenFunction &cgf;
2718
2719 /// The insertion point that precedes the conditional, stored as the
2720 /// enclosing block and the operation immediately before that point. Later
2721 /// operations (the condition, cleanup scopes) can be appended without
2722 /// moving this point. A null \c anchorAfter means the insertion point is
2723 /// the start of \c anchorBlock.
2724 mlir::Block *anchorBlock;
2725 mlir::Operation *anchorAfter = nullptr;
2726
2727 public:
2728 /// \p loc is the location of the conditional expression. It is used for
2729 /// the cleanup scope this may open.
2730 ConditionalEvaluation(CIRGenFunction &cgf, mlir::Location loc) : cgf(cgf) {
2731 // Open the cleanup scope that hosts cleanups deferred from inside this
2732 // conditional (see deferredConditionalCleanupStack). Only the outermost
2733 // conditional opens one, and only while a FullExprCleanupScope is
2734 // active to close it. When nothing is deferred into it the cleanup
2735 // region stays trivial and canonicalization inlines the scope away.
2736 if (cgf.currentFullExprCleanupScope && !cgf.isInConditionalBranch()) {
2737 cir::CleanupKind cleanupKind = cgf.getLangOpts().Exceptions
2738 ? cir::CleanupKind::All
2739 : cir::CleanupKind::Normal;
2740 cir::CleanupScopeOp scope = cir::CleanupScopeOp::create(
2741 cgf.builder, loc, cleanupKind,
2742 /*bodyBuilder=*/[](mlir::OpBuilder &, mlir::Location) {},
2743 /*cleanupBuilder=*/[](mlir::OpBuilder &, mlir::Location) {});
2744 cgf.conditionalCleanupScopes.push_back(
2745 {scope, cgf.deferredConditionalCleanupStack.size()});
2746 cgf.builder.setInsertionPointToEnd(&scope.getBodyRegion().front());
2747 }
2748
2749 anchorBlock = cgf.builder.getInsertionBlock();
2750 assert(anchorBlock && "conditional evaluation needs an insertion point");
2751 mlir::Block::iterator ip = cgf.builder.getInsertionPoint();
2752 if (ip != anchorBlock->begin())
2753 anchorAfter = &*std::prev(ip);
2754 }
2755
2757 assert(cgf.outermostConditional != this);
2758 if (!cgf.outermostConditional)
2759 cgf.outermostConditional = this;
2760 }
2761
2763 assert(cgf.outermostConditional != nullptr);
2764 if (cgf.outermostConditional == this)
2765 cgf.outermostConditional = nullptr;
2766 }
2767
2768 /// Records \p op as the last operation emitted at the pre-conditional
2769 /// insertion point, so that a later emission lands after it rather than
2770 /// ahead of it.
2771 void advanceInsertPoint(mlir::Operation *op) { anchorAfter = op; }
2772
2773 /// Returns the insertion point which will be executed prior to each
2774 /// evaluation of the conditional code. In LLVM OG, this method
2775 /// is called getStartingBlock.
2776 mlir::OpBuilder::InsertPoint getInsertPoint() const {
2777 if (!anchorAfter)
2778 return mlir::OpBuilder::InsertPoint(anchorBlock, anchorBlock->begin());
2779 return mlir::OpBuilder::InsertPoint(
2780 anchorAfter->getBlock(), std::next(anchorAfter->getIterator()));
2781 }
2782 };
2783
2785 std::optional<LValue> lhs{}, rhs{};
2786 mlir::Value result{};
2787 };
2788
2789 // Return true if we're currently emitting one branch or the other of a
2790 // conditional expression.
2791 bool isInConditionalBranch() const { return outermostConditional != nullptr; }
2792
2793 void setBeforeOutermostConditional(mlir::Value value, Address addr) {
2794 assert(isInConditionalBranch());
2795 {
2796 mlir::OpBuilder::InsertionGuard guard(builder);
2797 builder.restoreInsertionPoint(outermostConditional->getInsertPoint());
2798 cir::StoreOp store = builder.createStore(
2799 value.getLoc(), value, addr, /*isVolatile=*/false,
2800 /*isNontemporal=*/false,
2801 mlir::IntegerAttr::get(
2802 mlir::IntegerType::get(value.getContext(), 64),
2803 (uint64_t)addr.getAlignment().getAsAlign().value()));
2804 outermostConditional->advanceInsertPoint(store);
2805 }
2806 }
2807
2808 // Points to the outermost active conditional control. This is used so that
2809 // we know if a temporary should be destroyed conditionally.
2811
2812 // The outermost conditional that a FullExprCleanupScope in a conditional
2813 // branch hides from isInConditionalBranch(), if any. The cleanups of that
2814 // full-expression run at its end, so they are not conditional, but a
2815 // temporary whose lifetime is extended beyond it is still created
2816 // conditionally.
2818
2819 /// An RAII object to record that we're evaluating a statement
2820 /// expression.
2822 CIRGenFunction &cgf;
2823
2824 /// We have to save the outermost conditional: cleanups in a
2825 /// statement expression aren't conditional just because the
2826 /// StmtExpr is.
2827 ConditionalEvaluation *savedOutermostConditional;
2828 ConditionalEvaluation *savedHiddenOutermostConditional;
2829
2830 public:
2832 : cgf(cgf), savedOutermostConditional(cgf.outermostConditional),
2833 savedHiddenOutermostConditional(cgf.hiddenOutermostConditional) {
2834 cgf.outermostConditional = nullptr;
2835 cgf.hiddenOutermostConditional = nullptr;
2836 }
2837
2839 cgf.outermostConditional = savedOutermostConditional;
2840 cgf.hiddenOutermostConditional = savedHiddenOutermostConditional;
2841 }
2842 };
2843
2844 template <typename FuncTy>
2845 ConditionalInfo emitConditionalBlocks(const AbstractConditionalOperator *e,
2846 const FuncTy &branchGenFunc);
2847
2848 /// Build a "reference" to a va_list; this is either the address or the value
2849 /// of the expression, depending on how va_list is defined.
2850 Address emitVAListRef(const Expr *e);
2851
2852 /// Emits the start of a CIR variable-argument operation (`cir.va_start`)
2853 ///
2854 /// \param vaList A reference to the \c va_list as emitted by either
2855 /// \c emitVAListRef or \c emitMSVAListRef.
2856 void emitVAStart(mlir::Value vaList);
2857
2858 /// Emits the end of a CIR variable-argument operation (`cir.va_start`)
2859 ///
2860 /// \param vaList A reference to the \c va_list as emitted by either
2861 /// \c emitVAListRef or \c emitMSVAListRef.
2862 void emitVAEnd(mlir::Value vaList);
2863
2864 /// Generate code to get an argument from the passed in pointer
2865 /// and update it accordingly.
2866 ///
2867 /// \param ve The \c VAArgExpr for which to generate code.
2868 ///
2869 /// \param vaListAddr Receives a reference to the \c va_list as emitted by
2870 /// either \c emitVAListRef or \c emitMSVAListRef.
2871 ///
2872 /// \returns SSA value with the argument.
2873 mlir::Value emitVAArg(VAArgExpr *ve);
2874
2875 /// ----------------------
2876 /// CIR build helpers
2877 /// -----------------
2878public:
2879 cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc,
2880 const Twine &name = "tmp",
2881 mlir::Value arraySize = nullptr,
2882 bool insertIntoFnEntryBlock = false);
2883 cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc,
2884 const Twine &name = "tmp",
2885 mlir::OpBuilder::InsertPoint ip = {},
2886 mlir::Value arraySize = nullptr);
2887 Address createTempAlloca(mlir::Type ty, CharUnits align, mlir::Location loc,
2888 const Twine &name = "tmp",
2889 mlir::Value arraySize = nullptr,
2890 Address *alloca = nullptr,
2891 mlir::OpBuilder::InsertPoint ip = {});
2892 Address createTempAlloca(mlir::Type ty,
2893 mlir::ptr::MemorySpaceAttrInterface destAddrSpace,
2894 CharUnits align, mlir::Location loc,
2895 const Twine &name = "tmp",
2896 mlir::Value arraySize = nullptr,
2897 Address *alloca = nullptr,
2898 mlir::OpBuilder::InsertPoint ip = {});
2899 Address createTempAllocaWithoutCast(mlir::Type ty, CharUnits align,
2900 mlir::Location loc,
2901 const Twine &name = "tmp",
2902 mlir::Value arraySize = nullptr,
2903 mlir::OpBuilder::InsertPoint ip = {});
2904 Address
2905 maybeCastStackAddressSpace(Address alloca,
2906 mlir::ptr::MemorySpaceAttrInterface destAddrSpace,
2907 mlir::Value arraySize = nullptr);
2908 Address createDefaultAlignTempAlloca(mlir::Type ty, mlir::Location loc,
2909 const Twine &name);
2910
2911 /// Create a temporary memory object of the given type, with
2912 /// appropriate alignmen and cast it to the default address space. Returns
2913 /// the original alloca instruction by \p Alloca if it is not nullptr.
2914 Address createMemTemp(QualType t, mlir::Location loc,
2915 const Twine &name = "tmp", Address *alloca = nullptr,
2916 mlir::OpBuilder::InsertPoint ip = {});
2917 Address createMemTemp(QualType t, CharUnits align, mlir::Location loc,
2918 const Twine &name = "tmp", Address *alloca = nullptr,
2919 mlir::OpBuilder::InsertPoint ip = {});
2920 Address createMemTempWithoutCast(QualType t, mlir::Location loc,
2921 const Twine &name = "tmp");
2922
2923 mlir::Value performAddrSpaceCast(mlir::Value v, mlir::Type destTy) const {
2924 if (cir::GlobalOp globalOp = v.getDefiningOp<cir::GlobalOp>())
2925 cgm.errorNYI("Global op addrspace cast");
2926 return builder.createAddrSpaceCast(v, destTy);
2927 }
2928
2929 //===--------------------------------------------------------------------===//
2930 // OpenMP Emission
2931 //===--------------------------------------------------------------------===//
2932public:
2933 /// Emits a Sema-synthesized OpenMP helper variable (loop counter, iteration
2934 /// variable or pre-init capture) without lifetime markers. These variables
2935 /// are emitted between nested combined/composite OpenMP ops, which must be
2936 /// direct children of each other's regions, so they must not open a
2937 /// lifetime cleanup scope.
2938 void emitOMPNoLifetimeVarDecl(const VarDecl &d);
2939
2940 mlir::LogicalResult emitOMPScopeDirective(const OMPScopeDirective &s);
2941 mlir::LogicalResult emitOMPErrorDirective(const OMPErrorDirective &s);
2942 mlir::LogicalResult emitOMPParallelDirective(const OMPParallelDirective &s);
2943 mlir::LogicalResult emitOMPTaskwaitDirective(const OMPTaskwaitDirective &s);
2944 mlir::LogicalResult emitOMPTaskyieldDirective(const OMPTaskyieldDirective &s);
2945 mlir::LogicalResult emitOMPBarrierDirective(const OMPBarrierDirective &s);
2946 mlir::LogicalResult emitOMPMetaDirective(const OMPMetaDirective &s);
2947 mlir::LogicalResult emitOMPCanonicalLoop(const OMPCanonicalLoop &s);
2948 mlir::LogicalResult emitOMPSimdDirective(const OMPSimdDirective &s);
2949 mlir::LogicalResult emitOMPTileDirective(const OMPTileDirective &s);
2950 mlir::LogicalResult emitOMPUnrollDirective(const OMPUnrollDirective &s);
2951 mlir::LogicalResult emitOMPFuseDirective(const OMPFuseDirective &s);
2952 mlir::LogicalResult emitOMPForDirective(const OMPForDirective &s);
2953 mlir::LogicalResult emitOMPForSimdDirective(const OMPForSimdDirective &s);
2954 mlir::LogicalResult emitOMPSectionsDirective(const OMPSectionsDirective &s);
2955 mlir::LogicalResult emitOMPSectionDirective(const OMPSectionDirective &s);
2956 mlir::LogicalResult emitOMPSingleDirective(const OMPSingleDirective &s);
2957 mlir::LogicalResult emitOMPMasterDirective(const OMPMasterDirective &s);
2958 mlir::LogicalResult emitOMPCriticalDirective(const OMPCriticalDirective &s);
2959 mlir::LogicalResult
2960 emitOMPParallelForDirective(const OMPParallelForDirective &s);
2961 mlir::LogicalResult
2962 emitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &s);
2963 mlir::LogicalResult
2964 emitOMPParallelMasterDirective(const OMPParallelMasterDirective &s);
2965 mlir::LogicalResult
2966 emitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &s);
2967 mlir::LogicalResult emitOMPTaskDirective(const OMPTaskDirective &s);
2968 mlir::LogicalResult emitOMPTaskgroupDirective(const OMPTaskgroupDirective &s);
2969 mlir::LogicalResult emitOMPFlushDirective(const OMPFlushDirective &s);
2970 mlir::LogicalResult emitOMPDepobjDirective(const OMPDepobjDirective &s);
2971 mlir::LogicalResult emitOMPScanDirective(const OMPScanDirective &s);
2972 mlir::LogicalResult
2973 emitOMPOrderedStandaloneDirective(const OMPOrderedStandaloneDirective &s);
2974 mlir::LogicalResult
2975 emitOMPOrderedBlockAssocDirective(const OMPOrderedBlockAssocDirective &s);
2976 mlir::LogicalResult emitOMPAtomicDirective(const OMPAtomicDirective &s);
2977 mlir::LogicalResult emitOMPTargetDirective(const OMPTargetDirective &s);
2978 mlir::LogicalResult emitOMPTeamsDirective(const OMPTeamsDirective &s);
2979 mlir::LogicalResult
2980 emitOMPCancellationPointDirective(const OMPCancellationPointDirective &s);
2981 mlir::LogicalResult emitOMPCancelDirective(const OMPCancelDirective &s);
2982 mlir::LogicalResult
2983 emitOMPTargetDataDirective(const OMPTargetDataDirective &s);
2984 mlir::LogicalResult
2985 emitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &s);
2986 mlir::LogicalResult
2987 emitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &s);
2988 mlir::LogicalResult
2989 emitOMPTargetParallelDirective(const OMPTargetParallelDirective &s);
2990 mlir::LogicalResult
2991 emitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &s);
2992 mlir::LogicalResult emitOMPTaskLoopDirective(const OMPTaskLoopDirective &s);
2993 mlir::LogicalResult
2994 emitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &s);
2995 mlir::LogicalResult
2996 emitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective &s);
2997 mlir::LogicalResult
2998 emitOMPMaskedTaskLoopSimdDirective(const OMPMaskedTaskLoopSimdDirective &s);
2999 mlir::LogicalResult
3000 emitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &s);
3001 mlir::LogicalResult
3002 emitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &s);
3003 mlir::LogicalResult
3004 emitOMPParallelGenericLoopDirective(const OMPParallelGenericLoopDirective &s);
3005 mlir::LogicalResult
3006 emitOMPParallelMaskedDirective(const OMPParallelMaskedDirective &s);
3007 mlir::LogicalResult emitOMPParallelMaskedTaskLoopDirective(
3009 mlir::LogicalResult emitOMPParallelMaskedTaskLoopSimdDirective(
3011 mlir::LogicalResult emitOMPParallelMasterTaskLoopDirective(
3013 mlir::LogicalResult emitOMPParallelMasterTaskLoopSimdDirective(
3015 mlir::LogicalResult
3017 mlir::LogicalResult emitOMPDistributeParallelForDirective(
3019 mlir::LogicalResult emitOMPDistributeParallelForSimdDirective(
3021 mlir::LogicalResult
3022 emitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &s);
3023 mlir::LogicalResult emitOMPTargetParallelGenericLoopDirective(
3025 mlir::LogicalResult
3026 emitOMPTargetGenericLoopDirective(const OMPTargetGenericLoopDirective &s);
3027 mlir::LogicalResult emitOMPTargetParallelForSimdDirective(
3029 mlir::LogicalResult
3030 emitOMPTargetSimdDirective(const OMPTargetSimdDirective &s);
3031 mlir::LogicalResult emitOMPTargetTeamsGenericLoopDirective(
3033 mlir::LogicalResult
3034 emitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &s);
3035 mlir::LogicalResult
3036 emitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &s);
3037 mlir::LogicalResult
3038 emitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &s);
3039 mlir::LogicalResult emitOMPTeamsDistributeParallelForSimdDirective(
3041 mlir::LogicalResult emitOMPTeamsDistributeParallelForDirective(
3043 mlir::LogicalResult
3044 emitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &s);
3045 mlir::LogicalResult
3046 emitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &s);
3047 mlir::LogicalResult emitOMPTargetTeamsDistributeDirective(
3049 mlir::LogicalResult emitOMPTargetTeamsDistributeParallelForDirective(
3051 mlir::LogicalResult emitOMPTargetTeamsDistributeParallelForSimdDirective(
3053 mlir::LogicalResult emitOMPTargetTeamsDistributeSimdDirective(
3055 mlir::LogicalResult emitOMPInteropDirective(const OMPInteropDirective &s);
3056 mlir::LogicalResult emitOMPDispatchDirective(const OMPDispatchDirective &s);
3057 mlir::LogicalResult
3058 emitOMPGenericLoopDirective(const OMPGenericLoopDirective &s);
3059 mlir::LogicalResult emitOMPReverseDirective(const OMPReverseDirective &s);
3060 mlir::LogicalResult emitOMPSplitDirective(const OMPSplitDirective &s);
3061 mlir::LogicalResult
3062 emitOMPInterchangeDirective(const OMPInterchangeDirective &s);
3063 mlir::LogicalResult emitOMPFlattenDirective(const OMPFlattenDirective &s);
3064 mlir::LogicalResult emitOMPAssumeDirective(const OMPAssumeDirective &s);
3065 mlir::LogicalResult emitOMPMaskedDirective(const OMPMaskedDirective &s);
3066 mlir::LogicalResult emitOMPStripeDirective(const OMPStripeDirective &s);
3067
3068 void emitOMPThreadPrivateDecl(const OMPThreadPrivateDecl &d);
3069 void emitOMPGroupPrivateDecl(const OMPGroupPrivateDecl &d);
3070 void emitOMPCapturedExpr(const OMPCapturedExprDecl &d);
3071 void emitOMPAllocateDecl(const OMPAllocateDecl &d);
3072 void emitOMPDeclareReduction(const OMPDeclareReductionDecl &d);
3073 void emitOMPDeclareMapper(const OMPDeclareMapperDecl &d);
3074 void emitOMPRequiresDecl(const OMPRequiresDecl &d);
3075
3076 //===--------------------------------------------------------------------===//
3077 // OpenACC Emission
3078 //===--------------------------------------------------------------------===//
3079private:
3080 template <typename Op>
3081 Op emitOpenACCOp(mlir::Location start, OpenACCDirectiveKind dirKind,
3083 // Function to do the basic implementation of an operation with an Associated
3084 // Statement. Models AssociatedStmtConstruct.
3085 template <typename Op, typename TermOp>
3086 mlir::LogicalResult
3087 emitOpenACCOpAssociatedStmt(mlir::Location start, mlir::Location end,
3088 OpenACCDirectiveKind dirKind,
3090 const Stmt *associatedStmt);
3091
3092 template <typename Op, typename TermOp>
3093 mlir::LogicalResult emitOpenACCOpCombinedConstruct(
3094 mlir::Location start, mlir::Location end, OpenACCDirectiveKind dirKind,
3095 llvm::ArrayRef<const OpenACCClause *> clauses, const Stmt *loopStmt);
3096
3097 template <typename Op>
3098 void emitOpenACCClauses(Op &op, OpenACCDirectiveKind dirKind,
3100 // The second template argument doesn't need to be a template, since it should
3101 // always be an mlir::acc::LoopOp, but as this is a template anyway, we make
3102 // it a template argument as this way we can avoid including the OpenACC MLIR
3103 // headers here. We will count on linker failures/explicit instantiation to
3104 // ensure we don't mess this up, but it is only called from 1 place, and
3105 // instantiated 3x.
3106 template <typename ComputeOp, typename LoopOp>
3107 void emitOpenACCClauses(ComputeOp &op, LoopOp &loopOp,
3108 OpenACCDirectiveKind dirKind,
3110
3111 // The OpenACC LoopOp requires that we have auto, seq, or independent on all
3112 // LoopOp operations for the 'none' device type case. This function checks if
3113 // the LoopOp has one, else it updates it to have one.
3114 void updateLoopOpParallelism(mlir::acc::LoopOp &op, bool isOrphan,
3116
3117 // The OpenACC 'cache' construct actually applies to the 'loop' if present. So
3118 // keep track of the 'loop' so that we can add the cache vars to it correctly.
3119 mlir::acc::LoopOp *activeLoopOp = nullptr;
3120
3121 struct ActiveOpenACCLoopRAII {
3122 CIRGenFunction &cgf;
3123 mlir::acc::LoopOp *oldLoopOp;
3124
3125 ActiveOpenACCLoopRAII(CIRGenFunction &cgf, mlir::acc::LoopOp *newOp)
3126 : cgf(cgf), oldLoopOp(cgf.activeLoopOp) {
3127 cgf.activeLoopOp = newOp;
3128 }
3129 ~ActiveOpenACCLoopRAII() { cgf.activeLoopOp = oldLoopOp; }
3130 };
3131
3132 // Keep track of the last place we inserted a 'recipe' so that we can insert
3133 // the next one in lexical order.
3134 mlir::OpBuilder::InsertPoint lastRecipeLocation;
3135
3136public:
3137 // Helper type used to store the list of important information for a 'data'
3138 // clause variable, or a 'cache' variable reference.
3140 mlir::Location beginLoc;
3141 mlir::Value varValue;
3142 std::string name;
3143 // The type of the original variable reference: that is, after 'bounds' have
3144 // removed pointers/array types/etc. So in the case of int arr[5], and a
3145 // private(arr[1]), 'origType' is 'int', but 'baseType' is 'int[5]'.
3149 // The list of types that we found when going through the bounds, which we
3150 // can use to properly set the alloca section.
3152 };
3153
3154 // Gets the collection of info required to lower and OpenACC clause or cache
3155 // construct variable reference.
3157 // Helper function to emit the integer expressions as required by an OpenACC
3158 // clause/construct.
3159 mlir::Value emitOpenACCIntExpr(const Expr *intExpr);
3160 // Helper function to emit an integer constant as an mlir int type, used for
3161 // constants in OpenACC constructs/clauses.
3162 mlir::Value createOpenACCConstantInt(mlir::Location loc, unsigned width,
3163 int64_t value);
3164
3165 mlir::LogicalResult
3167 mlir::LogicalResult emitOpenACCLoopConstruct(const OpenACCLoopConstruct &s);
3168 mlir::LogicalResult
3170 mlir::LogicalResult emitOpenACCDataConstruct(const OpenACCDataConstruct &s);
3171 mlir::LogicalResult
3173 mlir::LogicalResult
3175 mlir::LogicalResult
3177 mlir::LogicalResult emitOpenACCWaitConstruct(const OpenACCWaitConstruct &s);
3178 mlir::LogicalResult emitOpenACCInitConstruct(const OpenACCInitConstruct &s);
3179 mlir::LogicalResult
3181 mlir::LogicalResult emitOpenACCSetConstruct(const OpenACCSetConstruct &s);
3182 mlir::LogicalResult
3184 mlir::LogicalResult
3186 mlir::LogicalResult emitOpenACCCacheConstruct(const OpenACCCacheConstruct &s);
3187
3190
3191 /// Create a temporary memory object for the given aggregate type.
3192 AggValueSlot createAggTemp(QualType ty, mlir::Location loc,
3193 const Twine &name = "tmp",
3194 Address *alloca = nullptr) {
3196 return AggValueSlot::forAddr(
3197 createMemTemp(ty, loc, name, alloca), ty.getQualifiers(),
3200 }
3201
3202private:
3203 QualType getVarArgType(const Expr *arg);
3204
3205 bool shouldEmitLifetimeMarkers = false;
3206 /// Set when the current function has a goto/switch that may bypass a local's
3207 /// init; lifetime markers are then suppressed. See functionMightHaveBypass.
3208 bool fnHasBypassStmt = false;
3209
3210 bool shouldEmitLifetimeMarkersForAutoVar() const {
3211 return shouldEmitLifetimeMarkers && !fnHasBypassStmt;
3212 }
3213
3214 class InlinedInheritingConstructorScope {
3215 public:
3216 InlinedInheritingConstructorScope(CIRGenFunction &cgf, GlobalDecl gd)
3217 : cgf(cgf), oldCurGD(cgf.curGD), oldCurFuncDecl(cgf.curFuncDecl),
3218 oldCurCodeDecl(cgf.curCodeDecl),
3219 oldCxxabiThisDecl(cgf.cxxabiThisDecl),
3220 oldCxxThisValue(cgf.cxxThisValue),
3221 oldCxxabiThisAlignment(cgf.cxxabiThisAlignment),
3222 oldCxxThisAlignment(cgf.cxxThisAlignment),
3223 oldReturnValue(cgf.returnValue), oldFnRetTy(cgf.fnRetTy),
3224 oldCxxInheritedCtorInitExprArgs(
3225 std::move(cgf.cxxInheritedCtorInitExprArgs)) {
3226 cgf.curGD = gd;
3227 cgf.curFuncDecl = cast<CXXConstructorDecl>(gd.getDecl());
3228 cgf.curCodeDecl = cgf.curFuncDecl;
3229 cgf.cxxabiThisDecl = nullptr;
3230 cgf.cxxabiThisValue = nullptr;
3231 cgf.cxxThisValue = nullptr;
3232 cgf.cxxThisAlignment = CharUnits();
3233 cgf.cxxabiThisAlignment = CharUnits();
3234 cgf.returnValue = Address::invalid();
3235 cgf.fnRetTy = QualType();
3236 cgf.cxxInheritedCtorInitExprArgs.clear();
3237 // FIXME: at one point when we want to call one of these, we'll need
3238 // CXXInheritedCtorInitExprArgs here too.
3239 }
3240 ~InlinedInheritingConstructorScope() {
3241 cgf.curGD = oldCurGD;
3242 cgf.curFuncDecl = oldCurFuncDecl;
3243 cgf.curCodeDecl = oldCurCodeDecl;
3244 cgf.cxxabiThisDecl = oldCxxabiThisDecl;
3245 cgf.cxxabiThisValue = oldCxxabiThisValue;
3246 cgf.cxxThisValue = oldCxxThisValue;
3247 cgf.cxxThisAlignment = oldCxxThisAlignment;
3248 cgf.cxxabiThisAlignment = oldCxxabiThisAlignment;
3249 cgf.returnValue = oldReturnValue;
3250 cgf.fnRetTy = oldFnRetTy;
3251 cgf.cxxInheritedCtorInitExprArgs =
3252 std::move(oldCxxInheritedCtorInitExprArgs);
3253 }
3254
3255 private:
3256 CIRGenFunction &cgf;
3257 GlobalDecl oldCurGD;
3258 const Decl *oldCurFuncDecl;
3259 const Decl *oldCurCodeDecl;
3260 ImplicitParamDecl *oldCxxabiThisDecl;
3261 mlir::Value oldCxxabiThisValue;
3262 mlir::Value oldCxxThisValue;
3263 clang::CharUnits oldCxxabiThisAlignment;
3264 clang::CharUnits oldCxxThisAlignment;
3265 Address oldReturnValue;
3266 QualType oldFnRetTy;
3267 CallArgList oldCxxInheritedCtorInitExprArgs;
3268 };
3269};
3270
3271} // namespace clang::CIRGen
3272
3273#endif
Defines the clang::ASTContext interface.
static void emitOMPDistributeDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM)
static void emitOMPForDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM, bool HasCancel)
static void emitOMPSimdDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM)
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
Definition CIRDialect.h:34
static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr *expr, Address dest, Address ptr, Address val1, Address val2, Address expectedResult, Expr *isWeakExpr, Expr *failureOrderExpr, int64_t size, cir::MemOrder order, cir::SyncScopeKind scope)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines some OpenACC-specific enums and functions.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines an enumeration for C++ overloaded operators.
Enumerates target-specific builtins in their own namespaces within namespace clang.
C Language Family Type Representation.
This represents 'pragma omp atomic' directive.
This represents 'pragma omp barrier' directive.
This represents 'pragma omp cancel' directive.
This represents 'pragma omp cancellation point' directive.
This represents 'pragma omp critical' directive.
This represents 'pragma omp depobj' directive.
This represents 'pragma omp dispatch' directive.
This represents 'pragma omp distribute' directive.
This represents 'pragma omp distribute parallel for' composite directive.
This represents 'pragma omp distribute parallel for simd' composite directive.
This represents 'pragma omp distribute simd' composite directive.
This represents 'pragma omp error' directive.
Represents the 'pragma omp flatten' loop transformation directive.
This represents 'pragma omp flush' directive.
This represents 'pragma omp for' directive.
This represents 'pragma omp for simd' directive.
Represents the 'pragma omp fuse' loop transformation directive.
This represents 'pragma omp loop' directive.
Represents the 'pragma omp interchange' loop transformation directive.
This represents 'pragma omp interop' directive.
This represents 'pragma omp masked' directive.
This represents 'pragma omp masked taskloop' directive.
This represents 'pragma omp masked taskloop simd' directive.
This represents 'pragma omp master' directive.
This represents 'pragma omp master taskloop' directive.
This represents 'pragma omp master taskloop simd' directive.
This represents 'pragma omp metadirective' directive.
This represents block-associated 'pragma omp ordered' directive.
This represents standalone 'pragma omp ordered' directive.
This represents 'pragma omp parallel for' directive.
This represents 'pragma omp parallel for simd' directive.
This represents 'pragma omp parallel loop' directive.
This represents 'pragma omp parallel masked' directive.
This represents 'pragma omp parallel masked taskloop' directive.
This represents 'pragma omp parallel masked taskloop simd' directive.
This represents 'pragma omp parallel master' directive.
This represents 'pragma omp parallel master taskloop' directive.
This represents 'pragma omp parallel master taskloop simd' directive.
This represents 'pragma omp parallel sections' directive.
Represents the 'pragma omp reverse' loop transformation directive.
This represents 'pragma omp scan' directive.
This represents 'pragma omp scope' directive.
This represents 'pragma omp section' directive.
This represents 'pragma omp sections' directive.
This represents 'pragma omp simd' directive.
This represents 'pragma omp single' directive.
Represents the 'pragma omp split' loop transformation directive.
This represents the 'pragma omp stripe' loop transformation directive.
This represents 'pragma omp target data' directive.
This represents 'pragma omp target' directive.
This represents 'pragma omp target enter data' directive.
This represents 'pragma omp target exit data' directive.
This represents 'pragma omp target loop' directive.
This represents 'pragma omp target parallel' directive.
This represents 'pragma omp target parallel for' directive.
This represents 'pragma omp target parallel for simd' directive.
This represents 'pragma omp target parallel loop' directive.
This represents 'pragma omp target simd' directive.
This represents 'pragma omp target teams' directive.
This represents 'pragma omp target teams distribute' combined directive.
This represents 'pragma omp target teams distribute parallel for' combined directive.
This represents 'pragma omp target teams distribute parallel for simd' combined directive.
This represents 'pragma omp target teams distribute simd' combined directive.
This represents 'pragma omp target teams loop' directive.
This represents 'pragma omp target update' directive.
This represents 'pragma omp task' directive.
This represents 'pragma omp taskloop' directive.
This represents 'pragma omp taskloop simd' directive.
This represents 'pragma omp taskgroup' directive.
This represents 'pragma omp taskwait' directive.
This represents 'pragma omp taskyield' directive.
This represents 'pragma omp teams' directive.
This represents 'pragma omp teams distribute' directive.
This represents 'pragma omp teams distribute parallel for' composite directive.
This represents 'pragma omp teams distribute parallel for simd' composite directive.
This represents 'pragma omp teams distribute simd' combined directive.
This represents 'pragma omp teams loop' directive.
This represents the 'pragma omp tile' loop transformation directive.
This represents the 'pragma omp unroll' loop transformation directive.
This class represents a 'loop' construct. The 'loop' construct applies to a 'for' loop (or range-for ...
cir::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4422
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
Definition Stmt.h:3290
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:7014
Defines the interface for sync scope model.
Definition SyncScope.h:105
Represents an attribute applied to a statement.
Definition Stmt.h:2214
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4522
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4560
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4557
BreakStmt - This represents a break.
Definition Stmt.h:3148
mlir::Value getPointer() const
Definition Address.h:98
static Address invalid()
Definition Address.h:76
clang::CharUnits getAlignment() const
Definition Address.h:138
mlir::Value getBasePointer() const
Definition Address.h:103
An aggregate value slot.
static AggValueSlot forAddr(Address addr, clang::Qualifiers quals, IsDestructed_t isDestructed, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed)
static AggValueSlot ignored()
Returns an aggregate value slot indicating that the aggregate value is being ignored.
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false, bool isNontemporal=false)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst, bool isVolatile=false, bool isNontemporal=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
An abstract representation of regular/ObjC call/message targets.
AbstractCallee(const clang::FunctionDecl *fd)
const clang::ParmVarDecl * getParamDecl(unsigned I) const
ArrayInitLoopExprScope(CIRGenFunction &cgf, bool setIdx, mlir::Value index)
CIRGenFPOptionsRAII(CIRGenFunction &cgf, FPOptions FPFeatures)
CXXDefaultInitExprScope(CIRGenFunction &cgf, const CXXDefaultInitExpr *e)
Captures cleanups for variables whose lifetime ends in a region owned by an enclosing op rather than ...
CapturedCleanups(CIRGenFunction &cgf, bool active)
void emitAsNestedScopes(mlir::Location loc)
Emit the captured cleanups at the current insertion point as nested cir.cleanup.scope operations,...
void emitIntoCleanupRegion(mlir::Location loc)
Emit the captured cleanups into the current insertion point, which must be inside the owning op's cle...
An object to manage conditionally-evaluated expressions.
void advanceInsertPoint(mlir::Operation *op)
Records op as the last operation emitted at the pre-conditional insertion point, so that a later emis...
mlir::OpBuilder::InsertPoint getInsertPoint() const
Returns the insertion point which will be executed prior to each evaluation of the conditional code.
ConditionalEvaluation(CIRGenFunction &cgf, mlir::Location loc)
loc is the location of the conditional expression.
static ConstantEmission forReference(mlir::TypedAttr c)
static ConstantEmission forValue(mlir::TypedAttr c)
LValue getReferenceLValue(CIRGenFunction &cgf, const Expr *refExpr) const
DeclMapRevertingRAII(CIRGenFunction &cgf, const VarDecl *vd)
FieldConstructionScope(CIRGenFunction &cgf, Address thisAddr)
FullExprCleanupScope(CIRGenFunction &cgf, const Stmt *s)
s is the AST root for one cleanup boundary: a full-expression, an asm statement, or the construction ...
void exit(ArrayRef< mlir::Value * > valuesToReload={})
A non-RAII class containing all the information about a bound opaque value.
static OpaqueValueMappingData bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const LValue &lv)
static OpaqueValueMappingData bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const RValue &rv)
static OpaqueValueMappingData bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const Expr *e)
OpaqueValueMapping(CIRGenFunction &cgf, const OpaqueValueExpr *opaqueValue, RValue rvalue)
OpaqueValueMapping(CIRGenFunction &cgf, const OpaqueValueExpr *opaqueValue, LValue lvalue)
OpaqueValueMapping(CIRGenFunction &cgf, const AbstractConditionalOperator *op)
Build the opaque value mapping for the given conditional operator if it's the GNU ?
OpaqueValueMapping(CIRGenFunction &cgf, const OpaqueValueExpr *ov)
Build the opaque value mapping for an OpaqueValueExpr whose source expression is set to the expressio...
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
RunCleanupsScope(CIRGenFunction &cgf)
Enter a new cleanup scope.
void deferLifetimeExtendedCleanups()
Leave the cleanups of lifetime-extended temporaries created in this scope to the enclosing scope inst...
void forceLifetimeExtendedCleanups()
Promote any pending lifetime-extended cleanup entries onto the EH scope stack at the current insertio...
void forceCleanup(ArrayRef< mlir::Value * > valuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
void forceCleanupExceptLifetimeExtended()
Force the emission of EH cleanups now, but defer promoting any lifetime-extended cleanup entries onto...
bool hasPendingCleanups() const
Whether there are any pending cleanups that have been pushed since this scope was entered.
~RunCleanupsScope()
Exit this cleanup scope, emitting any accumulated cleanups.
void restore()
Can be used to restore the state early, before the dtor is run.
SourceLocRAIIObject(CIRGenFunction &cgf, SourceRange value)
static bool isConstructorDelegationValid(const clang::CXXConstructorDecl *ctor)
Checks whether the given constructor is a valid subject for the complete-to-base constructor delegati...
static bool hasScalarEvaluationKind(clang::QualType type)
void emitFunctionProlog(const FunctionArgList &args, mlir::Block *entryBB, const FunctionDecl *fd, SourceLocation bodyBeginLoc)
Emit the function prologue: initialize the return value of an implicit-return-zero function and decla...
void emitOpenACCRoutine(const OpenACCRoutineDecl &d)
void emitLambdaDelegatingInvokeBody(const CXXMethodDecl *md)
mlir::Value emitComplexToScalarConversion(mlir::Value src, QualType srcTy, QualType dstTy, SourceLocation loc)
Emit a conversion from the specified complex type to the specified destination type,...
mlir::Type convertType(clang::QualType t)
cir::GlobalOp addInitializerToStaticVarDecl(const VarDecl &d, cir::GlobalOp gv, cir::GetGlobalOp gvAddr)
Add the initializer for 'd' to the global variable that has already been created for it.
LValue emitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *e)
mlir::Value emitCheckedArgForAssume(const Expr *e)
Emits an argument for a call to a __builtin_assume.
LValue emitOpaqueValueLValue(const OpaqueValueExpr *e)
static cir::TypeEvaluationKind getEvaluationKind(clang::QualType type)
Return the cir::TypeEvaluationKind of QualType type.
clang::GlobalDecl curGD
The GlobalDecl for the current function being compiled or the global variable currently being initial...
clang::CurrentSourceLocExprScope::SourceLocExprScopeGuard SourceLocExprScopeGuard
RValue convertTempToRValue(Address addr, clang::QualType type, clang::SourceLocation loc)
Given the address of a temporary variable, produce an r-value of its type.
mlir::LogicalResult emitCoreturnStmt(const CoreturnStmt &s)
mlir::LogicalResult emitOpenACCDataConstruct(const OpenACCDataConstruct &s)
AutoVarEmission emitAutoVarAlloca(const clang::VarDecl &d, mlir::OpBuilder::InsertPoint ip={})
mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType)
void emitAutoVarTypeCleanup(const AutoVarEmission &emission, clang::QualType::DestructionKind dtorKind)
Enter a destroy cleanup for the given local variable.
ImplicitParamDecl * cxxabiThisDecl
CXXThisDecl - When generating code for a C++ member function, this will hold the implicit 'this' decl...
EHScopeStack::stable_iterator prologueCleanupDepth
The cleanup depth enclosing all the cleanups associated with the parameters.
mlir::LogicalResult emitOpenACCCombinedConstruct(const OpenACCCombinedConstruct &s)
Address emitCXXMemberDataPointerAddress(const Expr *e, Address base, mlir::Value memberPtr, const MemberPointerType *memberPtrType, LValueBaseInfo *baseInfo)
bool curFuncIsThunk
In C++, whether we are code generating a thunk.
mlir::LogicalResult emitOpenACCWaitConstruct(const OpenACCWaitConstruct &s)
cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn, cir::FuncType funcType)
llvm::SmallVector< PendingCleanupEntry > lifetimeExtendedCleanupStack
ConditionalEvaluation * hiddenOutermostConditional
Address emitFieldAnnotations(const clang::FieldDecl *field, Address addr)
Annotate the address of field; accesses must use the result.
CIRGenTypes & getTypes() const
Address emitPointerWithAlignment(const clang::Expr *expr, LValueBaseInfo *baseInfo=nullptr)
Given an expression with a pointer type, emit the value and compute our best estimate of the alignmen...
llvm::ScopedHashTable< const clang::Decl *, mlir::Value > SymTableTy
The symbol table maps a variable name to a value in the current scope.
void initFullExprCleanup()
Set up the last cleanup that was pushed as a conditional full-expression cleanup.
void emitInvariantStart(CharUnits size, mlir::Value addr, mlir::Location loc)
Definition CIRGenCXX.cpp:33
void emitVariablyModifiedType(QualType ty)
RValue emitLoadOfLValue(LValue lv, SourceLocation loc)
Given an expression that represents a value lvalue, this method emits the address of the lvalue,...
const clang::LangOptions & getLangOpts() const
void emitCapturedCleanups(EHScopeStack::stable_iterator depth, mlir::Location loc)
Emit the captured cleanups (those pushed above depth while EHScopeStack was capturing cleanups) at th...
void emitTrap(mlir::Location loc, bool createNewBlock)
Emit a trap instruction, which is used to abort the program in an abnormal way, usually for debugging...
void emitForwardingCallToLambda(const CXXMethodDecl *lambdaCallOperator, CallArgList &callArgs)
mlir::Block * getCurFunctionEntryBlock()
RValue emitCXXMemberCallExpr(const clang::CXXMemberCallExpr *e, ReturnValueSlot returnValue)
mlir::LogicalResult emitOpenACCUpdateConstruct(const OpenACCUpdateConstruct &s)
RValue emitCXXMemberPointerCallExpr(const CXXMemberCallExpr *ce, ReturnValueSlot returnValue)
mlir::Value emitX86CpuIs(const CallExpr *expr)
LValue emitLValueForBitField(LValue base, const FieldDecl *field)
mlir::LogicalResult emitIfOnBoolExpr(const clang::Expr *cond, const clang::Stmt *thenS, const clang::Stmt *elseS)
Emit an if on a boolean condition to the specified blocks.
VlaSizePair getVLASize(const VariableArrayType *type)
Returns an MLIR::Value+QualType pair that corresponds to the size, in non-variably-sized elements,...
LValue emitScalarCompoundAssignWithComplex(const CompoundAssignOperator *e, mlir::Value &result)
cir::CoroAllocOp emitCoroAllocBuiltinCall(const CallExpr *e)
Address cxxDefaultInitExprThis
The value of 'this' to sue when evaluating CXXDefaultInitExprs within this expression.
cir::IfOp emitIfOnBoolValue(mlir::Value condV, mlir::Location loc, BuilderCallbackRef thenBuilder, mlir::Location thenLoc, BuilderCallbackRef elseBuilder, std::optional< mlir::Location > elseLoc={})
Build the cir.if for an already-emitted condition value.
void emitStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage)
mlir::Value emitComplexExpr(const Expr *e)
Emit the computation of the specified expression of complex type, returning the result.
void setBeforeOutermostConditional(mlir::Value value, Address addr)
mlir::LogicalResult emitOpenACCCacheConstruct(const OpenACCCacheConstruct &s)
mlir::Value loadCXXThis()
Load the value for 'this'.
LValue makeNaturalAlignPointeeAddrLValue(mlir::Value v, clang::QualType t)
Given a value of type T* that may not be to a complete object, construct an l-vlaue withi the natural...
RValue emitCallExpr(const clang::CallExpr *e, ReturnValueSlot returnValue=ReturnValueSlot())
void emitDeleteCall(const FunctionDecl *deleteFD, mlir::Value ptr, QualType deleteTy)
LValue emitMemberExpr(const MemberExpr *e)
const TargetInfo & getTarget() const
void replaceAddrOfLocalVar(const clang::VarDecl *vd, Address addr)
llvm::DenseMap< const clang::Decl *, Address > DeclMapTy
LValue emitConditionalOperatorLValue(const AbstractConditionalOperator *expr)
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
void addCatchHandlerAttr(const CXXCatchStmt *catchStmt, SmallVector< mlir::Attribute > &handlerAttrs)
Address makeNaturalAddressForPointer(mlir::Value ptr, QualType t, CharUnits alignment, bool forPointeeType=false, LValueBaseInfo *baseInfo=nullptr)
Construct an address with the natural alignment of T.
const clang::Decl * curFuncDecl
mlir::LogicalResult emitCXXForRangeStmt(const CXXForRangeStmt &s, llvm::ArrayRef< const Attr * > attrs)
cir::CoroNoopOp emitCoroNoopBuiltinCall(const CallExpr *e)
bool insertionPointIsReachable() const
True if code emitted at the builder's insertion point can be reached.
LValue emitLValueForLambdaField(const FieldDecl *field)
mlir::Value evaluateExprAsBool(const clang::Expr *e)
Perform the usual unary conversions on the specified expression and compare the result against zero,...
bool isTrivialInitializer(const Expr *init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
void emitOpenACCDeclare(const OpenACCDeclareDecl &d)
void emitInlinedInheritingCXXConstructorCall(SourceLocation loc, const CXXConstructorDecl *d, CXXCtorType ctorType, bool forVirtualBase, bool delegating, CallArgList &args)
Address getAddrOfLocalVar(const clang::VarDecl *vd)
Return the address of a local variable.
void emitAnyExprToExn(const Expr *e, Address addr)
void emitAggregateCopy(LValue dest, LValue src, QualType eltTy, AggValueSlot::Overlap_t mayOverlap, bool isVolatile=false)
Emit an aggregate copy.
cir::CoroSuspendOp emitCoroSuspendBuiltinCall(const CallExpr *e)
void emitCapturedCleanupsAsScopes(EHScopeStack::stable_iterator depth, mlir::Location loc)
Like emitCapturedCleanups, but push the captured cleanups again as ordinary cleanups,...
LValue makeNaturalAlignAddrLValue(mlir::Value val, QualType ty)
llvm::DenseMap< const Expr *, mlir::Value > vlaSizeMap
bool constantFoldsToSimpleInteger(const clang::Expr *cond, llvm::APSInt &resultInt, bool allowLabels=false)
If the specified expression does not fold to a constant, or if it does fold but contains a label,...
void emitMustTailThunk(GlobalDecl gd, mlir::Value adjustedThisPtr, cir::FuncOp callee)
Emit a musttail call for a thunk with a potentially different ABI.
mlir::LogicalResult emitForStmt(const clang::ForStmt &s, llvm::ArrayRef< const Attr * > attrs={})
void pushIrregularPartialArrayCleanup(mlir::Value arrayBegin, Address arrayEndPointer, QualType elementType, CharUnits elementAlign, Destroyer *destroyer)
Push an EH cleanup to destroy already-constructed elements of the given array.
void emitLifetimeEndOp(mlir::Location loc, mlir::Value addr)
Address getAsNaturalAddressOf(Address addr, QualType pointeeTy)
void pushCleanupAndDeferDeactivation(CleanupKind kind, As... a)
Push a cleanup and record it for deferred deactivation.
cir::TryOp ehSpecTryOp
The cir.try wrapping a function whose exception specification has to be enforced.
LValue emitComplexCompoundAssignmentLValue(const CompoundAssignOperator *e)
void emitBeginCatch(const CXXCatchStmt *catchStmt, mlir::Value ehToken)
Begins a catch statement by initializing the catch variable and calling __cxa_begin_catch.
mlir::Value getVTTParameter(GlobalDecl gd, bool forVirtualBase, bool delegating)
Return the VTT parameter that should be passed to a base constructor/destructor with virtual bases.
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
void initializeVTablePointers(mlir::Location loc, const clang::CXXRecordDecl *rd)
mlir::Type convertType(const TypeDecl *t)
bool constantFoldsToBool(const clang::Expr *cond, bool &resultBool, bool allowLabels=false)
If the specified expression does not fold to a constant, or if it does but contains a label,...
void emitVarAnnotations(const clang::VarDecl *d, mlir::Value addr)
Annotate the storage of d at addr.
mlir::Value emitOpOnBoolExpr(mlir::Location loc, const clang::Expr *cond)
TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
void emitStoreThroughExtVectorComponentLValue(RValue src, LValue dst)
CodeGenUtils::EvaluationOrder EvaluationOrder
void initializeVTablePointer(mlir::Location loc, const VPtr &vptr)
void emitCallArgs(CallArgList &args, PrototypeWrapper prototype, llvm::iterator_range< clang::CallExpr::const_arg_iterator > argRange, AbstractCallee callee=AbstractCallee(), unsigned paramsToSkip=0, EvaluationOrder order=EvaluationOrder::Default)
Address getAddressOfBaseClass(Address value, const CXXRecordDecl *derived, llvm::iterator_range< CastExpr::path_const_iterator > path, bool nullCheckValue, SourceLocation loc)
void emitAggregateStore(mlir::Value value, Address dest)
mlir::LogicalResult emitDoStmt(const clang::DoStmt &s, llvm::ArrayRef< const Attr * > attrs={})
mlir::LogicalResult emitReturnStmt(const clang::ReturnStmt &s)
LValue emitLoadOfReferenceLValue(Address refAddr, mlir::Location loc, QualType refTy, AlignmentSource source)
cir::CoroBeginOp emitCoroBeginBuiltinCall(const CallExpr *e)
void emitDelegateCXXConstructorCall(const clang::CXXConstructorDecl *ctor, clang::CXXCtorType ctorType, const FunctionArgList &args, clang::SourceLocation loc)
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
ConditionalEvaluation * outermostConditional
mlir::LogicalResult emitOpenACCInitConstruct(const OpenACCInitConstruct &s)
void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals, bool isInitializer)
Emits the code necessary to evaluate an arbitrary expression into the given memory location.
RValue emitCXXMemberOrOperatorCall(const clang::CXXMethodDecl *md, const CIRGenCallee &callee, ReturnValueSlot returnValue, mlir::Value thisPtr, mlir::Value implicitParam, clang::QualType implicitParamTy, const clang::CallExpr *ce, CallArgList *rtlArgs)
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
void emitBaseInitializer(mlir::Location loc, const CXXRecordDecl *classDecl, CXXCtorInitializer *baseInit)
RValue emitAtomicExpr(AtomicExpr *e)
void emitExprAsInit(const clang::Expr *init, const clang::ValueDecl *d, LValue lvalue, bool capturedByInit=false)
Emit an expression as an initializer for an object (variable, field, etc.) at the given location.
void emitCXXGuardedInit(const VarDecl &varDecl, cir::GlobalOp globalOp, bool performInit)
Emit a guarded initializer for a static local variable.
void emitLoopConditionVariable(const clang::VarDecl &d, CapturedCleanups &condCleanup, llvm::ArrayRef< QualType > extendedTemporaries)
Emit a loop's condition-variable declaration.
static bool resumeExprDefersCleanups(const CoroutineSuspendExpr &s)
Whether the resume expression of s contains a construct that defers cleanups to the end of the enclos...
mlir::Value emitArrayLength(const clang::ArrayType *arrayType, QualType &baseType, Address &addr)
Computes the length of an array in elements, as well as the base element type and a properly-typed fi...
void emitNullInitialization(mlir::Location loc, Address destPtr, QualType ty)
mlir::LogicalResult emitOpenACCSetConstruct(const OpenACCSetConstruct &s)
mlir::Value performAddrSpaceCast(mlir::Value v, mlir::Type destTy) const
RValue emitReferenceBindingToExpr(const Expr *e)
Emits a reference binding to the passed in expression.
llvm::SmallVector< DeferredDeactivateCleanup > deferredDeactivationCleanupStack
VPtrsVector getVTablePointers(const clang::CXXRecordDecl *vtableClass)
const TargetCIRGenInfo & getTargetHooks() const
mlir::LogicalResult emitSwitchStmt(const clang::SwitchStmt &s)
RValue emitCoyieldExpr(const CoyieldExpr &e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
cir::CoroFreeOp emitCoroFreeBuiltin(const CallExpr *e)
mlir::Value evaluateOrEmitBuiltinObjectSize(const clang::Expr *e, unsigned type, cir::IntType resType, mlir::Value emittedE, bool isDynamic)
void emitLambdaVLACapture(const VariableArrayType *vat, LValue lv)
mlir::Value emitX86CpuInit(mlir::Location loc)
std::optional< mlir::Value > emitRISCVBuiltinExpr(unsigned builtinID, const CallExpr *expr)
void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind, Address addr, QualType type)
mlir::LogicalResult emitWhileStmt(const clang::WhileStmt &s, llvm::ArrayRef< const Attr * > attrs={})
mlir::LogicalResult emitCaseStmt(const clang::CaseStmt &s, mlir::Type condType, bool buildingTopLevelCase)
LValue emitArraySubscriptExpr(const clang::ArraySubscriptExpr *e)
void emitScalarInit(const clang::Expr *init, LValue lvalue, bool capturedByInit=false)
llvm::ScopedHashTableScope< const clang::Decl *, mlir::Value > SymTableScopeTy
OpenACCDataOperandInfo getOpenACCDataOperandInfo(const Expr *e)
CleanupKind getCleanupKind(QualType::DestructionKind kind)
clang::CharUnits cxxabiThisAlignment
void checkTargetFeatures(const clang::CallExpr *e, const clang::FunctionDecl *targetDecl)
Emit a diagnostic if the target features required by targetDecl are not available in the calling func...
mlir::Value emitX86CpuSupports(const CallExpr *expr)
mlir::Value emitBuiltinObjectSize(const clang::Expr *e, unsigned type, cir::IntType resType, mlir::Value emittedE, bool isDynamic)
Returns a Value corresponding to the size of the given expression by emitting a cir....
LValue emitCoawaitLValue(const CoawaitExpr *e)
mlir::Value makeBinaryAtomicValue(cir::AtomicFetchKind kind, const clang::CallExpr *expr, mlir::Type *originalArgType=nullptr, mlir::Value *emittedArgValue=nullptr, cir::MemOrder ordering=cir::MemOrder::SequentiallyConsistent)
Utility to insert an atomic instruction based on Intrinsic::ID and the expression node.
RValue emitCUDAKernelCallExpr(const CUDAKernelCallExpr *expr, ReturnValueSlot returnValue)
AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *fd)
mlir::LogicalResult emitSimpleStmt(const clang::Stmt *s, bool useCurrentScope)
mlir::Operation * curFn
The current function or global initializer that is generated code for.
mlir::LogicalResult emitAsmStmt(const clang::AsmStmt &s)
std::pair< mlir::Value, mlir::Type > emitAsmInputLValue(const TargetInfo::ConstraintInfo &info, LValue inputValue, QualType inputType, std::string &constraintString, SourceLocation loc)
Address emitExtVectorElementLValue(LValue lv, mlir::Location loc)
Generates lvalue for partial ext_vector access.
mlir::Value emitScalarConversion(mlir::Value src, clang::QualType srcType, clang::QualType dstType, clang::SourceLocation loc)
Emit a conversion from the specified type to the specified destination type, both of which are CIR sc...
Address getAddressOfDerivedClass(mlir::Location loc, Address baseAddr, const CXXRecordDecl *derived, llvm::iterator_range< CastExpr::path_const_iterator > path, bool nullCheckValue)
std::optional< mlir::Value > emitTargetBuiltinExpr(unsigned builtinID, const clang::CallExpr *e, ReturnValueSlot &returnValue)
CallArgList cxxInheritedCtorInitExprArgs
The values of function arguments to use when evaluating CXXInheritedCtorInitExprs within this context...
mlir::Value emitPromotedComplexExpr(const Expr *e, QualType promotionType)
ImplicitParamDecl * cxxStructorImplicitParamDecl
When generating code for a constructor or destructor, this will hold the implicit argument (e....
mlir::LogicalResult emitOpenACCComputeConstruct(const OpenACCComputeConstruct &s)
EHScopeStack ehStack
Tracks function scope overall cleanup handling.
void enterDtorCleanups(const CXXDestructorDecl *dtor, CXXDtorType type)
Enter the cleanups necessary to complete the given phase of destruction for a destructor.
llvm::SmallVector< const ParmVarDecl * > fnArgs
Save Parameter Decl for coroutine.
mlir::Value emitUnPromotedValue(mlir::Value result, QualType unPromotionType)
mlir::LogicalResult emitSwitchBody(const clang::Stmt *s)
void startThunk(cir::FuncOp fn, GlobalDecl gd, const CIRGenFunctionInfo &fnInfo, bool isUnprototyped)
Start generating a thunk function.
RValue emitAtomicLoad(LValue lvalue, SourceLocation loc, AggValueSlot slot=AggValueSlot::ignored())
AggValueSlot createAggTemp(QualType ty, mlir::Location loc, const Twine &name="tmp", Address *alloca=nullptr)
Create a temporary memory object for the given aggregate type.
mlir::Value emitDevicePrintfCallExpr(const CallExpr *expr)
Emit a device-side printf call for GPU targets.
llvm::SmallVector< PendingCleanupEntry > deferredConditionalCleanupStack
Cleanups for temporaries constructed inside a conditional.
llvm::SmallVector< ConditionalCleanupScope > conditionalCleanupScopes
void emitNewArrayInitializer(const CXXNewExpr *e, QualType elementType, mlir::Type elementTy, Address beginPtr, mlir::Value numElements, mlir::Value allocSizeWithoutCookie)
std::optional< mlir::Value > fnRetAlloca
The compiler-generated variable that holds the return value.
void emitImplicitAssignmentOperatorBody(FunctionArgList &args)
clang::SanitizerSet sanOpts
Sanitizers enabled for this function.
static int64_t getZExtIntValueFromConstOp(mlir::Value val)
Get zero-extended integer from a mlir::Value that is an int constant or a constant op.
cir::FastMathFlagsAttr getFastMathFlagsAttr(cir::FastMathFlags fastMathFlags)
Create a CIR fast-math attribute from the specified flags.
RValue emitLoadOfExtVectorElementLValue(LValue lv)
mlir::Value emitCXXTypeidExpr(const CXXTypeidExpr *e)
mlir::Type convertTypeForMem(QualType t)
clang::QualType buildFunctionArgList(clang::GlobalDecl gd, FunctionArgList &args)
void emitCtorPrologue(const clang::CXXConstructorDecl *ctor, clang::CXXCtorType ctorType, FunctionArgList &args)
This routine generates necessary code to initialize base classes and non-static data members belongin...
mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty, mlir::Location loc, clang::CharUnits alignment, bool insertIntoFnEntryBlock, mlir::Value arraySize=nullptr)
mlir::Value emitComplexPrePostIncDec(const UnaryOperator *e, LValue lv)
void emitUnreachable(clang::SourceLocation loc, bool createNewBlock)
Emit a reached-unreachable diagnostic if loc is valid and runtime checking is enabled.
mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s, cxxTryBodyEmitter &bodyCallback, bool isFnTryBlock=false)
mlir::Value createDummyValue(mlir::Location loc, clang::QualType qt)
mlir::LogicalResult emitAttributedStmt(const AttributedStmt &s)
cir::FastMathFlags getCurrentFastMathFlags() const
Convert the active Clang floating-point options to CIR fast-math flags.
void emitCXXConstructExpr(const clang::CXXConstructExpr *e, AggValueSlot dest)
mlir::Value emitLoadOfComplex(LValue src, SourceLocation loc)
Load a complex number from the specified l-value.
cir::CoroPromiseOp emitCoroPromiseBuiltinCall(const CallExpr *e)
CodeGenUtils::MSVCIntrin MSVCIntrin
LValue emitAggExprToLValue(const Expr *e)
void emitStoreOfScalar(mlir::Value value, Address addr, bool isVolatile, clang::QualType ty, LValueBaseInfo baseInfo, bool isInit=false, bool isNontemporal=false)
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Push the standard destructor for the given type as at least a normal cleanup.
clang::CurrentSourceLocExprScope curSourceLocExprScope
Source location information about the default argument or member initializer expression we're evaluat...
mlir::Value loadCXXVTT()
Load the VTT parameter to base constructors/destructors have virtual bases.
void emitVarDecl(const clang::VarDecl &d)
This method handles emission of any variable declaration inside a function, including static vars etc...
LValue emitCompoundAssignmentLValue(const clang::CompoundAssignOperator *e)
mlir::Value emitSVEPredicateCast(mlir::Value pred, unsigned minNumElts, mlir::Location loc)
mlir::Value emitCXXNewExpr(const CXXNewExpr *e)
RValue getUndefRValue(clang::QualType ty)
Get an appropriate 'undef' rvalue for the given type.
bool getAArch64SVEProcessedOperands(unsigned builtinID, const CallExpr *expr, SmallVectorImpl< mlir::Value > &ops, clang::SVETypeFlags typeFlags)
Address returnValue
The temporary alloca to hold the return value.
LValue makeAddrLValue(Address addr, QualType ty, LValueBaseInfo baseInfo)
static int64_t getSExtIntValueFromConstOp(mlir::Value val)
Get integer from a mlir::Value that is an int constant or a constant op.
mlir::Value getArrayInitIndex()
Get the index of the current ArrayInitLoopExpr, if any.
std::optional< mlir::Value > emitX86BuiltinExpr(unsigned builtinID, const CallExpr *expr)
mlir::LogicalResult emitLabel(const clang::LabelDecl &d)
void emitCXXConstructorCall(const clang::CXXConstructorDecl *d, clang::CXXCtorType type, bool forVirtualBase, bool delegating, AggValueSlot thisAVS, const clang::CXXConstructExpr *e)
static bool hasAggregateEvaluationKind(clang::QualType type)
mlir::Value getVTablePtr(mlir::Location loc, Address thisAddr, const clang::CXXRecordDecl *vtableClass)
Return the Value of the vtable pointer member pointed to by thisAddr.
void emitArrayDestroy(mlir::Value begin, mlir::Value numElements, QualType elementType, CharUnits elementAlign, Destroyer *destroyer)
Destroys all the elements of the given array, beginning from last to first.
LValue emitPointerToDataMemberBinaryExpr(const BinaryOperator *e)
RValue emitAnyExprToTemp(const clang::Expr *e)
Similarly to emitAnyExpr(), however, the result will always be accessible even if no aggregate locati...
void finishFunction(SourceLocation endLoc)
mlir::LogicalResult emitOpenACCShutdownConstruct(const OpenACCShutdownConstruct &s)
mlir::LogicalResult emitFunctionBody(const clang::Stmt *body)
mlir::LogicalResult emitBreakStmt(const clang::BreakStmt &s)
void emitAutoVarDeclWithCapturedCleanups(const clang::VarDecl &d, CapturedCleanups &cleanups, bool guardDestruction=false, llvm::ArrayRef< QualType > extendedTemporaries={})
Emit d with captured cleanups.
void initFullExprCleanupWithFlag(Address activeFlag)
cir::CoroDestroyOp emitCoroDestroyBuiltinCall(const CallExpr *e)
mlir::LogicalResult emitIndirectGotoStmt(const IndirectGotoStmt &s)
void emitCallAndReturnForThunk(cir::FuncOp callee, SourceRange fnLoc, const ThunkInfo *thunk, bool isUnprototyped)
Emit the call and return for a thunk function.
void emitStoreOfComplex(mlir::Location loc, mlir::Value v, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
llvm::SmallPtrSet< const clang::CXXRecordDecl *, 4 > VisitedVirtualBasesSetTy
static bool destructorMayThrow(QualType type)
Whether destroying an object of type type, or its elements if it is an array, may throw an exception.
LValue emitUnaryOpLValue(const clang::UnaryOperator *e)
void emitReturnOfRValue(mlir::Location loc, RValue rv, QualType ty)
LValue emitMatrixSubscriptExpr(const MatrixSubscriptExpr *e)
Address createCleanupActiveFlag()
Create an active flag variable for use with conditional cleanups.
bool shouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *rd)
Returns whether we should perform a type checked load when loading a virtual function for virtual cal...
bool hasVolatileMember(QualType t)
returns true if aggregate type has a volatile member.
RValue emitLoadOfBitfieldLValue(LValue lv, SourceLocation loc)
LValue emitComplexAssignmentLValue(const BinaryOperator *e)
void emitCallArg(CallArgList &args, const clang::Expr *e, clang::QualType argType)
bool checkIfLoopMustProgress(const clang::Expr *controllingExpression, bool hasEmptyBody)
cir::CoroEndOp emitCoroEndBuiltinCall(const CallExpr *e)
clang::FieldDecl * lambdaThisCaptureField
void deactivateCleanupBlock(EHScopeStack::stable_iterator cleanup, mlir::Operation *dominatingIP)
Deactivates the given cleanup block.
cir::LoopHintAttr getLoopHints(llvm::ArrayRef< const Attr * > attrs, bool mustProgress)
Build the hints that get attached to a loop, or a null attribute if there is nothing to say about it.
mlir::LogicalResult emitContinueStmt(const clang::ContinueStmt &s)
const clang::Decl * curCodeDecl
This is the inner-most code context, which includes blocks.
mlir::Value emitX86MSVCIntrin(MSVCIntrin builtinID, const CallExpr *E)
void emitConstructorBody(FunctionArgList &args)
LValue emitLValueForFieldInitialization(LValue base, const clang::FieldDecl *field, llvm::StringRef fieldName)
Like emitLValueForField, excpet that if the Field is a reference, this will return the address of the...
mlir::Value getAsNaturalPointerTo(Address addr, QualType pointeeType)
LValue emitCallExprLValue(const clang::CallExpr *e)
bool haveInsertPoint() const
True if an insertion point is defined.
llvm::SmallVector< mlir::Type, 2 > condTypeStack
The type of the condition for the emitting switch statement.
RValue emitBuiltinWithOneOverloadedType(const CallExpr *e, llvm::StringRef intrinName, mlir::Type resultType={})
Emit a simple LLVM intrinsic that takes N scalar arguments.
void emitAutoVarInit(const AutoVarEmission &emission)
Emit the initializer for an allocated variable.
void emitInitializerForField(clang::FieldDecl *field, LValue lhs, clang::Expr *init)
void emitStopPoint(const Stmt *s)
Build a debug stoppoint if we are emitting debug info.
void emitAtomicExprWithSyncScope(const AtomicScopeModel *scopeModel, const EmittedOrderOrScope &scope, llvm::function_ref< void(cir::SyncScopeKind)> emitAtomicOp)
std::optional< mlir::Value > emitAMDGPUBuiltinExpr(unsigned builtinID, const CallExpr *expr)
Emit a call to an AMDGPU builtin function.
std::optional< mlir::Value > emitAArch64BuiltinExpr(unsigned builtinID, const CallExpr *expr, ReturnValueSlot returnValue, llvm::Triple::ArchType arch)
void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType, Address ptr)
Emits all the code to cause the given temporary to be cleaned up.
LValue emitStringLiteralLValue(const StringLiteral *e, llvm::StringRef name=".str")
void maybeEmitDeferredVarDeclInit(const VarDecl *vd)
mlir::Value getUndefConstant(mlir::Location loc, mlir::Type cirTy)
Return a CIR constant for an undefined value of cirTy.
LValue emitCoyieldLValue(const CoyieldExpr *e)
llvm::SmallDenseMap< const ParmVarDecl *, const ImplicitParamDecl * > sizeArguments
If a ParmVarDecl had the pass_object_size attribute, this will contain a mapping from said ParmVarDec...
mlir::Value loadThisForDtorDelete(const CXXDestructorDecl *dd)
Return the pointer to pass to the operator delete of the given destructor, converted to the type of i...
mlir::Value emitToMemory(mlir::Value value, clang::QualType ty)
Given a value and its clang type, returns the value casted to its memory representation.
mlir::LogicalResult emitOpenACCHostDataConstruct(const OpenACCHostDataConstruct &s)
std::optional< mlir::Value > emitAArch64SMEBuiltinExpr(unsigned builtinID, const CallExpr *expr)
LValue emitLValueForField(LValue base, const clang::FieldDecl *field)
const LifetimeExtensionCapture * lifetimeExtensionCapture
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
void emitAtomicExprWithMemOrder(const EmittedOrderOrScope &order, bool isStore, bool isLoad, bool isFence, llvm::function_ref< void(cir::MemOrder)> emitAtomicOp)
void pushStackRestore(CleanupKind kind, Address spMem)
LValue emitPseudoObjectLValue(const PseudoObjectExpr *E)
mlir::LogicalResult emitIfStmt(const clang::IfStmt &s)
void emitAutoVarDecl(const clang::VarDecl &d)
Emit code and set up symbol table for a variable declaration with auto, register, or no storage class...
cir::GetGlobalOp createGetCpuModel(mlir::Location loc)
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const clang::ValueDecl *extendingDecl)
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.
mlir::Value emitPromotedScalarExpr(const Expr *e, QualType promotionType)
AggValueSlot::Overlap_t getOverlapForReturnValue()
Determine whether a return value slot may overlap some other object.
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
mlir::LogicalResult emitSwitchCase(const clang::SwitchCase &s, bool buildingTopLevelCase)
Address emitLoadOfReference(LValue refLVal, mlir::Location loc, LValueBaseInfo *pointeeBaseInfo)
Address getAddressOfDirectBaseInCompleteClass(mlir::Location loc, Address value, const CXXRecordDecl *derived, const CXXRecordDecl *base, bool baseIsVirtual)
Convert the given pointer to a complete class to the given direct base.
bool shouldNullCheckClassCastValue(const CastExpr *ce)
mlir::Value emitAtomicCmpXchg(const clang::CallExpr *expr, bool returnBool, cir::MemOrder successOrder=cir::MemOrder::SequentiallyConsistent, cir::MemOrder failureOrder=cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind scope=cir::SyncScopeKind::System)
Emit cir.atomic.cmpxchg.
CIRGenBuilderTy & getBuilder()
cir::VectorType getSVEType(const SVETypeFlags &typeFlags)
bool didCallStackSave
Whether a cir.stacksave operation has been added.
void emitDecl(const clang::Decl &d, bool evaluateConditionDecl=false)
LValue emitBinaryOperatorLValue(const BinaryOperator *e)
mlir::Value emitOpenACCIntExpr(const Expr *intExpr)
Address getAddrOfBitFieldStorage(LValue base, const clang::FieldDecl *field, mlir::Type fieldType, unsigned index)
AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *rd, const CXXRecordDecl *baseRD, bool isVirtual)
Determine whether a base class initialization may overlap some other object.
cir::FuncType getIntrinsicType(llvm::Intrinsic::ID id, llvm::ArrayRef< mlir::Type > overloadTys={})
Return the CIR signature of the LLVM intrinsic id, resolving its overloaded types to overloadTys.
void emitDestroy(Address addr, QualType type, Destroyer *destroyer)
Immediately perform the destruction of the given object.
void emitNonNullArgCheck(RValue rv, QualType argType, SourceLocation argLoc, AbstractCallee ac, unsigned paramNum)
Create a check for a function parameter that may potentially be declared as non-null.
void pushPendingCleanupToEHStack(const PendingCleanupEntry &entry)
Promote a single pending cleanup entry onto the EH scope stack.
const CIRGenModule & getCIRGenModule() const
void startFunction(clang::GlobalDecl gd, clang::QualType returnType, cir::FuncOp fn, cir::FuncType funcType, FunctionArgList args, clang::SourceLocation loc, clang::SourceLocation startLoc)
Emit code for the start of a function.
llvm::DenseMap< const VarDecl *, mlir::Value > nrvoFlags
A mapping from NRVO variables to the flags used to indicate when the NRVO has been applied to this va...
unsigned counterRefTmp
Hold counters for incrementally naming temporaries.
mlir::MLIRContext & getMLIRContext()
mlir::LogicalResult emitOpenACCEnterDataConstruct(const OpenACCEnterDataConstruct &s)
RValue emitCall(const CIRGenFunctionInfo &funcInfo, const CIRGenCallee &callee, ReturnValueSlot returnValue, const CallArgList &args, bool isMustTail, cir::CIRCallOpInterface *callOrTryCall=nullptr)
Destroyer * getDestroyer(clang::QualType::DestructionKind kind)
mlir::Value emitRuntimeCall(mlir::Location loc, cir::FuncOp callee, llvm::ArrayRef< mlir::Value > args={}, mlir::NamedAttrList attrs={})
void Destroyer(CIRGenFunction &cgf, Address addr, QualType ty)
void emitDestructorBody(FunctionArgList &args)
Emits the body of the current destructor.
LValue emitInitListLValue(const InitListExpr *e)
mlir::Value arrayInitIndex
The current array initialization index when evaluating an ArrayInitIndexExpr within an ArrayInitLoopE...
void emitAtomicInit(Expr *init, LValue dest)
void popCleanupBlock(bool forDeactivation=false)
Pop a cleanup block from the stack.
std::optional< SourceRange > currSrcLoc
Use to track source locations across nested visitor traversals.
LValue emitCastLValue(const CastExpr *e)
Casts are never lvalues unless that cast is to a reference type.
LValue emitCXXTypeidLValue(const CXXTypeidExpr *e)
mlir::Value emitLoadOfScalar(LValue lvalue, SourceLocation loc)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv)
bool containsLabel(const clang::Stmt *s, bool ignoreCaseStmts=false)
Return true if the statement contains a label in it.
DeclMapTy localDeclMap
This keeps track of the CIR allocas or globals for local C declarations.
mlir::Value createOpenACCConstantInt(mlir::Location loc, unsigned width, int64_t value)
RValue emitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
LValue emitDeclRefLValue(const clang::DeclRefExpr *e)
void emitComplexExprIntoLValue(const Expr *e, LValue dest, bool isInit)
void pushEHDestroyIfNeeded(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushEHDestroyIfNeeded - Push the standard destructor for the given type as an EH-only cleanup.
std::optional< mlir::Value > emitNVPTXBuiltinExpr(unsigned builtinID, const CallExpr *expr)
Emit a call to an NVPTX builtin function.
static void eraseEmptyAndUnusedBlocks(cir::FuncOp func)
Remove leftover empty and unreachable blocks from an emitted function.
llvm::DenseMap< const clang::ValueDecl *, clang::FieldDecl * > lambdaCaptureFields
RValue emitCoawaitExpr(const CoawaitExpr &e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
ConstantEmission tryEmitAsConstant(const DeclRefExpr *refExpr)
Try to emit a reference to the given value without producing it as an l-value.
bool emitLifetimeStartOp(mlir::Location loc, mlir::Value addr)
RValue emitCall(const CIRGenFunctionInfo &funcInfo, const CIRGenCallee &callee, ReturnValueSlot returnValue, const CallArgList &args, cir::CIRCallOpInterface *callOp, bool isMustTail, SourceRange clangLoc)
mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, QualType ty, SourceLocation loc, SourceLocation assumptionLoc, int64_t alignment, mlir::Value offsetValue=nullptr)
std::optional< mlir::Value > emitSPIRVBuiltinExpr(unsigned builtinID, const CallExpr *expr)
Emit a call to a SPIR-V builtin function.
mlir::LogicalResult emitCaseDefaultCascade(const T *stmt, mlir::Type condType, mlir::ArrayAttr value, cir::CaseOpKind kind, bool buildingTopLevelCase)
void emitCXXThrowExpr(const CXXThrowExpr *e)
void setFastMathFlags(FPOptions fpFeatures)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
LValue emitMatrixElementExpr(const MatrixElementExpr *e)
int64_t getAccessedFieldNo(unsigned idx, mlir::ArrayAttr elts)
LValue emitPredefinedLValue(const PredefinedExpr *e)
RValue emitAnyExpr(const clang::Expr *e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Emit code to compute the specified expression which can have any type.
void emitCXXDestructorCall(const CXXDestructorDecl *dd, CXXDtorType type, bool forVirtualBase, bool delegating, Address thisAddr, QualType thisTy)
llvm::SmallVector< VPtr, 4 > VPtrsVector
cir::CoroSizeOp emitCoroSizeBuiltinCall(const CallExpr *e)
void emitLambdaStaticInvokeBody(const CXXMethodDecl *md)
bool sawAsmBlock
Whether or not a Microsoft-style asm block has been processed within this fuction.
void emitEndEHSpec(const clang::Decl *d)
Close the cir.try opened by emitStartEHSpec.
mlir::LogicalResult emitDeclStmt(const clang::DeclStmt &s)
cir::GetGlobalOp createGetCpuFeatures2(mlir::Location loc)
cir::CleanupScopeOp currentFullExprCleanupScope
The cir.cleanup.scope of the innermost FullExprCleanupScope that materialized one,...
llvm::DenseMap< const OpaqueValueExpr *, RValue > opaqueRValues
RValue emitNewOrDeleteBuiltinCall(const FunctionProtoType *type, const CallExpr *callExpr, OverloadedOperatorKind op)
mlir::LogicalResult emitDefaultStmt(const clang::DefaultStmt &s, mlir::Type condType, bool buildingTopLevelCase)
cir::CoroDoneOp emitCoroDoneBuiltinCall(const CallExpr *e)
cir::CoroResumeOp emitCoroResumeBuiltinCall(const CallExpr *e)
mlir::LogicalResult emitLabelStmt(const clang::LabelStmt &s)
Address emitArrayToPointerDecay(const Expr *e, LValueBaseInfo *baseInfo=nullptr)
std::pair< mlir::Value, mlir::Type > emitAsmInput(const TargetInfo::ConstraintInfo &info, const Expr *inputExpr, std::string &constraintString)
EHScopeStack::stable_iterator currentCleanupStackDepth
void emitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, const clang::ArrayType *arrayType, Address arrayBegin, const CXXConstructExpr *e, bool newPointerIsChecked, bool zeroInitialize=false)
Emit a loop to call a particular constructor for each of several members of an array.
cir::CoroAlignOp emitCoroAlignBuiltinCall(const CallExpr *e)
void pushFullExprCleanup(CleanupKind kind, As... a)
Push a cleanup to be run at the end of the current full-expression.
void emitDelegateCallArg(CallArgList &args, const clang::VarDecl *param, clang::SourceLocation loc)
We are performing a delegate call; that is, the current function is delegating to another one.
void emitAtomicStore(RValue rvalue, LValue dest, bool isInit)
mlir::Value emitStoreThroughBitfieldLValue(RValue src, LValue dstresult)
llvm::DenseMap< const OpaqueValueExpr *, LValue > opaqueLValues
Keeps track of the current set of opaque value expressions.
const CIRGenFunctionInfo * curFnInfo
CIRGenFunction(CIRGenModule &cgm, CIRGenBuilderTy &builder, bool suppressNewContext=false)
cir::CoroIdOp emitCoroIDBuiltinCall(const CallExpr *e)
void terminateStructuredRegionBody(mlir::Region &r, mlir::Location loc)
LValue emitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e)
LValue emitExtVectorElementExpr(const ExtVectorElementExpr *e)
bool inEHSpecTerminateScope()
Whether the wrapper opened by emitStartEHSpec is a terminate scope, whose handler calls std::terminat...
clang::ASTContext & getContext() const
RValue emitCXXMemberOrOperatorMemberCallExpr(const clang::CallExpr *ce, const clang::CXXMethodDecl *md, ReturnValueSlot returnValue, bool hasQualifier, clang::NestedNameSpecifier qualifier, bool isArrow, const clang::Expr *base)
void setAddrOfLocalVar(const clang::VarDecl *vd, Address addr)
Set the address of a local variable.
mlir::Value emitScalarConstant(const ConstantEmission &constant, Expr *e)
RValue emitBuiltinExpr(const clang::GlobalDecl &gd, unsigned builtinID, const clang::CallExpr *e, ReturnValueSlot returnValue)
void emitSYCLKernelCaller(const clang::OutlinedFunctionDecl *outlinedFnDecl, cir::FuncOp funcOp, cir::FuncType funcType, FunctionArgList &args)
void emitStartEHSpec(const clang::Decl *d)
Wrap the function body in a cir.try that enforces the exception specification of d: a filter handler ...
void emitInheritedCXXConstructorCall(const CXXConstructorDecl *d, bool forVirtualBase, Address thisAddr, bool inheritedFromVBase, const CXXInheritedCtorInitExpr *e)
void emitCXXDeleteExpr(const CXXDeleteExpr *e)
mlir::LogicalResult emitCoroutineBody(const CoroutineBodyStmt &s)
void pushCleanupAfterFullExpr(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer)
Queue a cleanup to be pushed after finishing the current full-expression.
RValue emitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *e, const CXXMethodDecl *md, ReturnValueSlot returnValue)
mlir::LogicalResult emitCompoundStmt(const clang::CompoundStmt &s, Address *lastValue=nullptr, AggValueSlot slot=AggValueSlot::ignored())
void emitNullabilityCheck(LValue lhs, mlir::Value rhs, clang::SourceLocation loc)
Given an assignment *lhs = rhs, emit a test that checks if rhs is nonnull, if 1LHS is marked _Nonnull...
mlir::LogicalResult emitGotoStmt(const clang::GotoStmt &s)
std::optional< mlir::Value > emitAArch64SVEBuiltinExpr(unsigned builtinID, const CallExpr *expr)
bool inAlwaysInlineAttributedStmt
True if the current statement has always_inline attribute.
bool inNoInlineAttributedStmt
True if the current statement has noinline attribute.
void emitStoreThroughLValue(RValue src, LValue dst, bool isInit=false)
Store the specified rvalue into the specified lvalue, where both are guaranteed to the have the same ...
bool isLValueSuitableForInlineAtomic(LValue lv)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
static llvm::SmallVector< QualType, 2 > getLifetimeExtendedTemporariesWithDestructor(const clang::VarDecl &d)
The types of the temporaries with a destructor that the initializer of the variable d,...
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
mlir::Value emitFromMemory(mlir::Value value, clang::QualType ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
mlir::LogicalResult emitCompoundStmtWithoutScope(const clang::CompoundStmt &s, Address *lastValue=nullptr, AggValueSlot slot=AggValueSlot::ignored())
mlir::LogicalResult emitOpenACCExitDataConstruct(const OpenACCExitDataConstruct &s)
void generateThunk(cir::FuncOp fn, SourceRange fnLoc, const CIRGenFunctionInfo &fnInfo, GlobalDecl gd, const ThunkInfo &thunk, bool isUnprototyped)
Generate code for a thunk function.
mlir::LogicalResult emitSYCLKernelCallStmt(const SYCLKernelCallStmt &s)
void emitIgnoredExpr(const clang::Expr *e)
Emit code to compute the specified expression, ignoring the result.
Address createMemTemp(QualType t, mlir::Location loc, const Twine &name="tmp", Address *alloca=nullptr, mlir::OpBuilder::InsertPoint ip={})
Create a temporary memory object of the given type, with appropriate alignmen and cast it to the defa...
void emitDelegatingCXXConstructorCall(const CXXConstructorDecl *ctor, const FunctionArgList &args)
mlir::Value emitDynamicCast(Address thisAddr, const CXXDynamicCastExpr *dce)
void emitAggExpr(const clang::Expr *e, AggValueSlot slot)
mlir::Value emitScalarOrConstFoldImmArg(unsigned iceArguments, unsigned idx, const Expr *argExpr)
Address createDefaultAlignTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name)
CreateDefaultAlignTempAlloca - This creates an alloca with the default alignment of the corresponding...
mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty, mlir::Location loc, clang::CharUnits alignment, mlir::OpBuilder::InsertPoint ip, mlir::Value arraySize=nullptr)
mlir::LogicalResult emitOpenACCAtomicConstruct(const OpenACCAtomicConstruct &s)
LValue emitCXXConstructLValue(const CXXConstructExpr *e)
void finishThunk()
Finish generating a thunk function.
RValue emitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *expr)
LValue emitCompoundLiteralLValue(const CompoundLiteralExpr *e)
void emitAutoVarCleanups(const AutoVarEmission &emission)
RValue emitRotate(const CallExpr *e, bool isRotateLeft)
mlir::LogicalResult emitOpenACCLoopConstruct(const OpenACCLoopConstruct &s)
CIRGenCallee emitCallee(const clang::Expr *e)
Address emitAddrOfFieldStorage(Address base, const FieldDecl *field, llvm::StringRef fieldName, unsigned fieldIndex)
This class organizes the cross-function state that is used while generating CIR code.
This class organizes the cross-module state that is used while lowering AST types to CIR types.
Definition CIRGenTypes.h:51
A saved depth on the scope stack.
A stack of scopes which respond to exceptions, including cleanups and catch blocks.
Type for representing both the decl and type of parameters to a function.
Definition CIRGenCall.h:195
static LValue makeAddr(Address address, clang::QualType t, LValueBaseInfo baseInfo)
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
Contains the address where the return value of a function can be stored, and whether the address is v...
Definition CIRGenCall.h:262
Represents a call to a CUDA kernel function.
Definition ExprCXX.h:239
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2631
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:486
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1756
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2360
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2750
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Represents a C++ temporary.
Definition ExprCXX.h:1464
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1213
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:853
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
CaseStmt - Represent a case statement.
Definition Stmt.h:1931
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4369
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3674
ContinueStmt - This represents a continue.
Definition Stmt.h:3132
Represents a 'co_return' statement in the C++ Coroutines TS.
Definition StmtCXX.h:474
Represents the body of a coroutine.
Definition StmtCXX.h:321
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition ExprCXX.h:5309
SourceLocExprScopeGuard(const Expr *DefaultExpr, CurrentSourceLocExprScope &Current)
Represents the current source location and context used to determine the value of the source location...
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2843
This represents one expression.
Definition Expr.h:114
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6696
Represents a member of a struct/union/class.
Definition Decl.h:3341
Represents a function declaration or definition.
Definition Decl.h:2082
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
const Decl * getDecl() const
Definition GlobalDecl.h:115
GotoStmt - This represents a direct goto.
Definition Stmt.h:2980
IndirectGotoStmt - This represents an indirect goto.
Definition Stmt.h:3019
Describes an C or C++ initializer list.
Definition Expr.h:5377
FPExceptionModeKind
Possible floating point exception behavior.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2934
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
This represents 'pragma omp allocate ...' directive.
Definition DeclOpenMP.h:536
Pseudo declaration for capturing expressions.
Definition DeclOpenMP.h:445
This represents 'pragma omp declare mapper ...' directive.
Definition DeclOpenMP.h:349
This represents 'pragma omp declare reduction ...' directive.
Definition DeclOpenMP.h:239
This represents 'pragma omp groupprivate ...' directive.
Definition DeclOpenMP.h:173
This represents 'pragma omp requires...' directive.
Definition DeclOpenMP.h:479
This represents 'pragma omp threadprivate ...' directive.
Definition DeclOpenMP.h:110
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1273
Represents a partial function definition.
Definition Decl.h:5066
Represents a parameter to a function.
Definition Decl.h:1832
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2074
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6890
A (possibly-)qualified type.
Definition TypeBase.h:938
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3173
Flags to identify the types for overloaded SVE builtins.
SYCLKernelCallStmt represents the transformation that is applied to the body of a function declared w...
Definition StmtSYCL.h:36
Encodes a location in the source.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2520
Exposes information about the current target.
Definition TargetInfo.h:228
Represents a declaration of a type.
Definition Decl.h:3694
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:5026
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
Represents a variable declaration or definition.
Definition Decl.h:934
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Expr * getSizeExpr() const
Definition TypeBase.h:4078
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2708
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
bool checkIfLoopMustProgress(const LangOptions &LangOpts, const CodeGenOptions &CGOpts, ASTContext &Ctx, const Expr *ControllingExpression, bool HasEmptyBody, llvm::function_ref< void()> RemoveMustProgress)
Returns true if a loop must make progress, which means the mustprogress attribute can be added to it.
Definition StmtUtils.cpp:15
EvaluationOrder
The order in which the arguments of a call must be evaluated.
Definition CallUtils.h:29
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
CXXCtorType
C++ constructor types.
Definition ABI.h:24
OpenACCDirectiveKind
QualType pointeeType(QualType T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OpenACCComputeConstruct(OpenACCDirectiveKind K, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses, Stmt *StructuredBlock)
const FunctionProtoType * T
CXXDtorType
C++ destructor types.
Definition ABI.h:34
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define true
Definition stdbool.h:25
static bool aggValueSlot()
static bool peepholeProtection()
static bool opAllocaEscapeByReference()
static bool generateDebugInfo()
AutoVarEmission(const clang::VarDecl &variable)
bool isEscapingByRef
True if the variable is a __block variable that is captured by an escaping block.
Address addr
The address of the alloca for languages with explicit address space (e.g.
bool useLifetimeMarkers
True if lifetime op should be used.
bool emittedAsOffload
True if the variable was emitted as an offload recipe, and thus doesn't have the same sort of alloca ...
bool isConstantAggregate
True if the variable is of aggregate type and has a constant initializer.
Address getAllocatedAddress() const
Returns the raw, allocated address, which is not necessarily the address of the object itself.
Address getObjectAddress(CIRGenFunction &cgf) const
Returns the address of the object within this declaration.
std::unique_ptr< CGCoroData > data
CXXDefaultArgExprScope(CIRGenFunction &cfg, const CXXDefaultArgExpr *e)
Scope that deactivates all enclosed deferred cleanups on exit.
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.
A cleanup that was pushed to the EH stack but whose deactivation is deferred until the enclosing Clea...
EmittedOrderOrScope(CIRGenFunction &cgf, const Expr *expr)
Represents a scope, including function bodies, compound statements, and the substatements of if/while...
llvm::ArrayRef< mlir::Block * > getRetBlocks()
mlir::Block * getOrCreateRetBlock(CIRGenFunction &cgf, mlir::Location loc)
LexicalScope(CIRGenFunction &cgf, mlir::Location loc, mlir::Block *eb)
void updateRetLoc(mlir::Block *b, mlir::Location loc)
mlir::Location getRetLoc(mlir::Block *b)
Set by emitAutoVarDeclWithCapturedCleanups while it emits the initializer of a variable,...
A cleanup whose destructor call is not emitted where the cleanup is registered.
CapturedCleanups * capturedBy
If set, the cleanup is captured by this owner instead of opening a cir.cleanup.scope when it is pushe...
llvm::PointerUnion< const clang::FunctionProtoType *, const clang::ObjCMethodDecl * > p
PrototypeWrapper(const clang::ObjCMethodDecl *md)
PrototypeWrapper(const clang::FunctionProtoType *ft)
const clang::CXXRecordDecl * vtableClass
const clang::CXXRecordDecl * nearestVBase
VlaSizePair(mlir::Value num, QualType ty)
virtual mlir::LogicalResult operator()(CIRGenFunction &cgf)=0
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
The this pointer adjustment as well as an optional return adjustment for a thunk.
Definition Thunk.h:157