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"
39#include "llvm/ADT/ScopedHashTable.h"
40#include "llvm/IR/Instructions.h"
41
42namespace {
43class ScalarExprEmitter;
44} // namespace
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 friend class ::ScalarExprEmitter;
67 /// The builder is a helper class to create IR inside a function. The
68 /// builder is stateful, in particular it keeps an "insertion point": this
69 /// is where the next operations will be introduced.
70 CIRGenBuilderTy &builder;
71
72 /// Saves the builder's constrained floating-point configuration on
73 /// construction and restores it on destruction. The builder is shared
74 /// across all functions in the module, so its constrained-FP state must be
75 /// scoped to each function's emission.
76 ///
77 /// Note that the similarly named CIRGenFunction::CIRGenFPOptionsRAII
78 /// intentionally avoids restoring the "isFPConstrained" state because that
79 /// state is function-wide, but this object does restore the state so that
80 /// any CIRGenFunction instance created while we are in the process of
81 /// emitting another function cannot corrupt the prior functions state.
82 struct ConstrainedFPRAII {
83 CIRGenBuilderTy &builder;
84 bool savedIsFPConstrained;
86 llvm::RoundingMode savedRounding;
87
88 explicit ConstrainedFPRAII(CIRGenBuilderTy &builder)
89 : builder(builder), savedIsFPConstrained(builder.getIsFPConstrained()),
90 savedExcept(builder.getDefaultConstrainedExcept()),
91 savedRounding(builder.getDefaultConstrainedRounding()) {}
92 ~ConstrainedFPRAII() {
93 builder.setIsFPConstrained(savedIsFPConstrained);
94 builder.setDefaultConstrainedExcept(savedExcept);
95 builder.setDefaultConstrainedRounding(savedRounding);
96 }
97 } constrainedFPState{builder};
98
99public:
100 /// The GlobalDecl for the current function being compiled or the global
101 /// variable currently being initialized.
103
105
106 /// The compiler-generated variable that holds the return value.
107 std::optional<mlir::Value> fnRetAlloca;
108
109 // Holds coroutine data if the current function is a coroutine. We use a
110 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
111 // in this header.
112 struct CGCoroInfo {
113 std::unique_ptr<CGCoroData> data;
114 CGCoroInfo();
115 ~CGCoroInfo();
116 };
118
119 bool isCoroutine() const { return curCoro.data != nullptr; }
120
121 /// The temporary alloca to hold the return value. This is
122 /// invalid iff the function has no return value.
124
125 /// Tracks function scope overall cleanup handling.
127
128 typedef void Destroyer(CIRGenFunction &cgf, Address addr, QualType ty);
129
130 /// A cleanup entry that will be promoted onto the EH scope stack at a later
131 /// point. Used by both the lifetime-extended cleanup stack (promoted when
132 /// the enclosing scope exits) and the deferred conditional cleanup stack
133 /// (promoted at the enclosing full-expression level).
134 ///
135 /// Currently only DestroyObject cleanups use this. When other cleanup types
136 /// are needed (e.g., CallLifetimeEnd), this struct can be extended with a
137 /// std::variant of cleanup data types.
145
147
149
150 /// A cleanup that was pushed to the EH stack but whose deactivation is
151 /// deferred until the enclosing CleanupDeactivationScope exits. Used to
152 /// protect partially-constructed aggregates (e.g. lambda captures) so that
153 /// already-initialized sub-objects are destroyed if a later initializer
154 /// throws, while avoiding double-destruction after full construction.
160
161 /// Scope that deactivates all enclosed deferred cleanups on exit.
162 /// Mirrors CodeGenFunction::CleanupDeactivationScope in classic codegen.
166 bool deactivated = false;
167
171
173 assert(!deactivated && "Deactivating already deactivated scope");
174 auto &stack = cgf.deferredDeactivationCleanupStack;
175 for (size_t i = stack.size(); i > oldDeactivateCleanupStackSize; i--) {
176 cgf.deactivateCleanupBlock(stack[i - 1].cleanup,
177 stack[i - 1].dominatingIP);
178 stack[i - 1].dominatingIP->erase();
179 }
180 stack.resize(oldDeactivateCleanupStackSize);
181 deactivated = true;
182 }
183
188 };
189
191
192 /// If a ParmVarDecl had the pass_object_size attribute, this will contain a
193 /// mapping from said ParmVarDecl to its implicit "object_size" parameter.
194 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *>
196
197 /// A mapping from NRVO variables to the flags used to indicate
198 /// when the NRVO has been applied to this variable.
199 llvm::DenseMap<const VarDecl *, mlir::Value> nrvoFlags;
200
201 llvm::DenseMap<const clang::ValueDecl *, clang::FieldDecl *>
204
205 /// CXXThisDecl - When generating code for a C++ member function,
206 /// this will hold the implicit 'this' declaration.
208 mlir::Value cxxabiThisValue = nullptr;
209 mlir::Value cxxThisValue = nullptr;
212
213 /// When generating code for a constructor or destructor, this will hold the
214 /// implicit argument (e.g. VTT).
217
218 /// The value of 'this' to sue when evaluating CXXDefaultInitExprs within this
219 /// expression.
221
222 /// The values of function arguments to use when evaluating
223 /// CXXInheritedCtorInitExprs within this context.
225
226 /// The current array initialization index when evaluating an
227 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
228 mlir::Value arrayInitIndex = nullptr;
229
230 // Holds the Decl for the current outermost non-closure context
231 const clang::Decl *curFuncDecl = nullptr;
232 /// This is the inner-most code context, which includes blocks.
233 const clang::Decl *curCodeDecl = nullptr;
236
237 /// The current function or global initializer that is generated code for.
238 /// This is usually a cir::FuncOp, but it can also be a cir::GlobalOp for
239 /// global initializers.
240 mlir::Operation *curFn = nullptr;
241
242 /// While the initializer of a variable with static storage duration is being
243 /// emitted, the region that destructors registered by that initializer belong
244 /// in: the cir.global's own dtor region for a namespace-scope variable, and
245 /// the enclosing cir.local_init's for a function-local static, which has to
246 /// be destroyed in-function under its guard. Null outside such an
247 /// initializer.
248 mlir::Region *curStaticVarDtorRegion = nullptr;
249
250 /// Save Parameter Decl for coroutine.
252
253 using DeclMapTy = llvm::DenseMap<const clang::Decl *, Address>;
254 /// This keeps track of the CIR allocas or globals for local C
255 /// declarations.
257
258 /// The type of the condition for the emitting switch statement.
260
261 clang::ASTContext &getContext() const { return cgm.getASTContext(); }
262
263 CIRGenBuilderTy &getBuilder() { return builder; }
264
266 const CIRGenModule &getCIRGenModule() const { return cgm; }
267
269 // We currently assume this isn't called for a global initializer.
270 auto fn = mlir::cast<cir::FuncOp>(curFn);
271 return &fn.getRegion().front();
272 }
273
274 /// Sanitizers enabled for this function.
276
278 public:
282
283 private:
284 void ConstructorHelper(clang::FPOptions FPFeatures);
285 CIRGenFunction &cgf;
286 clang::FPOptions oldFPFeatures;
288 llvm::RoundingMode oldRounding;
289 };
291
292 /// The symbol table maps a variable name to a value in the current scope.
293 /// Entering a function creates a new scope, and the function arguments are
294 /// added to the mapping. When the processing of a function is terminated,
295 /// the scope is destroyed and the mappings created in this scope are
296 /// dropped.
297 using SymTableTy = llvm::ScopedHashTable<const clang::Decl *, mlir::Value>;
299
300 /// Whether a cir.stacksave operation has been added. Used to avoid
301 /// inserting cir.stacksave for multiple VLAs in the same scope.
302 bool didCallStackSave = false;
303
304 /// Whether or not a Microsoft-style asm block has been processed within
305 /// this fuction. These can potentially set the return value.
306 bool sawAsmBlock = false;
307
308 /// In C++, whether we are code generating a thunk. This controls whether we
309 /// should emit cleanups.
310 bool curFuncIsThunk = false;
311
312 mlir::Type convertTypeForMem(QualType t);
313
314 mlir::Type convertType(clang::QualType t);
315 mlir::Type convertType(const TypeDecl *t) {
316 return convertType(getContext().getTypeDeclType(t));
317 }
318
319 /// Get integer from a mlir::Value that is an int constant or a constant op.
320 static int64_t getSExtIntValueFromConstOp(mlir::Value val) {
321 auto constOp = val.getDefiningOp<cir::ConstantOp>();
322 assert(constOp && "getSExtIntValueFromConstOp call with non ConstantOp");
323 return constOp.getIntValue().getSExtValue();
324 }
325
326 /// Get zero-extended integer from a mlir::Value that is an int constant or a
327 /// constant op.
328 static int64_t getZExtIntValueFromConstOp(mlir::Value val) {
329 auto constOp = val.getDefiningOp<cir::ConstantOp>();
330 assert(constOp && "getZExtIntValueFromConstOp call with non ConstantOp");
331 return constOp.getIntValue().getZExtValue();
332 }
333
334 /// Return the cir::TypeEvaluationKind of QualType \c type.
336
340
344
346 bool suppressNewContext = false);
348
349 CIRGenTypes &getTypes() const { return cgm.getTypes(); }
350
351 const TargetInfo &getTarget() const { return cgm.getTarget(); }
352 mlir::MLIRContext &getMLIRContext() { return cgm.getMLIRContext(); }
353
355 return cgm.getTargetCIRGenInfo();
356 }
357
358 // ---------------------
359 // Opaque value handling
360 // ---------------------
361
362 /// Keeps track of the current set of opaque value expressions.
363 llvm::DenseMap<const OpaqueValueExpr *, LValue> opaqueLValues;
364 llvm::DenseMap<const OpaqueValueExpr *, RValue> opaqueRValues;
365
366 // This keeps track of the associated size for each VLA type.
367 // We track this by the size expression rather than the type itself because
368 // in certain situations, like a const qualifier applied to an VLA typedef,
369 // multiple VLA types can share the same size expression.
370 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
371 // enter/leave scopes.
372 llvm::DenseMap<const Expr *, mlir::Value> vlaSizeMap;
373
374public:
375 /// A non-RAII class containing all the information about a bound
376 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
377 /// this which makes individual mappings very simple; using this
378 /// class directly is useful when you have a variable number of
379 /// opaque values or don't want the RAII functionality for some
380 /// reason.
381 class OpaqueValueMappingData {
382 const OpaqueValueExpr *opaqueValue;
383 bool boundLValue;
384
385 OpaqueValueMappingData(const OpaqueValueExpr *ov, bool boundLValue)
386 : opaqueValue(ov), boundLValue(boundLValue) {}
387
388 public:
389 OpaqueValueMappingData() : opaqueValue(nullptr) {}
390
391 static bool shouldBindAsLValue(const Expr *expr) {
392 // gl-values should be bound as l-values for obvious reasons.
393 // Records should be bound as l-values because IR generation
394 // always keeps them in memory. Expressions of function type
395 // act exactly like l-values but are formally required to be
396 // r-values in C.
397 return expr->isGLValue() || expr->getType()->isFunctionType() ||
399 }
400
402 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const Expr *e) {
403 if (shouldBindAsLValue(ov))
404 return bind(cgf, ov, cgf.emitLValue(e));
405 return bind(cgf, ov, cgf.emitAnyExpr(e));
406 }
407
409 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const LValue &lv) {
410 assert(shouldBindAsLValue(ov));
411 cgf.opaqueLValues.insert(std::make_pair(ov, lv));
412 return OpaqueValueMappingData(ov, true);
413 }
414
416 bind(CIRGenFunction &cgf, const OpaqueValueExpr *ov, const RValue &rv) {
417 assert(!shouldBindAsLValue(ov));
418 cgf.opaqueRValues.insert(std::make_pair(ov, rv));
419
420 OpaqueValueMappingData data(ov, false);
421
422 // Work around an extremely aggressive peephole optimization in
423 // EmitScalarConversion which assumes that all other uses of a
424 // value are extant.
426 return data;
427 }
428
429 bool isValid() const { return opaqueValue != nullptr; }
430 void clear() { opaqueValue = nullptr; }
431
433 assert(opaqueValue && "no data to unbind!");
434
435 if (boundLValue) {
436 cgf.opaqueLValues.erase(opaqueValue);
437 } else {
438 cgf.opaqueRValues.erase(opaqueValue);
440 }
441 }
442 };
443
444 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
446 CIRGenFunction &cgf;
448
449 public:
453
454 /// Build the opaque value mapping for the given conditional
455 /// operator if it's the GNU ?: extension. This is a common
456 /// enough pattern that the convenience operator is really
457 /// helpful.
458 ///
461 : cgf(cgf) {
462 if (mlir::isa<ConditionalOperator>(op))
463 // Leave Data empty.
464 return;
465
467 mlir::cast<BinaryConditionalOperator>(op);
469 e->getCommon());
470 }
471
472 /// Build the opaque value mapping for an OpaqueValueExpr whose source
473 /// expression is set to the expression the OVE represents.
475 : cgf(cgf) {
476 if (ov) {
477 assert(ov->getSourceExpr() && "wrong form of OpaqueValueMapping used "
478 "for OVE with no source expression");
479 data = OpaqueValueMappingData::bind(cgf, ov, ov->getSourceExpr());
480 }
481 }
482
484 LValue lvalue)
485 : cgf(cgf),
486 data(OpaqueValueMappingData::bind(cgf, opaqueValue, lvalue)) {}
487
489 RValue rvalue)
490 : cgf(cgf),
491 data(OpaqueValueMappingData::bind(cgf, opaqueValue, rvalue)) {}
492
493 void pop() {
494 data.unbind(cgf);
495 data.clear();
496 }
497
499 if (data.isValid())
500 data.unbind(cgf);
501 }
502 };
503
504private:
505 /// Declare a variable in the current scope, return success if the variable
506 /// wasn't declared yet.
507 void declare(mlir::Value addrVal, const clang::Decl *var, clang::QualType ty,
508 mlir::Location loc, clang::CharUnits alignment,
509 bool isParam = false);
510
511public:
512 mlir::Value createDummyValue(mlir::Location loc, clang::QualType qt);
513
514 void emitNullInitialization(mlir::Location loc, Address destPtr, QualType ty);
515
516private:
517 // Track current variable initialization (if there's one)
518 const clang::VarDecl *currVarDecl = nullptr;
519 class VarDeclContext {
521 const clang::VarDecl *oldVal = nullptr;
522
523 public:
524 VarDeclContext(CIRGenFunction &p, const VarDecl *value) : p(p) {
525 if (p.currVarDecl)
526 oldVal = p.currVarDecl;
527 p.currVarDecl = value;
528 }
529
530 /// Can be used to restore the state early, before the dtor
531 /// is run.
532 void restore() { p.currVarDecl = oldVal; }
533 ~VarDeclContext() { restore(); }
534 };
535
536public:
537 /// Use to track source locations across nested visitor traversals.
538 /// Always use a `SourceLocRAIIObject` to change currSrcLoc.
539 std::optional<mlir::Location> currSrcLoc;
541 CIRGenFunction &cgf;
542 std::optional<mlir::Location> oldLoc;
543
544 public:
545 SourceLocRAIIObject(CIRGenFunction &cgf, mlir::Location value) : cgf(cgf) {
546 if (cgf.currSrcLoc)
547 oldLoc = cgf.currSrcLoc;
548 cgf.currSrcLoc = value;
549 }
550
551 /// Can be used to restore the state early, before the dtor
552 /// is run.
553 void restore() { cgf.currSrcLoc = oldLoc; }
555 };
556
558 llvm::ScopedHashTableScope<const clang::Decl *, mlir::Value>;
559
560 /// Hold counters for incrementally naming temporaries
561 unsigned counterRefTmp = 0;
562 unsigned counterAggTmp = 0;
563 std::string getCounterRefTmpAsString();
564 std::string getCounterAggTmpAsString();
565
566 /// Helpers to convert Clang's SourceLocation to a MLIR Location.
567 mlir::Location getLoc(clang::SourceLocation srcLoc);
568 mlir::Location getLoc(clang::SourceRange srcLoc);
569 mlir::Location getLoc(mlir::Location lhs, mlir::Location rhs);
570
571 const clang::LangOptions &getLangOpts() const { return cgm.getLangOpts(); }
572
573 /// True if an insertion point is defined. If not, this indicates that the
574 /// current code being emitted is unreachable.
575 /// FIXME(cir): we need to inspect this and perhaps use a cleaner mechanism
576 /// since we don't yet force null insertion point to designate behavior (like
577 /// LLVM's codegen does) and we probably shouldn't.
578 bool haveInsertPoint() const {
579 return builder.getInsertionBlock() != nullptr;
580 }
581
582 // Wrapper for function prototype sources. Wraps either a FunctionProtoType or
583 // an ObjCMethodDecl.
585 llvm::PointerUnion<const clang::FunctionProtoType *,
586 const clang::ObjCMethodDecl *>
588
591 };
592
594
597 RValue emitAtomicLoad(LValue lvalue, SourceLocation loc, cir::MemOrder order,
598 bool isVolatile = false,
600
601 /// An abstract representation of regular/ObjC call/message targets.
603 /// The function declaration of the callee.
604 [[maybe_unused]] const clang::Decl *calleeDecl;
605
606 public:
607 AbstractCallee() : calleeDecl(nullptr) {}
608 AbstractCallee(const clang::FunctionDecl *fd) : calleeDecl(fd) {}
609
610 bool hasFunctionDecl() const {
611 return llvm::isa_and_nonnull<clang::FunctionDecl>(calleeDecl);
612 }
613
614 const clang::Decl *getDecl() const { return calleeDecl; }
615
616 unsigned getNumParams() const {
617 if (const auto *fd = llvm::dyn_cast<clang::FunctionDecl>(calleeDecl))
618 return fd->getNumParams();
619 return llvm::cast<clang::ObjCMethodDecl>(calleeDecl)->param_size();
620 }
621
622 const clang::ParmVarDecl *getParamDecl(unsigned I) const {
623 if (const auto *fd = llvm::dyn_cast<clang::FunctionDecl>(calleeDecl))
624 return fd->getParamDecl(I);
625 return *(llvm::cast<clang::ObjCMethodDecl>(calleeDecl)->param_begin() +
626 I);
627 }
628 };
629
630 /// True if the current statement has noinline attribute.
632
633 /// True if the current statement has always_inline attribute.
635
636 // The CallExpr within the current statement that the musttail attribute
637 // applies to. nullptr if there is no 'musttail' on the current statement.
638 const CallExpr *mustTailCall = nullptr;
639
640 struct VlaSizePair {
641 mlir::Value numElts;
643
644 VlaSizePair(mlir::Value num, QualType ty) : numElts(num), type(ty) {}
645 };
646
647 /// Return the number of elements for a single dimension
648 /// for the given array type.
649 VlaSizePair getVLAElements1D(const VariableArrayType *vla);
650
651 /// Returns an MLIR::Value+QualType pair that corresponds to the size,
652 /// in non-variably-sized elements, of a variable length array type,
653 /// plus that largest non-variably-sized element type. Assumes that
654 /// the type has already been emitted with emitVariablyModifiedType.
655 VlaSizePair getVLASize(const VariableArrayType *type);
656 VlaSizePair getVLASize(QualType type);
657
659
660 mlir::Value getAsNaturalPointerTo(Address addr, QualType pointeeType) {
661 return getAsNaturalAddressOf(addr, pointeeType).getBasePointer();
662 }
663
664 void finishFunction(SourceLocation endLoc);
665
666 /// Determine whether the given initializer is trivial in the sense
667 /// that it requires no code to be generated.
668 bool isTrivialInitializer(const Expr *init);
669
670 /// If the specified expression does not fold to a constant, or if it does but
671 /// contains a label, return false. If it constant folds return true and set
672 /// the boolean result in Result.
673 bool constantFoldsToBool(const clang::Expr *cond, bool &resultBool,
674 bool allowLabels = false);
676 llvm::APSInt &resultInt,
677 bool allowLabels = false);
678
679 /// Return true if the statement contains a label in it. If
680 /// this statement is not executed normally, it not containing a label means
681 /// that we can just remove the code.
682 bool containsLabel(const clang::Stmt *s, bool ignoreCaseStmts = false);
683
684 Address emitExtVectorElementLValue(LValue lv, mlir::Location loc);
685
686 class ConstantEmission {
687 // Cannot use mlir::TypedAttr directly here because of bit availability.
688 llvm::PointerIntPair<mlir::Attribute, 1, bool> valueAndIsReference;
689 ConstantEmission(mlir::TypedAttr c, bool isReference)
690 : valueAndIsReference(c, isReference) {}
691
692 public:
694 static ConstantEmission forReference(mlir::TypedAttr c) {
695 return ConstantEmission(c, true);
696 }
697 static ConstantEmission forValue(mlir::TypedAttr c) {
698 return ConstantEmission(c, false);
699 }
700
701 explicit operator bool() const {
702 return valueAndIsReference.getOpaqueValue() != nullptr;
703 }
704
705 bool isReference() const { return valueAndIsReference.getInt(); }
707 assert(isReference());
708 cgf.cgm.errorNYI(refExpr->getSourceRange(),
709 "ConstantEmission::getReferenceLValue");
710 return {};
711 }
712
713 mlir::TypedAttr getValue() const {
714 assert(!isReference());
715 return mlir::cast<mlir::TypedAttr>(valueAndIsReference.getPointer());
716 }
717 };
718
719 ConstantEmission tryEmitAsConstant(const DeclRefExpr *refExpr);
720 ConstantEmission tryEmitAsConstant(const MemberExpr *me);
721
724 /// The address of the alloca for languages with explicit address space
725 /// (e.g. OpenCL) or alloca casted to generic pointer for address space
726 /// agnostic languages (e.g. C++). Invalid if the variable was emitted
727 /// as a global constant.
729
730 /// True if the variable is of aggregate type and has a constant
731 /// initializer.
733
734 /// True if the variable is a __block variable that is captured by an
735 /// escaping block.
736 bool isEscapingByRef = false;
737
738 /// True if the variable was emitted as an offload recipe, and thus doesn't
739 /// have the same sort of alloca initialization.
740 bool emittedAsOffload = false;
741
742 /// True if lifetime op should be used.
743 bool useLifetimeMarkers = false;
744
745 mlir::Value nrvoFlag{};
746
747 struct Invalid {};
749
752
754
755 bool wasEmittedAsGlobal() const { return !addr.isValid(); }
756
758
759 /// Returns the raw, allocated address, which is not necessarily
760 /// the address of the object itself. It is casted to default
761 /// address space for address space agnostic languages.
762 Address getAllocatedAddress() const { return addr; }
763
764 // Changes the stored address for the emission. This function should only
765 // be used in extreme cases, and isn't required to model normal AST
766 // initialization/variables.
768
769 /// Returns the address of the object within this declaration.
770 /// Note that this does not chase the forwarding pointer for
771 /// __block decls.
773 if (!isEscapingByRef)
774 return addr;
775
777 return Address::invalid();
778 }
779 };
780
781 /// Perform the usual unary conversions on the specified expression and
782 /// compare the result against zero, returning an Int1Ty value.
783 mlir::Value evaluateExprAsBool(const clang::Expr *e);
784
785 cir::GlobalOp addInitializerToStaticVarDecl(const VarDecl &d,
786 cir::GlobalOp gv,
787 cir::GetGlobalOp gvAddr);
788
789 /// Enter the cleanups necessary to complete the given phase of destruction
790 /// for a destructor. The end result should call destructors on members and
791 /// base classes in reverse order of their construction.
793
794 /// Determines whether an EH cleanup is required to destroy a type
795 /// with the given destruction kind.
796 /// TODO(cir): could be shared with Clang LLVM codegen
798 switch (kind) {
800 return false;
804 return getLangOpts().Exceptions;
806 return getLangOpts().Exceptions &&
807 cgm.getCodeGenOpts().ObjCAutoRefCountExceptions;
808 }
809 llvm_unreachable("bad destruction kind");
810 }
811
815
817
818 /// Set the address of a local variable.
820 assert(!localDeclMap.count(vd) && "Decl already exists in LocalDeclMap!");
821 localDeclMap.insert({vd, addr});
822
823 // Add to the symbol table if not there already.
824 if (symbolTable.count(vd))
825 return;
826 symbolTable.insert(vd, addr.getPointer());
827 }
828
829 // Replaces the address of the local variable, if it exists. Else does the
830 // same thing as setAddrOfLocalVar.
832 localDeclMap.insert_or_assign(vd, addr);
833 }
834
835 // A class to allow reverting changes to a var-decl's registration to the
836 // localDeclMap. This is used in cases where things are being inserted into
837 // the variable list but don't follow normal lookup/search rules, like in
838 // OpenACC recipe generation.
840 CIRGenFunction &cgf;
841 const VarDecl *vd;
842 bool shouldDelete = false;
843 Address oldAddr = Address::invalid();
844
845 public:
847 : cgf(cgf), vd(vd) {
848 auto mapItr = cgf.localDeclMap.find(vd);
849
850 if (mapItr != cgf.localDeclMap.end())
851 oldAddr = mapItr->second;
852 else
853 shouldDelete = true;
854 }
855
857 if (shouldDelete)
858 cgf.localDeclMap.erase(vd);
859 else
860 cgf.localDeclMap.insert_or_assign(vd, oldAddr);
861 }
862 };
863
865
868
869 static bool
871
878
881
885 const clang::CXXRecordDecl *nearestVBase,
886 clang::CharUnits offsetFromNearestVBase,
887 bool baseIsNonVirtualPrimaryBase,
888 const clang::CXXRecordDecl *vtableClass,
889 VisitedVirtualBasesSetTy &vbases, VPtrsVector &vptrs);
890 /// Return the Value of the vtable pointer member pointed to by thisAddr.
891 mlir::Value getVTablePtr(mlir::Location loc, Address thisAddr,
892 const clang::CXXRecordDecl *vtableClass);
893
894 /// Returns whether we should perform a type checked load when loading a
895 /// virtual function for virtual calls to members of RD. This is generally
896 /// true when both vcall CFI and whole-program-vtables are enabled.
898
899 /// Source location information about the default argument or member
900 /// initializer expression we're evaluating, if any.
904
905 /// A scope within which we are constructing the fields of an object which
906 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use if
907 /// we need to evaluate the CXXDefaultInitExpr within the evaluation.
909 public:
911 : cgf(cgf), oldCXXDefaultInitExprThis(cgf.cxxDefaultInitExprThis) {
912 cgf.cxxDefaultInitExprThis = thisAddr;
913 }
915 cgf.cxxDefaultInitExprThis = oldCXXDefaultInitExprThis;
916 }
917
918 private:
919 CIRGenFunction &cgf;
920 Address oldCXXDefaultInitExprThis;
921 };
922
923 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
924 /// is overridden to be the object under construction.
926 public:
931 cgf.cxxThisValue = cgf.cxxDefaultInitExprThis.getPointer();
932 cgf.cxxThisAlignment = cgf.cxxDefaultInitExprThis.getAlignment();
933 }
935 cgf.cxxThisValue = oldCXXThisValue;
936 cgf.cxxThisAlignment = oldCXXThisAlignment;
937 }
938
939 public:
941 mlir::Value oldCXXThisValue;
944 };
945
950
951 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
952 /// current loop index is overridden. In order to encourage re-use of existing
953 /// array initialization, this uses a flag to determine if it is a 'no-op' or
954 /// not.
956 public:
957 ArrayInitLoopExprScope(CIRGenFunction &cgf, bool setIdx, mlir::Value index)
958 : cgf(cgf),
959 oldArrayInitIndex(setIdx
960 ? std::optional<mlir::Value>(cgf.arrayInitIndex)
961 : std::nullopt) {
962 if (setIdx)
963 cgf.arrayInitIndex = index;
964 }
966 if (oldArrayInitIndex.has_value())
967 cgf.arrayInitIndex = *oldArrayInitIndex;
968 }
969
970 private:
971 CIRGenFunction &cgf;
972 std::optional<mlir::Value> oldArrayInitIndex;
973 };
974
975 /// Get the index of the current ArrayInitLoopExpr, if any.
976 mlir::Value getArrayInitIndex() { return arrayInitIndex; }
977
979 LValue makeNaturalAlignAddrLValue(mlir::Value val, QualType ty);
980
981 /// Construct an address with the natural alignment of T. If a pointer to T
982 /// is expected to be signed, the pointer passed to this function must have
983 /// been signed, and the returned Address will have the pointer authentication
984 /// information needed to authenticate the signed pointer.
986 CharUnits alignment,
987 bool forPointeeType = false,
988 LValueBaseInfo *baseInfo = nullptr) {
989 if (alignment.isZero())
990 alignment = cgm.getNaturalTypeAlignment(t, baseInfo);
991 return Address(ptr, convertTypeForMem(t), alignment);
992 }
993
995 Address value, const CXXRecordDecl *derived,
996 llvm::iterator_range<CastExpr::path_const_iterator> path,
997 bool nullCheckValue, SourceLocation loc);
998
1000 mlir::Location loc, Address baseAddr, const CXXRecordDecl *derived,
1001 llvm::iterator_range<CastExpr::path_const_iterator> path,
1002 bool nullCheckValue);
1003
1004 /// Return the VTT parameter that should be passed to a base
1005 /// constructor/destructor with virtual bases.
1006 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
1007 /// to ItaniumCXXABI.cpp together with all the references to VTT.
1008 mlir::Value getVTTParameter(GlobalDecl gd, bool forVirtualBase,
1009 bool delegating);
1010
1013 return makeAddrLValue(addr, ty, LValueBaseInfo(source));
1014 }
1015
1017 return LValue::makeAddr(addr, ty, baseInfo);
1018 }
1019
1020 void initializeVTablePointers(mlir::Location loc,
1021 const clang::CXXRecordDecl *rd);
1022 void initializeVTablePointer(mlir::Location loc, const VPtr &vptr);
1023
1025
1026 /// Return the address of a local variable.
1028 auto it = localDeclMap.find(vd);
1029 assert(it != localDeclMap.end() &&
1030 "Invalid argument to getAddrOfLocalVar(), no decl!");
1031 return it->second;
1032 }
1033
1035 mlir::Type fieldType, unsigned index);
1036
1037 /// Given an opaque value expression, return its LValue mapping if it exists,
1038 /// otherwise create one.
1040
1041 /// Given an opaque value expression, return its RValue mapping if it exists,
1042 /// otherwise create one.
1044
1045 /// Load the value for 'this'. This function is only valid while generating
1046 /// code for an C++ member function.
1047 /// FIXME(cir): this should return a mlir::Value!
1048 mlir::Value loadCXXThis() {
1049 assert(cxxThisValue && "no 'this' value for this function");
1050 return cxxThisValue;
1051 }
1053
1054 /// Load the VTT parameter to base constructors/destructors have virtual
1055 /// bases. FIXME: Every place that calls LoadCXXVTT is something that needs to
1056 /// be abstracted properly.
1057 mlir::Value loadCXXVTT() {
1058 assert(cxxStructorImplicitParamValue && "no VTT value for this function");
1060 }
1061
1062 /// Convert the given pointer to a complete class to the given direct base.
1064 Address value,
1065 const CXXRecordDecl *derived,
1066 const CXXRecordDecl *base,
1067 bool baseIsVirtual);
1068
1069 /// Determine whether a return value slot may overlap some other object.
1071 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
1072 // class subobjects. These cases may need to be revisited depending on the
1073 // resolution of the relevant core issue.
1075 }
1076
1077 /// Determine whether a base class initialization may overlap some other
1078 /// object.
1080 const CXXRecordDecl *baseRD,
1081 bool isVirtual);
1082
1083 /// Return a CIR constant for an undefined value of \p cirTy.
1084 mlir::Value getUndefConstant(mlir::Location loc, mlir::Type cirTy);
1085
1086 /// Get an appropriate 'undef' rvalue for the given type.
1088
1089 cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn,
1090 cir::FuncType funcType);
1091
1093 FunctionArgList &args);
1094
1095 /// Emit the function prologue: declare function arguments in the symbol
1096 /// table.
1097 void emitFunctionProlog(const FunctionArgList &args, mlir::Block *entryBB,
1098 const FunctionDecl *fd, SourceLocation bodyBeginLoc);
1099
1100 /// Emit code for the start of a function.
1101 /// \param loc The location to be associated with the function.
1102 /// \param startLoc The location of the function body.
1104 cir::FuncOp fn, cir::FuncType funcType,
1106 clang::SourceLocation startLoc);
1107
1108 /// returns true if aggregate type has a volatile member.
1110 if (const auto *rd = t->getAsRecordDecl())
1111 return rd->hasVolatileMember();
1112 return false;
1113 }
1114
1115 void addCatchHandlerAttr(const CXXCatchStmt *catchStmt,
1116 SmallVector<mlir::Attribute> &handlerAttrs);
1117
1118 /// The cleanup depth enclosing all the cleanups associated with the
1119 /// parameters.
1121
1123
1124 /// Takes the old cleanup stack size and emits the cleanup blocks
1125 /// that have been added.
1126 void popCleanupBlocks(EHScopeStack::stable_iterator oldCleanupStackDepth,
1127 ArrayRef<mlir::Value *> valuesToReload = {});
1128
1129 /// Pops cleanup blocks until the given savepoint is reached, then adds the
1130 /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
1131 void popCleanupBlocks(EHScopeStack::stable_iterator oldCleanupStackDepth,
1132 size_t oldLifetimeExtendedSize,
1133 ArrayRef<mlir::Value *> valuesToReload = {});
1134 void popCleanupBlock(bool forDeactivation = false);
1135
1136 /// Emit the cleanups captured for a loop's condition variable (those pushed
1137 /// above \p depth while EHScopeStack was capturing condition cleanups) at
1138 /// the current insertion point, which must be inside the loop op's cleanup
1139 /// region, and pop them off the EH stack.
1140 void emitLoopConditionCleanups(EHScopeStack::stable_iterator depth,
1141 mlir::Location loc);
1142
1143 void terminateStructuredRegionBody(mlir::Region &r, mlir::Location loc);
1144
1145 /// Deactivates the given cleanup block. The block cannot be reactivated. Pops
1146 /// it if it's the top of the stack.
1147 ///
1148 /// \param DominatingIP - An instruction which is known to
1149 /// dominate the current IP (if set) and which lies along
1150 /// all paths of execution between the current IP and the
1151 /// the point at which the cleanup comes into scope.
1152 void deactivateCleanupBlock(EHScopeStack::stable_iterator cleanup,
1153 mlir::Operation *dominatingIP);
1154
1155 /// Create an active flag variable for use with conditional cleanups. The
1156 /// flag is initialized to false before the outermost conditional and set to
1157 /// true at the current insertion point (inside the conditional branch).
1158 Address createCleanupActiveFlag();
1159
1160 /// Set up the last cleanup that was pushed as a conditional
1161 /// full-expression cleanup.
1162 void initFullExprCleanup();
1163 void initFullExprCleanupWithFlag(Address activeFlag);
1164
1165 /// Promote a single pending cleanup entry onto the EH scope stack. If the
1166 /// entry has a valid activeFlag, the cleanup is configured as conditional.
1167 /// Defined in CIRGenDecl.cpp where the concrete cleanup types are visible.
1168 void pushPendingCleanupToEHStack(const PendingCleanupEntry &entry);
1169
1170 /// Push a cleanup to be run at the end of the current full-expression. Safe
1171 /// against the possibility that we're currently inside a
1172 /// conditionally-evaluated expression.
1173 template <class T, class... As>
1175 if (!isInConditionalBranch())
1176 return ehStack.pushCleanup<T>(kind, a...);
1177
1178 // Defer the cleanup until the FullExprCleanupScope exits. We can't push
1179 // to the EH stack now because the ternary's inner LexicalScope would pop
1180 // it prematurely.
1181 Address activeFlag = createCleanupActiveFlag();
1183 PendingCleanupEntry{kind, a..., activeFlag});
1184 }
1185
1186 /// Push a cleanup and record it for deferred deactivation. The cleanup will
1187 /// be deactivated when the enclosing CleanupDeactivationScope exits.
1188 template <class T, class... As>
1190 mlir::Location loc = builder.getUnknownLoc();
1191 mlir::Operation *dominatingIP = builder.getBool(false, loc).getOperation();
1192 ehStack.pushCleanup<T>(kind, a...);
1194 {ehStack.stable_begin(), dominatingIP});
1195 }
1196
1198 Address addr, QualType type);
1200 QualType type, Destroyer *destroyer,
1201 bool useEHCleanupForArray);
1202
1203 /// Queue a cleanup to be pushed after finishing the current full-expression.
1204 /// When the enclosing RunCleanupsScope exits, popCleanupBlocks promotes these
1205 /// entries onto the EH scope stack for the enclosing scope.
1207 Destroyer *destroyer) {
1208 lifetimeExtendedCleanupStack.push_back({kind, addr, type, destroyer});
1209 }
1210
1211 /// Enters a new scope for capturing cleanups, all of which
1212 /// will be executed once the scope is exited.
1213 class RunCleanupsScope {
1214 EHScopeStack::stable_iterator cleanupStackDepth, oldCleanupStackDepth;
1215 size_t lifetimeExtendedCleanupStackSize;
1216 CleanupDeactivationScope deactivateCleanups;
1217
1218 protected:
1221
1222 private:
1223 RunCleanupsScope(const RunCleanupsScope &) = delete;
1224 void operator=(const RunCleanupsScope &) = delete;
1225
1226 protected:
1228
1229 public:
1230 /// Enter a new cleanup scope.
1232 : deactivateCleanups(cgf), performCleanup(true), cgf(cgf) {
1233 cleanupStackDepth = cgf.ehStack.stable_begin();
1234 lifetimeExtendedCleanupStackSize =
1235 cgf.lifetimeExtendedCleanupStack.size();
1236 oldDidCallStackSave = cgf.didCallStackSave;
1237 cgf.didCallStackSave = false;
1238 oldCleanupStackDepth = cgf.currentCleanupStackDepth;
1239 cgf.currentCleanupStackDepth = cleanupStackDepth;
1240 }
1241
1242 /// Exit this cleanup scope, emitting any accumulated cleanups.
1244 if (performCleanup)
1245 forceCleanup();
1246 }
1247
1248 /// Force the emission of cleanups now, instead of waiting
1249 /// until this object is destroyed.
1250 void forceCleanup(ArrayRef<mlir::Value *> valuesToReload = {}) {
1251 assert(performCleanup && "Already forced cleanup");
1253
1254 // forceDeactivate() can pop cleanup scopes that were pushed with
1255 // deferred deactivation, which moves the insertion point out of the
1256 // cleanup body region. Any caller value defined inside such a body
1257 // would no longer dominate uses past the scope. The downstream
1258 // popCleanupBlocks() handles the spill for any cleanups it pops
1259 // itself, but it cannot help with cleanups that forceDeactivate has
1260 // already popped. Spill those values here, while the insertion point
1261 // is still inside the body, so we can reload them after all popping
1262 // is done. We only spill values whose defining op lives inside a
1263 // cir.cleanup.scope, since values defined outside any cleanup scope
1264 // (e.g. allocas in the entry block) already dominate the post-scope
1265 // insertion point.
1266 const bool hasPendingDeactivations =
1268 deactivateCleanups.oldDeactivateCleanupStackSize;
1269
1270 llvm::SmallVector<Address> tempAllocas;
1271 bool didSpillAny = false;
1272 if (hasPendingDeactivations) {
1273 tempAllocas.reserve(valuesToReload.size());
1274 for (mlir::Value *valPtr : valuesToReload) {
1275 mlir::Value val = *valPtr;
1276 if (!val || !val.getDefiningOp() ||
1277 !val.getDefiningOp()->getParentOfType<cir::CleanupScopeOp>()) {
1278 tempAllocas.push_back(Address::invalid());
1279 continue;
1280 }
1282 val.getType(), val.getLoc(), "tmp.exprcleanup");
1283 tempAllocas.push_back(temp);
1284 cgf.builder.createStore(val.getLoc(), val, temp);
1285 didSpillAny = true;
1286 }
1287 }
1288
1289 deactivateCleanups.forceDeactivate();
1290 // If we already spilled some of the caller's values, don't ask
1291 // popCleanupBlocks to spill them again. Values we did not pre-spill
1292 // are not inside any cir.cleanup.scope, so they cannot be invalidated
1293 // by either forceDeactivate's or popCleanupBlocks's pops (both only
1294 // pop cir.cleanup.scope ops); they already dominate the post-scope
1295 // insertion point on their own.
1296 if (didSpillAny) {
1297 cgf.popCleanupBlocks(cleanupStackDepth,
1298 lifetimeExtendedCleanupStackSize);
1299
1300 // Reload the spilled values now that all cleanup popping (and
1301 // promotion of any lifetime-extended cleanups onto the EH stack) is
1302 // done.
1303 for (auto [addr, valPtr] : llvm::zip(tempAllocas, valuesToReload)) {
1304 if (!addr.isValid())
1305 continue;
1306 *valPtr = cgf.builder.createLoad(valPtr->getLoc(), addr);
1307 }
1308 } else {
1309 cgf.popCleanupBlocks(cleanupStackDepth,
1310 lifetimeExtendedCleanupStackSize, valuesToReload);
1311 }
1312
1313 performCleanup = false;
1314 cgf.currentCleanupStackDepth = oldCleanupStackDepth;
1315 }
1316
1317 /// Force the emission of EH cleanups now, but defer promoting any
1318 /// lifetime-extended cleanup entries onto the EH scope stack. The caller
1319 /// must subsequently call forceLifetimeExtendedCleanups() to finalize the
1320 /// scope.
1322 assert(performCleanup && "Already forced cleanup");
1323 cgf.didCallStackSave = oldDidCallStackSave;
1324 deactivateCleanups.forceDeactivate();
1325 cgf.popCleanupBlocks(cleanupStackDepth);
1326 }
1327
1328 /// Promote any pending lifetime-extended cleanup entries onto the EH scope
1329 /// stack at the current insertion point and finalize this scope. This must
1330 /// be paired with a prior call to forceCleanupExceptLifetimeExtended().
1332 assert(performCleanup && "Already forced cleanup");
1333 assert(deactivateCleanups.deactivated &&
1334 "forceCleanupExceptLifetimeExtended() must be called first");
1335 cgf.popCleanupBlocks(cleanupStackDepth, lifetimeExtendedCleanupStackSize);
1336 performCleanup = false;
1337 cgf.currentCleanupStackDepth = oldCleanupStackDepth;
1338 }
1339
1340 /// Whether there are any pending cleanups that have been pushed since
1341 /// this scope was entered.
1342 bool hasPendingCleanups() const {
1343 return cgf.ehStack.stable_begin() != cleanupStackDepth;
1344 }
1345 };
1346
1347 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
1349
1351 CIRGenFunction &cgf;
1352 RunCleanupsScope cleanups;
1353 cir::CleanupScopeOp scope;
1354 size_t deferredCleanupStackSize;
1355 bool exited = false;
1356
1357 public:
1358 FullExprCleanupScope(CIRGenFunction &cgf, const Expr *subExpr);
1359
1360 void exit(ArrayRef<mlir::Value *> valuesToReload = {});
1361
1363 if (!exited)
1364 exit();
1365 }
1366
1367 private:
1369 void operator=(const FullExprCleanupScope &) = delete;
1370 };
1371
1372 /// Captures cleanups for a loop's condition variable so that they can be
1373 /// emitted into the loop op's per-iteration cleanup region.
1375 CIRGenFunction &cgf;
1377 bool active;
1378
1379 public:
1381 : cgf(cgf), depth(cgf.ehStack.stable_begin()), active(active) {}
1382
1383 /// An RAII class that suppresses cir.cleanup.scope creation for cleanups
1384 /// pushed onto the EH stack while a loop condition variable is being
1385 /// emitted and instead captures these cleanups so that they can be emitted
1386 /// into the loop op's cleanup region after the condition region is built.
1388 EHScopeStack &ehStack;
1389
1390 public:
1392 : ehStack(scope.cgf.ehStack) {
1393 // Capture scopes deliberately wrap individual cleanup-producing
1394 // operations, so they must never nest.
1395 assert(!ehStack.isCapturingLoopConditionCleanups() &&
1396 "loop condition cleanup capturing should not nest");
1397 if (scope.active)
1398 ehStack.setCapturingLoopConditionCleanups(true);
1399 }
1400 ~CaptureScope() { ehStack.setCapturingLoopConditionCleanups(false); }
1401
1402 CaptureScope(const CaptureScope &) = delete;
1403 void operator=(const CaptureScope &) = delete;
1404 };
1405
1406 /// Emit the captured condition-variable cleanups into the current insertion
1407 /// point (the loop's cleanup region).
1408 void emitIntoLoopCleanupRegion(mlir::Location loc) {
1409 if (active)
1410 cgf.emitLoopConditionCleanups(depth, loc);
1411 }
1412
1413 private:
1415 void operator=(const DeferredLoopConditionCleanup &) = delete;
1416 };
1417
1418public:
1419 /// Represents a scope, including function bodies, compound statements, and
1420 /// the substatements of if/while/do/for/switch/try statements. This class
1421 /// handles any automatic cleanup, along with the return value.
1422 struct LexicalScope : public RunCleanupsScope {
1423 private:
1424 // Points to the scope entry block. This is useful, for instance, for
1425 // helping to insert allocas before finalizing any recursive CodeGen from
1426 // switches.
1427 mlir::Block *entryBlock;
1428
1429 LexicalScope *parentScope = nullptr;
1430
1431 // Holds the actual value for ScopeKind::Try
1432 cir::TryOp tryOp = nullptr;
1433
1434 // On a coroutine body, the OnFallthrough sub stmt holds the handler
1435 // (CoreturnStmt) for control flow falling off the body. Keep track
1436 // of emitted co_return in this scope and allow OnFallthrough to be
1437 // skipeed.
1438 bool hasCoreturnStmt = false;
1439
1440 // Only Regular is used at the moment. Support for other kinds will be
1441 // added as the relevant statements/expressions are upstreamed.
1442 enum Kind {
1443 Regular, // cir.if, cir.scope, if_regions
1444 Ternary, // cir.ternary
1445 Switch, // cir.switch
1446 Try, // cir.try
1447 GlobalInit // cir.global initialization code
1448 };
1449 Kind scopeKind = Kind::Regular;
1450
1451 // The scope return value.
1452 mlir::Value retVal = nullptr;
1453
1454 mlir::Location beginLoc;
1455 mlir::Location endLoc;
1456
1457 public:
1458 unsigned depth = 0;
1459
1460 LexicalScope(CIRGenFunction &cgf, mlir::Location loc, mlir::Block *eb)
1461 : RunCleanupsScope(cgf), entryBlock(eb), parentScope(cgf.curLexScope),
1462 beginLoc(loc), endLoc(loc) {
1463
1464 assert(entryBlock && "LexicalScope requires an entry block");
1465 cgf.curLexScope = this;
1466 if (parentScope)
1467 ++depth;
1468
1469 if (const auto fusedLoc = mlir::dyn_cast<mlir::FusedLoc>(loc)) {
1470 assert(fusedLoc.getLocations().size() == 2 && "too many locations");
1471 beginLoc = fusedLoc.getLocations()[0];
1472 endLoc = fusedLoc.getLocations()[1];
1473 }
1474 }
1475
1476 void setRetVal(mlir::Value v) { retVal = v; }
1477
1478 void cleanup();
1479 void restore() { cgf.curLexScope = parentScope; }
1480
1483 cleanup();
1484 restore();
1485 }
1486
1487 // ---
1488 // Coroutine tracking
1489 // ---
1490 bool hasCoreturn() const { return hasCoreturnStmt; }
1491 void setCoreturn() { hasCoreturnStmt = true; }
1492
1493 // ---
1494 // Kind
1495 // ---
1496 bool isGlobalInit() { return scopeKind == Kind::GlobalInit; }
1497 bool isRegular() { return scopeKind == Kind::Regular; }
1498 bool isSwitch() { return scopeKind == Kind::Switch; }
1499 bool isTernary() { return scopeKind == Kind::Ternary; }
1500 bool isTry() { return scopeKind == Kind::Try; }
1501 cir::TryOp getClosestTryParent();
1502 void setAsGlobalInit() { scopeKind = Kind::GlobalInit; }
1503 void setAsSwitch() { scopeKind = Kind::Switch; }
1504 void setAsTernary() { scopeKind = Kind::Ternary; }
1505 void setAsTry(cir::TryOp op) {
1506 scopeKind = Kind::Try;
1507 tryOp = op;
1508 }
1509
1510 cir::TryOp getTry() {
1511 assert(isTry());
1512 return tryOp;
1513 }
1514
1515 // ---
1516 // Return handling.
1517 // ---
1518
1519 private:
1520 // On switches we need one return block per region, since cases don't
1521 // have their own scopes but are distinct regions nonetheless.
1522
1523 // TODO: This implementation should change once we have support for early
1524 // exits in MLIR structured control flow (llvm-project#161575)
1526 llvm::DenseMap<mlir::Block *, mlir::Location> retLocs;
1527 llvm::DenseMap<cir::CaseOp, unsigned> retBlockInCaseIndex;
1528 std::optional<unsigned> normalRetBlockIndex;
1529
1530 // There's usually only one ret block per scope, but this needs to be
1531 // get or create because of potential unreachable return statements, note
1532 // that for those, all source location maps to the first one found.
1533 mlir::Block *createRetBlock(CIRGenFunction &cgf, mlir::Location loc) {
1534 assert((isa_and_nonnull<cir::CaseOp>(
1535 cgf.builder.getBlock()->getParentOp()) ||
1536 retBlocks.size() == 0) &&
1537 "only switches can hold more than one ret block");
1538
1539 // Create the return block but don't hook it up just yet.
1540 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
1541 auto *b = cgf.builder.createBlock(cgf.builder.getBlock()->getParent());
1542 retBlocks.push_back(b);
1543 updateRetLoc(b, loc);
1544 return b;
1545 }
1546
1547 cir::ReturnOp emitReturn(mlir::Location loc);
1548 void emitImplicitReturn();
1549
1550 public:
1552 mlir::Location getRetLoc(mlir::Block *b) { return retLocs.at(b); }
1553 void updateRetLoc(mlir::Block *b, mlir::Location loc) {
1554 retLocs.insert_or_assign(b, loc);
1555 }
1556
1557 mlir::Block *getOrCreateRetBlock(CIRGenFunction &cgf, mlir::Location loc) {
1558 // Check if we're inside a case region
1559 if (auto caseOp = mlir::dyn_cast_if_present<cir::CaseOp>(
1560 cgf.builder.getBlock()->getParentOp())) {
1561 auto iter = retBlockInCaseIndex.find(caseOp);
1562 if (iter != retBlockInCaseIndex.end()) {
1563 // Reuse existing return block
1564 mlir::Block *ret = retBlocks[iter->second];
1565 updateRetLoc(ret, loc);
1566 return ret;
1567 }
1568 // Create new return block
1569 mlir::Block *ret = createRetBlock(cgf, loc);
1570 retBlockInCaseIndex[caseOp] = retBlocks.size() - 1;
1571 return ret;
1572 }
1573
1574 if (normalRetBlockIndex) {
1575 mlir::Block *ret = retBlocks[*normalRetBlockIndex];
1576 updateRetLoc(ret, loc);
1577 return ret;
1578 }
1579
1580 mlir::Block *ret = createRetBlock(cgf, loc);
1581 normalRetBlockIndex = retBlocks.size() - 1;
1582 return ret;
1583 }
1584
1585 mlir::Block *getEntryBlock() { return entryBlock; }
1586 };
1587
1589
1591
1593 QualType type);
1594
1595 void pushDestroy(QualType::DestructionKind dtorKind, Address addr,
1596 QualType type);
1597
1599 Destroyer *destroyer);
1600
1602 QualType type, Destroyer *destroyer,
1603 bool useEHCleanupForArray);
1604
1606
1607 void pushIrregularPartialArrayCleanup(mlir::Value arrayBegin,
1608 Address arrayEndPointer,
1609 QualType elementType,
1610 CharUnits elementAlign,
1611 Destroyer *destroyer);
1612
1613 /// Start generating a thunk function.
1614 void startThunk(cir::FuncOp fn, GlobalDecl gd,
1615 const CIRGenFunctionInfo &fnInfo, bool isUnprototyped);
1616
1617 /// Finish generating a thunk function.
1618 void finishThunk();
1619
1620 /// Generate code for a thunk function.
1621 void generateThunk(cir::FuncOp fn, const CIRGenFunctionInfo &fnInfo,
1622 GlobalDecl gd, const ThunkInfo &thunk,
1623 bool isUnprototyped);
1624
1625 /// ----------------------
1626 /// CIR emit functions
1627 /// ----------------------
1628public:
1629 bool getAArch64SVEProcessedOperands(unsigned builtinID, const CallExpr *expr,
1631 clang::SVETypeFlags typeFlags);
1632 mlir::Value emitSVEPredicateCast(mlir::Value pred, unsigned minNumElts,
1633 mlir::Location loc);
1634 std::optional<mlir::Value>
1635 emitAArch64BuiltinExpr(unsigned builtinID, const CallExpr *expr,
1637 llvm::Triple::ArchType arch);
1638 std::optional<mlir::Value> emitAArch64SMEBuiltinExpr(unsigned builtinID,
1639 const CallExpr *expr);
1640 std::optional<mlir::Value> emitAArch64SVEBuiltinExpr(unsigned builtinID,
1641 const CallExpr *expr);
1642
1643 mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, QualType ty,
1644 SourceLocation loc,
1645 SourceLocation assumptionLoc,
1646 int64_t alignment,
1647 mlir::Value offsetValue = nullptr);
1648
1649 mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, const Expr *expr,
1650 SourceLocation assumptionLoc,
1651 int64_t alignment,
1652 mlir::Value offsetValue = nullptr);
1653
1654 bool emitLifetimeStartOp(mlir::Location loc, mlir::Value addr);
1655 void emitLifetimeEndOp(mlir::Location loc, mlir::Value addr);
1656
1657private:
1658 void emitAndUpdateRetAlloca(clang::QualType type, mlir::Location loc,
1659 clang::CharUnits alignment);
1660
1661 CIRGenCallee emitDirectCallee(const GlobalDecl &gd);
1662
1663public:
1665 llvm::StringRef fieldName,
1666 unsigned fieldIndex);
1667
1668 mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty,
1669 mlir::Location loc, clang::CharUnits alignment,
1670 bool insertIntoFnEntryBlock,
1671 mlir::Value arraySize = nullptr);
1672 mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty,
1673 mlir::Location loc, clang::CharUnits alignment,
1674 mlir::OpBuilder::InsertPoint ip,
1675 mlir::Value arraySize = nullptr);
1676
1677 void emitAggregateStore(mlir::Value value, Address dest);
1678
1679 void emitAggExpr(const clang::Expr *e, AggValueSlot slot);
1680
1682
1684
1685 /// Emit an aggregate copy.
1686 ///
1687 /// \param isVolatile \c true iff either the source or the destination is
1688 /// volatile.
1689 /// \param MayOverlap Whether the tail padding of the destination might be
1690 /// occupied by some other object. More efficient code can often be
1691 /// generated if not.
1692 void emitAggregateCopy(LValue dest, LValue src, QualType eltTy,
1693 AggValueSlot::Overlap_t mayOverlap,
1694 bool isVolatile = false);
1695
1696 /// Emit code to compute the specified expression which can have any type. The
1697 /// result is returned as an RValue struct. If this is an aggregate
1698 /// expression, the aggloc/agglocvolatile arguments indicate where the result
1699 /// should be returned.
1702 bool ignoreResult = false);
1703
1704 /// Emits the code necessary to evaluate an arbitrary expression into the
1705 /// given memory location.
1706 void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals,
1707 bool isInitializer);
1708
1709 /// Similarly to emitAnyExpr(), however, the result will always be accessible
1710 /// even if no aggregate location is provided.
1712
1713 void emitAnyExprToExn(const Expr *e, Address addr);
1714
1715 void emitArrayDestroy(mlir::Value begin, mlir::Value numElements,
1716 QualType elementType, CharUnits elementAlign,
1717 Destroyer *destroyer);
1718
1719 mlir::Value emitArrayLength(const clang::ArrayType *arrayType,
1720 QualType &baseType, Address &addr);
1723
1725
1727 LValueBaseInfo *baseInfo = nullptr);
1728
1729 std::pair<mlir::Value, mlir::Type>
1731 QualType inputType, std::string &constraintString,
1732 SourceLocation loc);
1733 std::pair<mlir::Value, mlir::Type>
1734 emitAsmInput(const TargetInfo::ConstraintInfo &info, const Expr *inputExpr,
1735 std::string &constraintString);
1736 mlir::LogicalResult emitAsmStmt(const clang::AsmStmt &s);
1737
1739 void emitAtomicInit(Expr *init, LValue dest);
1740 void emitAtomicStore(RValue rvalue, LValue dest, bool isInit);
1741 void emitAtomicStore(RValue rvalue, LValue dest, cir::MemOrder order,
1742 bool isVolatile, bool isInit);
1744 const Expr *memOrder, bool isStore, bool isLoad, bool isFence,
1745 llvm::function_ref<void(cir::MemOrder)> emitAtomicOp);
1746
1747 mlir::Value makeBinaryAtomicValue(
1748 cir::AtomicFetchKind kind, const clang::CallExpr *expr,
1749 mlir::Type *originalArgType = nullptr,
1750 mlir::Value *emittedArgValue = nullptr,
1751 cir::MemOrder ordering = cir::MemOrder::SequentiallyConsistent);
1752
1753 mlir::LogicalResult emitAttributedStmt(const AttributedStmt &s);
1754
1755 AutoVarEmission emitAutoVarAlloca(const clang::VarDecl &d,
1756 mlir::OpBuilder::InsertPoint ip = {});
1757
1759 AggValueSlot slot = AggValueSlot::ignored());
1761
1762 /// Emit code and set up symbol table for a variable declaration with auto,
1763 /// register, or no storage class specifier. These turn into simple stack
1764 /// objects, globals depending on target.
1765 void emitAutoVarDecl(const clang::VarDecl &d);
1766
1767 void emitAutoVarCleanups(const AutoVarEmission &emission);
1768
1769 /// Emit a loop's condition-variable declaration. This needs special handling
1770 /// so that we can manage per-iteration cleanups for the loop condition.
1772 DeferredLoopConditionCleanup &condCleanup);
1773
1774 /// Emit the initializer for an allocated variable. If this call is not
1775 /// associated with the call to emitAutoVarAlloca (as the address of the
1776 /// emission is not directly an alloca), the allocatedSeparately parameter can
1777 /// be used to suppress the assertions. However, this should only be used in
1778 /// extreme cases, as it doesn't properly reflect the language/AST.
1779 void emitAutoVarInit(const AutoVarEmission &emission);
1780 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
1782
1783 void maybeEmitDeferredVarDeclInit(const VarDecl *vd);
1784
1785 void emitBaseInitializer(mlir::Location loc, const CXXRecordDecl *classDecl,
1786 CXXCtorInitializer *baseInit);
1787
1789
1790 mlir::LogicalResult emitBreakStmt(const clang::BreakStmt &s);
1791
1792 RValue emitBuiltinExpr(const clang::GlobalDecl &gd, unsigned builtinID,
1793 const clang::CallExpr *e, ReturnValueSlot returnValue);
1794
1795 /// Returns a Value corresponding to the size of the given expression by
1796 /// emitting a `cir.objsize` operation.
1797 ///
1798 /// \param e The expression whose object size to compute
1799 /// \param type Determines the semantics of the object size computation.
1800 /// The type parameter is a 2-bit value where:
1801 /// bit 0 (type & 1): 0 = whole object, 1 = closest subobject
1802 /// bit 1 (type & 2): 0 = maximum size, 2 = minimum size
1803 /// \param resType The result type for the size value
1804 /// \param emittedE Optional pre-emitted pointer value. If non-null, we'll
1805 /// call `cir.objsize` on this value rather than emitting e.
1806 /// \param isDynamic If true, allows runtime evaluation via dynamic mode
1807 mlir::Value emitBuiltinObjectSize(const clang::Expr *e, unsigned type,
1808 cir::IntType resType, mlir::Value emittedE,
1809 bool isDynamic);
1810
1811 mlir::Value evaluateOrEmitBuiltinObjectSize(const clang::Expr *e,
1812 unsigned type,
1813 cir::IntType resType,
1814 mlir::Value emittedE,
1815 bool isDynamic);
1816
1817 int64_t getAccessedFieldNo(unsigned idx, mlir::ArrayAttr elts);
1818
1819 /// Emit a simple LLVM intrinsic that takes N scalar arguments. The intrinsic
1820 /// name is used verbatim; any overload mangling (e.g. `.f32`, `.p1`) must be
1821 /// baked into \p intrinName by the caller. The result type defaults to the
1822 /// type of the first argument; pass \p resultType for intrinsics whose result
1823 /// differs from the operand, such as a vector reduction that returns the
1824 /// element type. Unlike classic CodeGen, CIR has no intrinsic registry to
1825 /// derive the result type from the operand, so it must be supplied here.
1826 template <unsigned N>
1827 [[maybe_unused]] RValue
1829 llvm::StringRef intrinName,
1830 mlir::Type resultType = {}) {
1831 static_assert(N, "expect non-empty argument");
1832 mlir::Type cirTy =
1833 resultType ? resultType : convertType(e->getArg(0)->getType());
1835 for (unsigned i = 0; i < N; ++i)
1836 args.push_back(emitScalarExpr(e->getArg(i)));
1837 const auto call = cir::LLVMIntrinsicCallOp::create(
1838 builder, getLoc(e->getExprLoc()), builder.getStringAttr(intrinName),
1839 cirTy, args);
1840 return RValue::get(call->getResult(0));
1841 }
1842
1843 RValue emitCall(const CIRGenFunctionInfo &funcInfo,
1844 const CIRGenCallee &callee, ReturnValueSlot returnValue,
1845 const CallArgList &args, cir::CIRCallOpInterface *callOp,
1846 bool isMustTail, mlir::Location loc);
1849 const CallArgList &args, bool isMustTail,
1850 cir::CIRCallOpInterface *callOrTryCall = nullptr) {
1851 assert(currSrcLoc && "source location must have been set");
1852 return emitCall(funcInfo, callee, returnValue, args, callOrTryCall,
1853 isMustTail, *currSrcLoc);
1854 }
1855
1856 RValue emitCall(clang::QualType calleeTy, const CIRGenCallee &callee,
1858
1859 /// Emit the call and return for a thunk function.
1860 void emitCallAndReturnForThunk(cir::FuncOp callee, const ThunkInfo *thunk,
1861 bool isUnprototyped);
1862
1863 void emitCallArg(CallArgList &args, const clang::Expr *e,
1864 clang::QualType argType);
1865 void emitCallArgs(
1866 CallArgList &args, PrototypeWrapper prototype,
1867 llvm::iterator_range<clang::CallExpr::const_arg_iterator> argRange,
1868 AbstractCallee callee = AbstractCallee(), unsigned paramsToSkip = 0);
1872
1876
1877 template <typename T>
1878 mlir::LogicalResult emitCaseDefaultCascade(const T *stmt, mlir::Type condType,
1879 mlir::ArrayAttr value,
1880 cir::CaseOpKind kind,
1881 bool buildingTopLevelCase);
1882
1884
1885 mlir::LogicalResult emitCaseStmt(const clang::CaseStmt &s,
1886 mlir::Type condType,
1887 bool buildingTopLevelCase);
1888
1889 LValue emitCastLValue(const CastExpr *e);
1890
1891 /// Emits an argument for a call to a `__builtin_assume`. If the builtin
1892 /// sanitizer is enabled, a runtime check is also emitted.
1893 mlir::Value emitCheckedArgForAssume(const Expr *e);
1894
1895 /// Emit a conversion from the specified complex type to the specified
1896 /// destination type, where the destination type is an LLVM scalar type.
1897 mlir::Value emitComplexToScalarConversion(mlir::Value src, QualType srcTy,
1898 QualType dstTy, SourceLocation loc);
1899
1902
1904
1905 mlir::LogicalResult emitCoroutineBody(const CoroutineBodyStmt &s);
1906 cir::CoroEndOp emitCoroEndBuiltinCall(const CallExpr *e);
1907 cir::CoroIdOp emitCoroIDBuiltinCall(const CallExpr *e);
1908 cir::CoroAllocOp emitCoroAllocBuiltinCall(const CallExpr *e);
1909 cir::CoroBeginOp emitCoroBeginBuiltinCall(const CallExpr *e);
1910
1911 cir::CoroSizeOp emitCoroSizeBuiltinCall(const CallExpr *e);
1912 cir::CoroFreeOp emitCoroFreeBuiltin(const CallExpr *e);
1914
1915 void emitDestroy(Address addr, QualType type, Destroyer *destroyer);
1916
1918
1919 mlir::LogicalResult emitContinueStmt(const clang::ContinueStmt &s);
1920
1921 mlir::LogicalResult emitCoreturnStmt(const CoreturnStmt &s);
1922
1924 AggValueSlot dest);
1925
1928 Address arrayBegin, const CXXConstructExpr *e,
1929 bool newPointerIsChecked,
1930 bool zeroInitialize = false);
1932 mlir::Value numElements, Address arrayBase,
1933 const CXXConstructExpr *e,
1934 bool newPointerIsChecked, bool zeroInitialize,
1935 Address endOfInit);
1937 clang::CXXCtorType type, bool forVirtualBase,
1938 bool delegating, AggValueSlot thisAVS,
1939 const clang::CXXConstructExpr *e);
1940
1942 clang::CXXCtorType type, bool forVirtualBase,
1943 bool delegating, Address thisAddr,
1945
1947 bool forVirtualBase, Address thisAddr,
1948 bool inheritedFromVBase,
1949 const CXXInheritedCtorInitExpr *e);
1950
1952 SourceLocation loc, const CXXConstructorDecl *d, CXXCtorType ctorType,
1953 bool forVirtualBase, bool delegating, CallArgList &args);
1954
1955 void emitCXXDeleteExpr(const CXXDeleteExpr *e);
1956
1958 bool forVirtualBase, bool delegating,
1959 Address thisAddr, QualType thisTy);
1960
1962 mlir::Value thisVal, QualType thisTy,
1963 mlir::Value implicitParam,
1964 QualType implicitParamTy, const CallExpr *e);
1965
1966 mlir::LogicalResult emitCXXForRangeStmt(const CXXForRangeStmt &s,
1968
1971
1973 const Expr *e, Address base, mlir::Value memberPtr,
1974 const MemberPointerType *memberPtrType, LValueBaseInfo *baseInfo);
1975
1977 const clang::CXXMethodDecl *md, const CIRGenCallee &callee,
1978 ReturnValueSlot returnValue, mlir::Value thisPtr,
1979 mlir::Value implicitParam, clang::QualType implicitParamTy,
1980 const clang::CallExpr *ce, CallArgList *rtlArgs);
1981
1983 const clang::CallExpr *ce, const clang::CXXMethodDecl *md,
1984 ReturnValueSlot returnValue, bool hasQualifier,
1985 clang::NestedNameSpecifier qualifier, bool isArrow,
1986 const clang::Expr *base);
1987
1990
1991 mlir::Value emitCXXNewExpr(const CXXNewExpr *e);
1992
1993 void emitNewArrayInitializer(const CXXNewExpr *e, QualType elementType,
1994 mlir::Type elementTy, Address beginPtr,
1995 mlir::Value numElements,
1996 mlir::Value allocSizeWithoutCookie);
1997
1998 /// Create a check for a function parameter that may potentially be
1999 /// declared as non-null.
2000 void emitNonNullArgCheck(RValue rv, QualType argType, SourceLocation argLoc,
2001 AbstractCallee ac, unsigned paramNum);
2002
2004 const CXXMethodDecl *md,
2006
2009
2011
2013 const CallExpr *callExpr,
2015
2016 void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType,
2017 Address ptr);
2018
2019 void emitCXXThrowExpr(const CXXThrowExpr *e);
2020
2022 virtual mlir::LogicalResult operator()(CIRGenFunction &cgf) = 0;
2023 virtual ~cxxTryBodyEmitter() = default;
2024 };
2025
2026 void emitBeginCatch(const CXXCatchStmt *catchStmt, mlir::Value ehToken);
2027
2028 mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s,
2029 cxxTryBodyEmitter &bodyCallback);
2030 mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s);
2031
2033 clang::CXXCtorType ctorType, FunctionArgList &args);
2034
2035 // It's important not to confuse this and emitDelegateCXXConstructorCall.
2036 // Delegating constructors are the C++11 feature. The constructor delegate
2037 // optimization is used to reduce duplication in the base and complete
2038 // constructors where they are substantially the same.
2040 const FunctionArgList &args);
2041
2042 void emitDeleteCall(const FunctionDecl *deleteFD, mlir::Value ptr,
2043 QualType deleteTy);
2044
2045 mlir::LogicalResult emitDoStmt(const clang::DoStmt &s);
2046
2047 mlir::Value emitCXXTypeidExpr(const CXXTypeidExpr *e);
2048 mlir::Value emitDynamicCast(Address thisAddr, const CXXDynamicCastExpr *dce);
2049
2050 /// Emit an expression as an initializer for an object (variable, field, etc.)
2051 /// at the given location. The expression is not necessarily the normal
2052 /// initializer for the object, and the address is not necessarily
2053 /// its normal location.
2054 ///
2055 /// \param init the initializing expression
2056 /// \param d the object to act as if we're initializing
2057 /// \param lvalue the lvalue to initialize
2058 /// \param capturedByInit true if \p d is a __block variable whose address is
2059 /// potentially changed by the initializer
2060 void emitExprAsInit(const clang::Expr *init, const clang::ValueDecl *d,
2061 LValue lvalue, bool capturedByInit = false);
2062
2063 mlir::LogicalResult emitFunctionBody(const clang::Stmt *body);
2064
2065 mlir::LogicalResult emitGotoStmt(const clang::GotoStmt &s);
2066
2067 mlir::LogicalResult emitIndirectGotoStmt(const IndirectGotoStmt &s);
2068
2070
2072 clang::Expr *init);
2073
2075
2076 mlir::Value emitPromotedComplexExpr(const Expr *e, QualType promotionType);
2077
2078 mlir::Value emitPromotedScalarExpr(const Expr *e, QualType promotionType);
2079
2080 mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType);
2081
2082 void emitReturnOfRValue(mlir::Location loc, RValue rv, QualType ty);
2083
2084 mlir::Value emitRuntimeCall(mlir::Location loc, cir::FuncOp callee,
2086 mlir::NamedAttrList attrs = {});
2087
2088 void emitInvariantStart(CharUnits size, mlir::Value addr, mlir::Location loc);
2089
2090 /// Emit the computation of the specified expression of scalar type.
2091 mlir::Value emitScalarExpr(const clang::Expr *e,
2092 bool ignoreResultAssign = false);
2093
2094 mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv);
2095
2096 /// Build a debug stoppoint if we are emitting debug info.
2097 void emitStopPoint(const Stmt *s);
2098
2099 // Build CIR for a statement. useCurrentScope should be true if no
2100 // new scopes need be created when finding a compound statement.
2101 mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope,
2102 llvm::ArrayRef<const Attr *> attrs = {});
2103
2104 mlir::LogicalResult emitSimpleStmt(const clang::Stmt *s,
2105 bool useCurrentScope);
2106
2107 mlir::LogicalResult emitForStmt(const clang::ForStmt &s);
2108
2109 void emitForwardingCallToLambda(const CXXMethodDecl *lambdaCallOperator,
2110 CallArgList &callArgs);
2111
2112 RValue emitCoawaitExpr(const CoawaitExpr &e,
2113 AggValueSlot aggSlot = AggValueSlot::ignored(),
2114 bool ignoreResult = false);
2115
2116 RValue emitCoyieldExpr(const CoyieldExpr &e,
2117 AggValueSlot aggSlot = AggValueSlot::ignored(),
2118 bool ignoreResult = false);
2119 /// Emit the computation of the specified expression of complex type,
2120 /// returning the result.
2121 mlir::Value emitComplexExpr(const Expr *e);
2122
2123 void emitComplexExprIntoLValue(const Expr *e, LValue dest, bool isInit);
2124
2125 mlir::Value emitComplexPrePostIncDec(const UnaryOperator *e, LValue lv);
2126
2127 LValue emitComplexAssignmentLValue(const BinaryOperator *e);
2128 LValue emitComplexCompoundAssignmentLValue(const CompoundAssignOperator *e);
2129 LValue emitScalarCompoundAssignWithComplex(const CompoundAssignOperator *e,
2130 mlir::Value &result);
2131
2132 mlir::LogicalResult
2133 emitCompoundStmt(const clang::CompoundStmt &s, Address *lastValue = nullptr,
2134 AggValueSlot slot = AggValueSlot::ignored());
2135
2136 mlir::LogicalResult
2138 Address *lastValue = nullptr,
2139 AggValueSlot slot = AggValueSlot::ignored());
2140
2141 void emitDecl(const clang::Decl &d, bool evaluateConditionDecl = false);
2142 mlir::LogicalResult emitDeclStmt(const clang::DeclStmt &s);
2143 LValue emitDeclRefLValue(const clang::DeclRefExpr *e);
2144
2145 mlir::LogicalResult emitDefaultStmt(const clang::DefaultStmt &s,
2146 mlir::Type condType,
2147 bool buildingTopLevelCase);
2148
2150 clang::CXXCtorType ctorType,
2151 const FunctionArgList &args,
2153
2154 /// We are performing a delegate call; that is, the current function is
2155 /// delegating to another one. Produce a r-value suitable for passing the
2156 /// given parameter.
2157 void emitDelegateCallArg(CallArgList &args, const clang::VarDecl *param,
2159
2160 /// Emit an `if` on a boolean condition to the specified blocks.
2161 /// FIXME: Based on the condition, this might try to simplify the codegen of
2162 /// the conditional based on the branch.
2163 /// In the future, we may apply code generation simplifications here,
2164 /// similar to those used in classic LLVM codegen
2165 /// See `EmitBranchOnBoolExpr` for inspiration.
2166 mlir::LogicalResult emitIfOnBoolExpr(const clang::Expr *cond,
2167 const clang::Stmt *thenS,
2168 const clang::Stmt *elseS);
2169 cir::IfOp emitIfOnBoolExpr(const clang::Expr *cond,
2170 BuilderCallbackRef thenBuilder,
2171 mlir::Location thenLoc,
2172 BuilderCallbackRef elseBuilder,
2173 std::optional<mlir::Location> elseLoc = {});
2174
2175 mlir::Value emitOpOnBoolExpr(mlir::Location loc, const clang::Expr *cond);
2176
2177 LValue emitPointerToDataMemberBinaryExpr(const BinaryOperator *e);
2178
2179 mlir::LogicalResult emitLabel(const clang::LabelDecl &d);
2180 mlir::LogicalResult emitLabelStmt(const clang::LabelStmt &s);
2181
2182 void emitLambdaDelegatingInvokeBody(const CXXMethodDecl *md);
2183 void emitLambdaStaticInvokeBody(const CXXMethodDecl *md);
2184
2185 mlir::LogicalResult emitIfStmt(const clang::IfStmt &s);
2186
2187 /// Emit code to compute the specified expression,
2188 /// ignoring the result.
2189 void emitIgnoredExpr(const clang::Expr *e);
2190
2191 RValue emitLoadOfBitfieldLValue(LValue lv, SourceLocation loc);
2192
2193 /// Load a complex number from the specified l-value.
2194 mlir::Value emitLoadOfComplex(LValue src, SourceLocation loc);
2195
2196 RValue emitLoadOfExtVectorElementLValue(LValue lv);
2197
2198 /// Given an expression that represents a value lvalue, this method emits
2199 /// the address of the lvalue, then loads the result as an rvalue,
2200 /// returning the rvalue.
2201 RValue emitLoadOfLValue(LValue lv, SourceLocation loc);
2202
2203 Address emitLoadOfReference(LValue refLVal, mlir::Location loc,
2204 LValueBaseInfo *pointeeBaseInfo);
2205 LValue emitLoadOfReferenceLValue(Address refAddr, mlir::Location loc,
2206 QualType refTy, AlignmentSource source);
2207
2208 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2209 /// care to appropriately convert from the memory representation to
2210 /// the LLVM value representation. The l-value must be a simple
2211 /// l-value.
2212 mlir::Value emitLoadOfScalar(LValue lvalue, SourceLocation loc);
2213 mlir::Value emitLoadOfScalar(Address addr, bool isVolatile, QualType ty,
2214 SourceLocation loc, LValueBaseInfo baseInfo,
2215 bool isNontemporal = false);
2216
2217 /// Emit code to compute a designator that specifies the location
2218 /// of the expression.
2219 /// FIXME: document this function better.
2220 LValue emitLValue(const clang::Expr *e);
2221 LValue emitLValueForBitField(LValue base, const FieldDecl *field);
2222 LValue emitLValueForField(LValue base, const clang::FieldDecl *field);
2223
2224 LValue emitLValueForLambdaField(const FieldDecl *field);
2225 LValue emitLValueForLambdaField(const FieldDecl *field,
2226 mlir::Value thisValue);
2227
2228 /// Like emitLValueForField, excpet that if the Field is a reference, this
2229 /// will return the address of the reference and not the address of the value
2230 /// stored in the reference.
2231 LValue emitLValueForFieldInitialization(LValue base,
2232 const clang::FieldDecl *field,
2233 llvm::StringRef fieldName);
2234
2235 LValue emitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e);
2236
2237 LValue emitMemberExpr(const MemberExpr *e);
2238
2239 /// Emit a musttail call for a thunk with a potentially different ABI.
2240 void emitMustTailThunk(GlobalDecl gd, mlir::Value adjustedThisPtr,
2241 cir::FuncOp callee);
2242
2243 /// Emit a call to an AMDGPU builtin function.
2244 std::optional<mlir::Value> emitAMDGPUBuiltinExpr(unsigned builtinID,
2245 const CallExpr *expr);
2246
2247 /// Emit a call to an NVPTX builtin function.
2248 std::optional<mlir::Value> emitNVPTXBuiltinExpr(unsigned builtinID,
2249 const CallExpr *expr);
2250
2251 /// Emit a device-side printf call for NVPTX targets.
2252 mlir::Value emitNVPTXDevicePrintfCallExpr(const CallExpr *expr);
2253
2254 LValue emitOpaqueValueLValue(const OpaqueValueExpr *e);
2255
2256 LValue emitConditionalOperatorLValue(const AbstractConditionalOperator *expr);
2257
2258 /// Given an expression with a pointer type, emit the value and compute our
2259 /// best estimate of the alignment of the pointee.
2260 ///
2261 /// One reasonable way to use this information is when there's a language
2262 /// guarantee that the pointer must be aligned to some stricter value, and
2263 /// we're simply trying to ensure that sufficiently obvious uses of under-
2264 /// aligned objects don't get miscompiled; for example, a placement new
2265 /// into the address of a local variable. In such a case, it's quite
2266 /// reasonable to just ignore the returned alignment when it isn't from an
2267 /// explicit source.
2268 Address emitPointerWithAlignment(const clang::Expr *expr,
2269 LValueBaseInfo *baseInfo = nullptr);
2270
2271 /// Emits a reference binding to the passed in expression.
2272 RValue emitReferenceBindingToExpr(const Expr *e);
2273
2274 mlir::LogicalResult emitReturnStmt(const clang::ReturnStmt &s);
2275
2276 RValue emitRotate(const CallExpr *e, bool isRotateLeft);
2277
2278 mlir::Value emitScalarConstant(const ConstantEmission &constant, Expr *e);
2279
2280 /// Emit a conversion from the specified type to the specified destination
2281 /// type, both of which are CIR scalar types.
2282 mlir::Value emitScalarConversion(mlir::Value src, clang::QualType srcType,
2283 clang::QualType dstType,
2284 clang::SourceLocation loc);
2285
2286 void emitScalarInit(const clang::Expr *init, mlir::Location loc,
2287 LValue lvalue, bool capturedByInit = false);
2288
2289 mlir::Value emitScalarOrConstFoldImmArg(unsigned iceArguments, unsigned idx,
2290 const Expr *argExpr);
2291
2292 void emitStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage);
2293
2294 /// Emit a guarded initializer for a static local variable.
2295 void emitCXXGuardedInit(const VarDecl &varDecl, cir::GlobalOp globalOp,
2296 bool performInit);
2297
2298 void emitStoreOfComplex(mlir::Location loc, mlir::Value v, LValue dest,
2299 bool isInit);
2300
2301 void emitStoreOfScalar(mlir::Value value, Address addr, bool isVolatile,
2302 clang::QualType ty, LValueBaseInfo baseInfo,
2303 bool isInit = false, bool isNontemporal = false);
2304 void emitStoreOfScalar(mlir::Value value, LValue lvalue, bool isInit);
2305
2306 void emitStoreThroughExtVectorComponentLValue(RValue src, LValue dst);
2307
2308 /// Store the specified rvalue into the specified
2309 /// lvalue, where both are guaranteed to the have the same type, and that
2310 /// type is 'Ty'.
2311 void emitStoreThroughLValue(RValue src, LValue dst, bool isInit = false);
2312
2313 mlir::Value emitStoreThroughBitfieldLValue(RValue src, LValue dstresult);
2314
2315 LValue emitStringLiteralLValue(const StringLiteral *e,
2316 llvm::StringRef name = ".str");
2317
2318 mlir::LogicalResult emitSwitchBody(const clang::Stmt *s);
2319 mlir::LogicalResult emitSwitchCase(const clang::SwitchCase &s,
2320 bool buildingTopLevelCase);
2321 mlir::LogicalResult emitSwitchStmt(const clang::SwitchStmt &s);
2322
2323 mlir::LogicalResult emitSYCLKernelCallStmt(const SYCLKernelCallStmt &s);
2324
2325 void emitSYCLKernelCaller(const clang::OutlinedFunctionDecl *outlinedFnDecl,
2326 cir::FuncOp funcOp, cir::FuncType funcType,
2327 FunctionArgList &args);
2328
2329 /// Remove leftover empty and unreachable blocks from an emitted function.
2330 static void eraseEmptyAndUnusedBlocks(cir::FuncOp func);
2331
2332 std::optional<mlir::Value>
2333 emitTargetBuiltinExpr(unsigned builtinID, const clang::CallExpr *e,
2334 ReturnValueSlot &returnValue);
2335
2336 /// Given a value and its clang type, returns the value casted to its memory
2337 /// representation.
2338 /// Note: CIR defers most of the special casting to the final lowering passes
2339 /// to conserve the high level information.
2340 mlir::Value emitToMemory(mlir::Value value, clang::QualType ty);
2341
2342 /// EmitFromMemory - Change a scalar value from its memory
2343 /// representation to its value representation.
2344 mlir::Value emitFromMemory(mlir::Value value, clang::QualType ty);
2345
2346 /// Emit a trap instruction, which is used to abort the program in an abnormal
2347 /// way, usually for debugging purposes.
2348 /// \p createNewBlock indicates whether to create a new block for the IR
2349 /// builder. Since the `cir.trap` operation is a terminator, operations that
2350 /// follow a trap cannot be emitted after `cir.trap` in the same block. To
2351 /// ensure these operations get emitted successfully, you need to create a new
2352 /// dummy block and set the insertion point there before continuing from the
2353 /// trap operation.
2354 void emitTrap(mlir::Location loc, bool createNewBlock);
2355
2356 LValue emitUnaryOpLValue(const clang::UnaryOperator *e);
2357
2358 mlir::Value emitUnPromotedValue(mlir::Value result, QualType unPromotionType);
2359
2360 /// Emit a reached-unreachable diagnostic if \p loc is valid and runtime
2361 /// checking is enabled. Otherwise, just emit an unreachable instruction.
2362 /// \p createNewBlock indicates whether to create a new block for the IR
2363 /// builder. Since the `cir.unreachable` operation is a terminator, operations
2364 /// that follow an unreachable point cannot be emitted after `cir.unreachable`
2365 /// in the same block. To ensure these operations get emitted successfully,
2366 /// you need to create a dummy block and set the insertion point there before
2367 /// continuing from the unreachable point.
2368 void emitUnreachable(clang::SourceLocation loc, bool createNewBlock);
2369
2370 /// This method handles emission of any variable declaration
2371 /// inside a function, including static vars etc.
2372 void emitVarDecl(const clang::VarDecl &d);
2373
2374 void emitVariablyModifiedType(QualType ty);
2375
2376 mlir::LogicalResult emitWhileStmt(const clang::WhileStmt &s);
2377
2378 std::optional<mlir::Value> emitRISCVBuiltinExpr(unsigned builtinID,
2379 const CallExpr *expr);
2380 cir::GetGlobalOp createGetCpuModel(mlir::Location loc);
2381 cir::GetGlobalOp createGetCpuFeatures2(mlir::Location loc);
2382 mlir::Value emitX86CpuIs(const CallExpr *expr);
2383 mlir::Value emitX86CpuIs(mlir::Location loc, StringRef cpuStr);
2384 mlir::Value emitX86CpuSupports(const CallExpr *expr);
2385 mlir::Value emitX86CpuSupports(mlir::Location loc,
2386 ArrayRef<StringRef> FeatureStrs);
2387 mlir::Value emitX86CpuSupports(mlir::Location loc,
2388 std::array<uint32_t, 4> FeatureMask);
2389 mlir::Value emitX86CpuInit(mlir::Location loc);
2390 std::optional<mlir::Value> emitX86BuiltinExpr(unsigned builtinID,
2391 const CallExpr *expr);
2392
2393 /// Given an assignment `*lhs = rhs`, emit a test that checks if \p rhs is
2394 /// nonnull, if 1\p LHS is marked _Nonnull.
2395 void emitNullabilityCheck(LValue lhs, mlir::Value rhs,
2396 clang::SourceLocation loc);
2397
2398 /// An object to manage conditionally-evaluated expressions.
2400 CIRGenFunction &cgf;
2401 mlir::OpBuilder::InsertPoint insertPt;
2402
2403 public:
2405 : cgf(cgf), insertPt(cgf.builder.saveInsertionPoint()) {}
2406 ConditionalEvaluation(CIRGenFunction &cgf, mlir::OpBuilder::InsertPoint ip)
2407 : cgf(cgf), insertPt(ip) {}
2408
2410 assert(cgf.outermostConditional != this);
2411 if (!cgf.outermostConditional)
2412 cgf.outermostConditional = this;
2413 }
2414
2416 assert(cgf.outermostConditional != nullptr);
2417 if (cgf.outermostConditional == this)
2418 cgf.outermostConditional = nullptr;
2419 }
2420
2421 /// Returns the insertion point which will be executed prior to each
2422 /// evaluation of the conditional code. In LLVM OG, this method
2423 /// is called getStartingBlock.
2424 mlir::OpBuilder::InsertPoint getInsertPoint() const { return insertPt; }
2425 };
2426
2428 std::optional<LValue> lhs{}, rhs{};
2429 mlir::Value result{};
2430 };
2431
2432 // Return true if we're currently emitting one branch or the other of a
2433 // conditional expression.
2434 bool isInConditionalBranch() const { return outermostConditional != nullptr; }
2435
2436 void setBeforeOutermostConditional(mlir::Value value, Address addr) {
2437 assert(isInConditionalBranch());
2438 {
2439 mlir::OpBuilder::InsertionGuard guard(builder);
2440 builder.restoreInsertionPoint(outermostConditional->getInsertPoint());
2441 builder.createStore(
2442 value.getLoc(), value, addr, /*isVolatile=*/false,
2443 /*isNontemporal=*/false,
2444 mlir::IntegerAttr::get(
2445 mlir::IntegerType::get(value.getContext(), 64),
2446 (uint64_t)addr.getAlignment().getAsAlign().value()));
2447 }
2448 }
2449
2450 // Points to the outermost active conditional control. This is used so that
2451 // we know if a temporary should be destroyed conditionally.
2453
2454 /// An RAII object to record that we're evaluating a statement
2455 /// expression.
2457 CIRGenFunction &cgf;
2458
2459 /// We have to save the outermost conditional: cleanups in a
2460 /// statement expression aren't conditional just because the
2461 /// StmtExpr is.
2462 ConditionalEvaluation *savedOutermostConditional;
2463
2464 public:
2466 : cgf(cgf), savedOutermostConditional(cgf.outermostConditional) {
2467 cgf.outermostConditional = nullptr;
2468 }
2469
2471 cgf.outermostConditional = savedOutermostConditional;
2472 }
2473 };
2474
2475 template <typename FuncTy>
2476 ConditionalInfo emitConditionalBlocks(const AbstractConditionalOperator *e,
2477 const FuncTy &branchGenFunc);
2478
2479 mlir::Value emitTernaryOnBoolExpr(const clang::Expr *cond, mlir::Location loc,
2480 const clang::Stmt *thenS,
2481 const clang::Stmt *elseS);
2482
2483 /// Build a "reference" to a va_list; this is either the address or the value
2484 /// of the expression, depending on how va_list is defined.
2485 Address emitVAListRef(const Expr *e);
2486
2487 /// Emits the start of a CIR variable-argument operation (`cir.va_start`)
2488 ///
2489 /// \param vaList A reference to the \c va_list as emitted by either
2490 /// \c emitVAListRef or \c emitMSVAListRef.
2491 void emitVAStart(mlir::Value vaList);
2492
2493 /// Emits the end of a CIR variable-argument operation (`cir.va_start`)
2494 ///
2495 /// \param vaList A reference to the \c va_list as emitted by either
2496 /// \c emitVAListRef or \c emitMSVAListRef.
2497 void emitVAEnd(mlir::Value vaList);
2498
2499 /// Generate code to get an argument from the passed in pointer
2500 /// and update it accordingly.
2501 ///
2502 /// \param ve The \c VAArgExpr for which to generate code.
2503 ///
2504 /// \param vaListAddr Receives a reference to the \c va_list as emitted by
2505 /// either \c emitVAListRef or \c emitMSVAListRef.
2506 ///
2507 /// \returns SSA value with the argument.
2508 mlir::Value emitVAArg(VAArgExpr *ve);
2509
2510 /// ----------------------
2511 /// CIR build helpers
2512 /// -----------------
2513public:
2514 cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc,
2515 const Twine &name = "tmp",
2516 mlir::Value arraySize = nullptr,
2517 bool insertIntoFnEntryBlock = false);
2518 cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc,
2519 const Twine &name = "tmp",
2520 mlir::OpBuilder::InsertPoint ip = {},
2521 mlir::Value arraySize = nullptr);
2522 Address createTempAlloca(mlir::Type ty, CharUnits align, mlir::Location loc,
2523 const Twine &name = "tmp",
2524 mlir::Value arraySize = nullptr,
2525 Address *alloca = nullptr,
2526 mlir::OpBuilder::InsertPoint ip = {});
2527 Address createTempAlloca(mlir::Type ty,
2528 mlir::ptr::MemorySpaceAttrInterface destAddrSpace,
2529 CharUnits align, mlir::Location loc,
2530 const Twine &name = "tmp",
2531 mlir::Value arraySize = nullptr,
2532 Address *alloca = nullptr,
2533 mlir::OpBuilder::InsertPoint ip = {});
2534 Address createTempAllocaWithoutCast(mlir::Type ty, CharUnits align,
2535 mlir::Location loc,
2536 const Twine &name = "tmp",
2537 mlir::Value arraySize = nullptr,
2538 mlir::OpBuilder::InsertPoint ip = {});
2539 Address
2540 maybeCastStackAddressSpace(Address alloca,
2541 mlir::ptr::MemorySpaceAttrInterface destAddrSpace,
2542 mlir::Value arraySize);
2543 Address createDefaultAlignTempAlloca(mlir::Type ty, mlir::Location loc,
2544 const Twine &name);
2545
2546 /// Create a temporary memory object of the given type, with
2547 /// appropriate alignmen and cast it to the default address space. Returns
2548 /// the original alloca instruction by \p Alloca if it is not nullptr.
2549 Address createMemTemp(QualType t, mlir::Location loc,
2550 const Twine &name = "tmp", Address *alloca = nullptr,
2551 mlir::OpBuilder::InsertPoint ip = {});
2552 Address createMemTemp(QualType t, CharUnits align, mlir::Location loc,
2553 const Twine &name = "tmp", Address *alloca = nullptr,
2554 mlir::OpBuilder::InsertPoint ip = {});
2555 Address createMemTempWithoutCast(QualType t, mlir::Location loc,
2556 const Twine &name = "tmp");
2557
2558 mlir::Value performAddrSpaceCast(mlir::Value v, mlir::Type destTy) const {
2559 if (cir::GlobalOp globalOp = v.getDefiningOp<cir::GlobalOp>())
2560 cgm.errorNYI("Global op addrspace cast");
2561 return builder.createAddrSpaceCast(v, destTy);
2562 }
2563
2564 //===--------------------------------------------------------------------===//
2565 // OpenMP Emission
2566 //===--------------------------------------------------------------------===//
2567public:
2568 mlir::LogicalResult emitOMPScopeDirective(const OMPScopeDirective &s);
2569 mlir::LogicalResult emitOMPErrorDirective(const OMPErrorDirective &s);
2570 mlir::LogicalResult emitOMPParallelDirective(const OMPParallelDirective &s);
2571 mlir::LogicalResult emitOMPTaskwaitDirective(const OMPTaskwaitDirective &s);
2572 mlir::LogicalResult emitOMPTaskyieldDirective(const OMPTaskyieldDirective &s);
2573 mlir::LogicalResult emitOMPBarrierDirective(const OMPBarrierDirective &s);
2574 mlir::LogicalResult emitOMPMetaDirective(const OMPMetaDirective &s);
2575 mlir::LogicalResult emitOMPCanonicalLoop(const OMPCanonicalLoop &s);
2576 mlir::LogicalResult emitOMPSimdDirective(const OMPSimdDirective &s);
2577 mlir::LogicalResult emitOMPTileDirective(const OMPTileDirective &s);
2578 mlir::LogicalResult emitOMPUnrollDirective(const OMPUnrollDirective &s);
2579 mlir::LogicalResult emitOMPFuseDirective(const OMPFuseDirective &s);
2580 mlir::LogicalResult emitOMPForDirective(const OMPForDirective &s);
2581 mlir::LogicalResult emitOMPForSimdDirective(const OMPForSimdDirective &s);
2582 mlir::LogicalResult emitOMPSectionsDirective(const OMPSectionsDirective &s);
2583 mlir::LogicalResult emitOMPSectionDirective(const OMPSectionDirective &s);
2584 mlir::LogicalResult emitOMPSingleDirective(const OMPSingleDirective &s);
2585 mlir::LogicalResult emitOMPMasterDirective(const OMPMasterDirective &s);
2586 mlir::LogicalResult emitOMPCriticalDirective(const OMPCriticalDirective &s);
2587 mlir::LogicalResult
2589 mlir::LogicalResult
2591 mlir::LogicalResult
2593 mlir::LogicalResult
2595 mlir::LogicalResult emitOMPTaskDirective(const OMPTaskDirective &s);
2596 mlir::LogicalResult emitOMPTaskgroupDirective(const OMPTaskgroupDirective &s);
2597 mlir::LogicalResult emitOMPFlushDirective(const OMPFlushDirective &s);
2598 mlir::LogicalResult emitOMPDepobjDirective(const OMPDepobjDirective &s);
2599 mlir::LogicalResult emitOMPScanDirective(const OMPScanDirective &s);
2600 mlir::LogicalResult
2602 mlir::LogicalResult
2604 mlir::LogicalResult emitOMPAtomicDirective(const OMPAtomicDirective &s);
2605 mlir::LogicalResult emitOMPTargetDirective(const OMPTargetDirective &s);
2606 mlir::LogicalResult emitOMPTeamsDirective(const OMPTeamsDirective &s);
2607 mlir::LogicalResult
2609 mlir::LogicalResult emitOMPCancelDirective(const OMPCancelDirective &s);
2610 mlir::LogicalResult
2612 mlir::LogicalResult
2614 mlir::LogicalResult
2616 mlir::LogicalResult
2618 mlir::LogicalResult
2620 mlir::LogicalResult emitOMPTaskLoopDirective(const OMPTaskLoopDirective &s);
2621 mlir::LogicalResult
2623 mlir::LogicalResult
2625 mlir::LogicalResult
2627 mlir::LogicalResult
2629 mlir::LogicalResult
2631 mlir::LogicalResult
2633 mlir::LogicalResult
2635 mlir::LogicalResult emitOMPParallelMaskedTaskLoopDirective(
2639 mlir::LogicalResult emitOMPParallelMasterTaskLoopDirective(
2643 mlir::LogicalResult
2645 mlir::LogicalResult emitOMPDistributeParallelForDirective(
2649 mlir::LogicalResult
2653 mlir::LogicalResult emitOMPTargetParallelForSimdDirective(
2655 mlir::LogicalResult
2657 mlir::LogicalResult emitOMPTargetTeamsGenericLoopDirective(
2659 mlir::LogicalResult
2661 mlir::LogicalResult
2663 mlir::LogicalResult
2669 mlir::LogicalResult
2671 mlir::LogicalResult
2673 mlir::LogicalResult emitOMPTargetTeamsDistributeDirective(
2681 mlir::LogicalResult emitOMPInteropDirective(const OMPInteropDirective &s);
2682 mlir::LogicalResult emitOMPDispatchDirective(const OMPDispatchDirective &s);
2683 mlir::LogicalResult
2685 mlir::LogicalResult emitOMPReverseDirective(const OMPReverseDirective &s);
2686 mlir::LogicalResult emitOMPSplitDirective(const OMPSplitDirective &s);
2687 mlir::LogicalResult
2689 mlir::LogicalResult emitOMPAssumeDirective(const OMPAssumeDirective &s);
2690 mlir::LogicalResult emitOMPMaskedDirective(const OMPMaskedDirective &s);
2691 mlir::LogicalResult emitOMPStripeDirective(const OMPStripeDirective &s);
2692
2696 void emitOMPAllocateDecl(const OMPAllocateDecl &d);
2699 void emitOMPRequiresDecl(const OMPRequiresDecl &d);
2700
2701 //===--------------------------------------------------------------------===//
2702 // OpenACC Emission
2703 //===--------------------------------------------------------------------===//
2704private:
2705 template <typename Op>
2706 Op emitOpenACCOp(mlir::Location start, OpenACCDirectiveKind dirKind,
2708 // Function to do the basic implementation of an operation with an Associated
2709 // Statement. Models AssociatedStmtConstruct.
2710 template <typename Op, typename TermOp>
2711 mlir::LogicalResult
2712 emitOpenACCOpAssociatedStmt(mlir::Location start, mlir::Location end,
2713 OpenACCDirectiveKind dirKind,
2715 const Stmt *associatedStmt);
2716
2717 template <typename Op, typename TermOp>
2718 mlir::LogicalResult emitOpenACCOpCombinedConstruct(
2719 mlir::Location start, mlir::Location end, OpenACCDirectiveKind dirKind,
2720 llvm::ArrayRef<const OpenACCClause *> clauses, const Stmt *loopStmt);
2721
2722 template <typename Op>
2723 void emitOpenACCClauses(Op &op, OpenACCDirectiveKind dirKind,
2725 // The second template argument doesn't need to be a template, since it should
2726 // always be an mlir::acc::LoopOp, but as this is a template anyway, we make
2727 // it a template argument as this way we can avoid including the OpenACC MLIR
2728 // headers here. We will count on linker failures/explicit instantiation to
2729 // ensure we don't mess this up, but it is only called from 1 place, and
2730 // instantiated 3x.
2731 template <typename ComputeOp, typename LoopOp>
2732 void emitOpenACCClauses(ComputeOp &op, LoopOp &loopOp,
2733 OpenACCDirectiveKind dirKind,
2735
2736 // The OpenACC LoopOp requires that we have auto, seq, or independent on all
2737 // LoopOp operations for the 'none' device type case. This function checks if
2738 // the LoopOp has one, else it updates it to have one.
2739 void updateLoopOpParallelism(mlir::acc::LoopOp &op, bool isOrphan,
2741
2742 // The OpenACC 'cache' construct actually applies to the 'loop' if present. So
2743 // keep track of the 'loop' so that we can add the cache vars to it correctly.
2744 mlir::acc::LoopOp *activeLoopOp = nullptr;
2745
2746 struct ActiveOpenACCLoopRAII {
2747 CIRGenFunction &cgf;
2748 mlir::acc::LoopOp *oldLoopOp;
2749
2750 ActiveOpenACCLoopRAII(CIRGenFunction &cgf, mlir::acc::LoopOp *newOp)
2751 : cgf(cgf), oldLoopOp(cgf.activeLoopOp) {
2752 cgf.activeLoopOp = newOp;
2753 }
2754 ~ActiveOpenACCLoopRAII() { cgf.activeLoopOp = oldLoopOp; }
2755 };
2756
2757 // Keep track of the last place we inserted a 'recipe' so that we can insert
2758 // the next one in lexical order.
2759 mlir::OpBuilder::InsertPoint lastRecipeLocation;
2760
2761public:
2762 // Helper type used to store the list of important information for a 'data'
2763 // clause variable, or a 'cache' variable reference.
2765 mlir::Location beginLoc;
2766 mlir::Value varValue;
2767 std::string name;
2768 // The type of the original variable reference: that is, after 'bounds' have
2769 // removed pointers/array types/etc. So in the case of int arr[5], and a
2770 // private(arr[1]), 'origType' is 'int', but 'baseType' is 'int[5]'.
2774 // The list of types that we found when going through the bounds, which we
2775 // can use to properly set the alloca section.
2777 };
2778
2779 // Gets the collection of info required to lower and OpenACC clause or cache
2780 // construct variable reference.
2782 // Helper function to emit the integer expressions as required by an OpenACC
2783 // clause/construct.
2784 mlir::Value emitOpenACCIntExpr(const Expr *intExpr);
2785 // Helper function to emit an integer constant as an mlir int type, used for
2786 // constants in OpenACC constructs/clauses.
2787 mlir::Value createOpenACCConstantInt(mlir::Location loc, unsigned width,
2788 int64_t value);
2789
2790 mlir::LogicalResult
2792 mlir::LogicalResult emitOpenACCLoopConstruct(const OpenACCLoopConstruct &s);
2793 mlir::LogicalResult
2795 mlir::LogicalResult emitOpenACCDataConstruct(const OpenACCDataConstruct &s);
2796 mlir::LogicalResult
2798 mlir::LogicalResult
2800 mlir::LogicalResult
2802 mlir::LogicalResult emitOpenACCWaitConstruct(const OpenACCWaitConstruct &s);
2803 mlir::LogicalResult emitOpenACCInitConstruct(const OpenACCInitConstruct &s);
2804 mlir::LogicalResult
2806 mlir::LogicalResult emitOpenACCSetConstruct(const OpenACCSetConstruct &s);
2807 mlir::LogicalResult
2809 mlir::LogicalResult
2811 mlir::LogicalResult emitOpenACCCacheConstruct(const OpenACCCacheConstruct &s);
2812
2815
2816 /// Create a temporary memory object for the given aggregate type.
2817 AggValueSlot createAggTemp(QualType ty, mlir::Location loc,
2818 const Twine &name = "tmp",
2819 Address *alloca = nullptr) {
2821 return AggValueSlot::forAddr(
2822 createMemTemp(ty, loc, name, alloca), ty.getQualifiers(),
2825 }
2826
2827private:
2828 QualType getVarArgType(const Expr *arg);
2829
2830 bool shouldEmitLifetimeMarkers = false;
2831 /// Set when the current function has a goto/switch that may bypass a local's
2832 /// init; lifetime markers are then suppressed. See functionMightHaveBypass.
2833 bool fnHasBypassStmt = false;
2834
2835 bool shouldEmitLifetimeMarkersForAutoVar() const {
2836 return shouldEmitLifetimeMarkers && !fnHasBypassStmt;
2837 }
2838
2839 class InlinedInheritingConstructorScope {
2840 public:
2841 InlinedInheritingConstructorScope(CIRGenFunction &cgf, GlobalDecl gd)
2842 : cgf(cgf), oldCurGD(cgf.curGD), oldCurFuncDecl(cgf.curFuncDecl),
2843 oldCurCodeDecl(cgf.curCodeDecl),
2844 oldCxxabiThisDecl(cgf.cxxabiThisDecl),
2845 oldCxxThisValue(cgf.cxxThisValue),
2846 oldCxxabiThisAlignment(cgf.cxxabiThisAlignment),
2847 oldCxxThisAlignment(cgf.cxxThisAlignment),
2848 oldReturnValue(cgf.returnValue), oldFnRetTy(cgf.fnRetTy),
2849 oldCxxInheritedCtorInitExprArgs(
2850 std::move(cgf.cxxInheritedCtorInitExprArgs)) {
2851 cgf.curGD = gd;
2852 cgf.curFuncDecl = cast<CXXConstructorDecl>(gd.getDecl());
2853 cgf.curCodeDecl = cgf.curFuncDecl;
2854 cgf.cxxabiThisDecl = nullptr;
2855 cgf.cxxabiThisValue = nullptr;
2856 cgf.cxxThisValue = nullptr;
2857 cgf.cxxThisAlignment = CharUnits();
2858 cgf.cxxabiThisAlignment = CharUnits();
2859 cgf.returnValue = Address::invalid();
2860 cgf.fnRetTy = QualType();
2861 cgf.cxxInheritedCtorInitExprArgs.clear();
2862 // FIXME: at one point when we want to call one of these, we'll need
2863 // CXXInheritedCtorInitExprArgs here too.
2864 }
2865 ~InlinedInheritingConstructorScope() {
2866 cgf.curGD = oldCurGD;
2867 cgf.curFuncDecl = oldCurFuncDecl;
2868 cgf.curCodeDecl = oldCurCodeDecl;
2869 cgf.cxxabiThisDecl = oldCxxabiThisDecl;
2870 cgf.cxxabiThisValue = oldCxxabiThisValue;
2871 cgf.cxxThisValue = oldCxxThisValue;
2872 cgf.cxxThisAlignment = oldCxxThisAlignment;
2873 cgf.cxxabiThisAlignment = oldCxxabiThisAlignment;
2874 cgf.returnValue = oldReturnValue;
2875 cgf.fnRetTy = oldFnRetTy;
2876 cgf.cxxInheritedCtorInitExprArgs =
2877 std::move(oldCxxInheritedCtorInitExprArgs);
2878 }
2879
2880 private:
2881 CIRGenFunction &cgf;
2882 GlobalDecl oldCurGD;
2883 const Decl *oldCurFuncDecl;
2884 const Decl *oldCurCodeDecl;
2885 ImplicitParamDecl *oldCxxabiThisDecl;
2886 mlir::Value oldCxxabiThisValue;
2887 mlir::Value oldCxxThisValue;
2888 clang::CharUnits oldCxxabiThisAlignment;
2889 clang::CharUnits oldCxxThisAlignment;
2890 Address oldReturnValue;
2891 QualType oldFnRetTy;
2892 CallArgList oldCxxInheritedCtorInitExprArgs;
2893 };
2894};
2895
2896} // namespace clang::CIRGen
2897
2898#endif
Defines the clang::ASTContext interface.
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
Definition CIRDialect.h:37
static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr *expr, Address dest, Address ptr, Address val1, Address val2, 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.
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 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 ...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4397
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2765
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
Definition Stmt.h:3289
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6978
Represents an attribute applied to a statement.
Definition Stmt.h:2215
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4497
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4535
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4532
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
BreakStmt - This represents a break.
Definition Stmt.h:3147
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)
An object to manage conditionally-evaluated expressions.
ConditionalEvaluation(CIRGenFunction &cgf, mlir::OpBuilder::InsertPoint ip)
mlir::OpBuilder::InsertPoint getInsertPoint() const
Returns the insertion point which will be executed prior to each evaluation of the conditional code.
static ConstantEmission forReference(mlir::TypedAttr c)
static ConstantEmission forValue(mlir::TypedAttr c)
LValue getReferenceLValue(CIRGenFunction &cgf, Expr *refExpr) const
DeclMapRevertingRAII(CIRGenFunction &cgf, const VarDecl *vd)
Captures cleanups for a loop's condition variable so that they can be emitted into the loop op's per-...
void emitIntoLoopCleanupRegion(mlir::Location loc)
Emit the captured condition-variable cleanups into the current insertion point (the loop's cleanup re...
FieldConstructionScope(CIRGenFunction &cgf, Address thisAddr)
FullExprCleanupScope(CIRGenFunction &cgf, const Expr *subExpr)
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 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, mlir::Location 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: declare function arguments in the symbol table.
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,...
void emitCallArgs(CallArgList &args, PrototypeWrapper prototype, llvm::iterator_range< clang::CallExpr::const_arg_iterator > argRange, AbstractCallee callee=AbstractCallee(), unsigned paramsToSkip=0)
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.
mlir::LogicalResult emitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &s)
LValue emitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *e)
mlir::LogicalResult emitOMPParallelMasterTaskLoopSimdDirective(const OMPParallelMasterTaskLoopSimdDirective &s)
void generateThunk(cir::FuncOp fn, const CIRGenFunctionInfo &fnInfo, GlobalDecl gd, const ThunkInfo &thunk, bool isUnprototyped)
Generate code for a thunk function.
mlir::LogicalResult emitOMPSimdDirective(const OMPSimdDirective &s)
mlir::Value emitCheckedArgForAssume(const Expr *e)
Emits an argument for a call to a __builtin_assume.
LValue emitOpaqueValueLValue(const OpaqueValueExpr *e)
mlir::LogicalResult emitDoStmt(const clang::DoStmt &s)
mlir::LogicalResult emitOMPCriticalDirective(const OMPCriticalDirective &s)
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.
Address maybeCastStackAddressSpace(Address alloca, mlir::ptr::MemorySpaceAttrInterface destAddrSpace, mlir::Value arraySize)
mlir::LogicalResult emitOMPParallelMasterDirective(const OMPParallelMasterDirective &s)
mlir::LogicalResult emitOpenACCWaitConstruct(const OpenACCWaitConstruct &s)
cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn, cir::FuncType funcType)
llvm::SmallVector< PendingCleanupEntry > lifetimeExtendedCleanupStack
mlir::LogicalResult emitOMPCancellationPointDirective(const OMPCancellationPointDirective &s)
mlir::LogicalResult emitOMPParallelMaskedTaskLoopDirective(const OMPParallelMaskedTaskLoopDirective &s)
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
mlir::LogicalResult emitOMPReverseDirective(const OMPReverseDirective &s)
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
cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, bool insertIntoFnEntryBlock=false)
This creates an alloca and inserts it into the entry block if ArraySize is nullptr,...
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()
void emitLoopConditionCleanups(EHScopeStack::stable_iterator depth, mlir::Location loc)
Emit the cleanups captured for a loop's condition variable (those pushed above depth while EHScopeSta...
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 emitOMPTileDirective(const OMPTileDirective &s)
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.
void emitOMPRequiresDecl(const OMPRequiresDecl &d)
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)
mlir::LogicalResult emitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &s)
Address cxxDefaultInitExprThis
The value of 'this' to sue when evaluating CXXDefaultInitExprs within this expression.
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.
mlir::LogicalResult emitOMPTeamsDistributeParallelForDirective(const OMPTeamsDistributeParallelForDirective &s)
mlir::LogicalResult emitOMPBarrierDirective(const OMPBarrierDirective &s)
void setBeforeOutermostConditional(mlir::Value value, Address addr)
mlir::LogicalResult emitOMPTargetParallelDirective(const OMPTargetParallelDirective &s)
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 emitOMPTargetDirective(const OMPTargetDirective &s)
mlir::LogicalResult emitCXXForRangeStmt(const CXXForRangeStmt &s, llvm::ArrayRef< const Attr * > attrs)
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.
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,...
mlir::Value emitNVPTXDevicePrintfCallExpr(const CallExpr *expr)
Emit a device-side printf call for NVPTX targets.
void emitMustTailThunk(GlobalDecl gd, mlir::Value adjustedThisPtr, cir::FuncOp callee)
Emit a musttail call for a thunk with a potentially different ABI.
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.
LValue emitComplexCompoundAssignmentLValue(const CompoundAssignOperator *e)
mlir::LogicalResult emitOMPScopeDirective(const OMPScopeDirective &s)
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.
mlir::LogicalResult emitOMPDepobjDirective(const OMPDepobjDirective &s)
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,...
mlir::Value emitOpOnBoolExpr(mlir::Location loc, const clang::Expr *cond)
TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
void emitLoopConditionVariable(const clang::VarDecl &d, DeferredLoopConditionCleanup &condCleanup)
Emit a loop's condition-variable declaration.
void emitStoreThroughExtVectorComponentLValue(RValue src, LValue dst)
void initializeVTablePointer(mlir::Location loc, const VPtr &vptr)
Address getAddressOfBaseClass(Address value, const CXXRecordDecl *derived, llvm::iterator_range< CastExpr::path_const_iterator > path, bool nullCheckValue, SourceLocation loc)
void emitOMPDeclareReduction(const OMPDeclareReductionDecl &d)
void emitAggregateStore(mlir::Value value, Address dest)
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.
mlir::LogicalResult emitOMPDistributeParallelForSimdDirective(const OMPDistributeParallelForSimdDirective &s)
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.
mlir::LogicalResult emitOMPUnrollDirective(const OMPUnrollDirective &s)
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 emitOMPTaskDirective(const OMPTaskDirective &s)
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.
mlir::LogicalResult emitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &s)
llvm::SmallVector< DeferredDeactivateCleanup > deferredDeactivationCleanupStack
VPtrsVector getVTablePointers(const clang::CXXRecordDecl *vtableClass)
const TargetCIRGenInfo & getTargetHooks() const
mlir::LogicalResult emitOMPCanonicalLoop(const OMPCanonicalLoop &s)
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)
mlir::LogicalResult emitOMPTeamsDirective(const OMPTeamsDirective &s)
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 emitCaseStmt(const clang::CaseStmt &s, mlir::Type condType, bool buildingTopLevelCase)
LValue emitArraySubscriptExpr(const clang::ArraySubscriptExpr *e)
llvm::ScopedHashTableScope< const clang::Decl *, mlir::Value > SymTableScopeTy
OpenACCDataOperandInfo getOpenACCDataOperandInfo(const Expr *e)
mlir::LogicalResult emitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective &s)
CleanupKind getCleanupKind(QualType::DestructionKind kind)
clang::CharUnits cxxabiThisAlignment
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....
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)
mlir::LogicalResult emitOMPFuseDirective(const OMPFuseDirective &s)
AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *fd)
mlir::LogicalResult emitSimpleStmt(const clang::Stmt *s, bool useCurrentScope)
mlir::LogicalResult emitOMPSectionDirective(const OMPSectionDirective &s)
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::LogicalResult emitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &s)
void emitOMPAllocateDecl(const OMPAllocateDecl &d)
mlir::LogicalResult emitOMPDistributeParallelForDirective(const OMPDistributeParallelForDirective &s)
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)
mlir::LogicalResult emitOMPOrderedStandaloneDirective(const OMPOrderedStandaloneDirective &s)
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)
void emitOMPDeclareMapper(const OMPDeclareMapperDecl &d)
mlir::LogicalResult emitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &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())
mlir::LogicalResult emitForStmt(const clang::ForStmt &s)
AggValueSlot createAggTemp(QualType ty, mlir::Location loc, const Twine &name="tmp", Address *alloca=nullptr)
Create a temporary memory object for the given aggregate type.
llvm::SmallVector< PendingCleanupEntry > deferredConditionalCleanupStack
void emitNewArrayInitializer(const CXXNewExpr *e, QualType elementType, mlir::Type elementTy, Address beginPtr, mlir::Value numElements, mlir::Value allocSizeWithoutCookie)
mlir::LogicalResult emitOMPTaskwaitDirective(const OMPTaskwaitDirective &s)
mlir::LogicalResult emitOMPFlushDirective(const OMPFlushDirective &s)
mlir::LogicalResult emitOMPGenericLoopDirective(const OMPGenericLoopDirective &s)
mlir::LogicalResult emitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &s)
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.
mlir::LogicalResult emitOMPTargetParallelForSimdDirective(const OMPTargetParallelForSimdDirective &s)
mlir::LogicalResult emitOMPInterchangeDirective(const OMPInterchangeDirective &s)
RValue emitLoadOfExtVectorElementLValue(LValue lv)
mlir::Value emitCXXTypeidExpr(const CXXTypeidExpr *e)
mlir::LogicalResult emitOMPDispatchDirective(const OMPDispatchDirective &s)
mlir::Type convertTypeForMem(QualType t)
mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s, cxxTryBodyEmitter &bodyCallback)
clang::QualType buildFunctionArgList(clang::GlobalDecl gd, FunctionArgList &args)
mlir::LogicalResult emitOMPParallelDirective(const OMPParallelDirective &s)
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::Value createDummyValue(mlir::Location loc, clang::QualType qt)
mlir::LogicalResult emitAttributedStmt(const AttributedStmt &s)
void emitCXXConstructExpr(const clang::CXXConstructExpr *e, AggValueSlot dest)
mlir::Value emitLoadOfComplex(LValue src, SourceLocation loc)
Load a complex number from the specified l-value.
mlir::LogicalResult emitOMPForSimdDirective(const OMPForSimdDirective &s)
LValue emitAggExprToLValue(const Expr *e)
mlir::LogicalResult emitOMPTaskLoopDirective(const OMPTaskLoopDirective &s)
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)
void emitCallAndReturnForThunk(cir::FuncOp callee, const ThunkInfo *thunk, bool isUnprototyped)
Emit the call and return for a thunk function.
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.
mlir::LogicalResult emitOMPTargetDataDirective(const OMPTargetDataDirective &s)
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)
mlir::LogicalResult emitOMPTargetParallelGenericLoopDirective(const OMPTargetParallelGenericLoopDirective &s)
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)
mlir::LogicalResult emitOMPParallelMaskedDirective(const OMPParallelMaskedDirective &s)
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 emitOMPMaskedTaskLoopSimdDirective(const OMPMaskedTaskLoopSimdDirective &s)
mlir::LogicalResult emitOMPAtomicDirective(const OMPAtomicDirective &s)
mlir::LogicalResult emitOpenACCShutdownConstruct(const OpenACCShutdownConstruct &s)
mlir::LogicalResult emitFunctionBody(const clang::Stmt *body)
mlir::LogicalResult emitBreakStmt(const clang::BreakStmt &s)
void initFullExprCleanupWithFlag(Address activeFlag)
mlir::LogicalResult emitIndirectGotoStmt(const IndirectGotoStmt &s)
mlir::LogicalResult emitOMPTeamsDistributeParallelForSimdDirective(const OMPTeamsDistributeParallelForSimdDirective &s)
mlir::LogicalResult emitOMPTaskgroupDirective(const OMPTaskgroupDirective &s)
mlir::Value emitTernaryOnBoolExpr(const clang::Expr *cond, mlir::Location loc, const clang::Stmt *thenS, const clang::Stmt *elseS)
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
mlir::LogicalResult emitOMPParallelMaskedTaskLoopSimdDirective(const OMPParallelMaskedTaskLoopSimdDirective &s)
mlir::LogicalResult emitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &s)
void emitScalarInit(const clang::Expr *init, mlir::Location loc, LValue lvalue, bool capturedByInit=false)
LValue emitUnaryOpLValue(const clang::UnaryOperator *e)
void emitReturnOfRValue(mlir::Location loc, RValue rv, QualType ty)
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)
mlir::LogicalResult emitOMPInteropDirective(const OMPInteropDirective &s)
mlir::LogicalResult emitOMPErrorDirective(const OMPErrorDirective &s)
LValue emitComplexAssignmentLValue(const BinaryOperator *e)
mlir::LogicalResult emitOMPSingleDirective(const OMPSingleDirective &s)
void emitCallArg(CallArgList &args, const clang::Expr *e, clang::QualType argType)
cir::CoroEndOp emitCoroEndBuiltinCall(const CallExpr *e)
clang::FieldDecl * lambdaThisCaptureField
void deactivateCleanupBlock(EHScopeStack::stable_iterator cleanup, mlir::Operation *dominatingIP)
Deactivates the given cleanup block.
mlir::LogicalResult emitContinueStmt(const clang::ContinueStmt &s)
const clang::Decl * curCodeDecl
This is the inner-most code context, which includes blocks.
mlir::LogicalResult emitOMPTaskyieldDirective(const OMPTaskyieldDirective &s)
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)
mlir::LogicalResult emitOMPTargetTeamsDistributeSimdDirective(const OMPTargetTeamsDistributeSimdDirective &s)
LValue emitCallExprLValue(const clang::CallExpr *e)
mlir::LogicalResult emitOMPScanDirective(const OMPScanDirective &s)
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.
mlir::LogicalResult emitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &s)
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.
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")
mlir::LogicalResult emitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &s)
void emitAtomicExprWithMemOrder(const Expr *memOrder, bool isStore, bool isLoad, bool isFence, llvm::function_ref< void(cir::MemOrder)> emitAtomicOp)
void maybeEmitDeferredVarDeclInit(const VarDecl *vd)
mlir::Value getUndefConstant(mlir::Location loc, mlir::Type cirTy)
Return a CIR constant for an undefined value of cirTy.
llvm::SmallDenseMap< const ParmVarDecl *, const ImplicitParamDecl * > sizeArguments
If a ParmVarDecl had the pass_object_size attribute, this will contain a mapping from said ParmVarDec...
void emitVAEnd(mlir::Value vaList)
Emits the end of a CIR variable-argument operation (cir.va_start)
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)
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
void pushStackRestore(CleanupKind kind, Address spMem)
LValue emitPseudoObjectLValue(const PseudoObjectExpr *E)
mlir::LogicalResult emitIfStmt(const clang::IfStmt &s)
mlir::LogicalResult emitOMPForDirective(const OMPForDirective &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)
mlir::LogicalResult emitOMPMasterDirective(const OMPMasterDirective &s)
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::LogicalResult emitOMPMetaDirective(const OMPMetaDirective &s)
mlir::LogicalResult emitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &s)
CIRGenBuilderTy & getBuilder()
void emitVAStart(mlir::Value vaList)
Emits the start of a CIR variable-argument operation (cir.va_start)
bool didCallStackSave
Whether a cir.stacksave operation has been added.
void emitDecl(const clang::Decl &d, bool evaluateConditionDecl=false)
mlir::LogicalResult emitOMPParallelGenericLoopDirective(const OMPParallelGenericLoopDirective &s)
LValue emitBinaryOperatorLValue(const BinaryOperator *e)
mlir::Value emitOpenACCIntExpr(const Expr *intExpr)
mlir::LogicalResult emitOMPMaskedDirective(const OMPMaskedDirective &s)
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.
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.
mlir::LogicalResult emitOMPSplitDirective(const OMPSplitDirective &s)
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.
mlir::Region * curStaticVarDtorRegion
While the initializer of a variable with static storage duration is being emitted,...
LValue emitCastLValue(const CastExpr *e)
Casts are never lvalues unless that cast is to a reference type.
LValue emitCXXTypeidLValue(const CXXTypeidExpr *e)
mlir::LogicalResult emitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &s)
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.
mlir::LogicalResult emitOMPOrderedBlockAssocDirective(const OMPOrderedBlockAssocDirective &s)
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)
mlir::LogicalResult emitOMPTargetTeamsDistributeParallelForDirective(const OMPTargetTeamsDistributeParallelForDirective &s)
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.
void emitOMPThreadPrivateDecl(const OMPThreadPrivateDecl &d)
std::optional< mlir::Value > emitNVPTXBuiltinExpr(unsigned builtinID, const CallExpr *expr)
Emit a call to an NVPTX builtin function.
void emitOMPGroupPrivateDecl(const OMPGroupPrivateDecl &d)
static void eraseEmptyAndUnusedBlocks(cir::FuncOp func)
Remove leftover empty and unreachable blocks from an emitted function.
llvm::DenseMap< const clang::ValueDecl *, clang::FieldDecl * > lambdaCaptureFields
mlir::LogicalResult emitOMPParallelForDirective(const OMPParallelForDirective &s)
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)
mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, QualType ty, SourceLocation loc, SourceLocation assumptionLoc, int64_t alignment, mlir::Value offsetValue=nullptr)
mlir::LogicalResult emitCaseDefaultCascade(const T *stmt, mlir::Type condType, mlir::ArrayAttr value, cir::CaseOpKind kind, bool buildingTopLevelCase)
void emitCXXThrowExpr(const CXXThrowExpr *e)
mlir::LogicalResult emitOMPSectionsDirective(const OMPSectionsDirective &s)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
int64_t getAccessedFieldNo(unsigned idx, mlir::ArrayAttr elts)
LValue emitPredefinedLValue(const PredefinedExpr *e)
mlir::LogicalResult emitOMPDistributeDirective(const OMPDistributeDirective &s)
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.
mlir::LogicalResult emitOMPTargetTeamsDistributeParallelForSimdDirective(const OMPTargetTeamsDistributeParallelForSimdDirective &s)
void emitCXXDestructorCall(const CXXDestructorDecl *dd, CXXDtorType type, bool forVirtualBase, bool delegating, Address thisAddr, QualType thisTy)
mlir::LogicalResult emitOMPTargetTeamsGenericLoopDirective(const OMPTargetTeamsGenericLoopDirective &s)
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.
mlir::LogicalResult emitDeclStmt(const clang::DeclStmt &s)
cir::GetGlobalOp createGetCpuFeatures2(mlir::Location loc)
mlir::LogicalResult emitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &s)
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)
mlir::LogicalResult emitWhileStmt(const clang::WhileStmt &s)
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.
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.
mlir::LogicalResult emitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &s)
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)
std::optional< mlir::Location > currSrcLoc
Use to track source locations across nested visitor traversals.
void terminateStructuredRegionBody(mlir::Region &r, mlir::Location loc)
Address createMemTempWithoutCast(QualType t, mlir::Location loc, const Twine &name="tmp")
LValue emitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e)
LValue emitExtVectorElementExpr(const ExtVectorElementExpr *e)
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 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 emitCall(const CIRGenFunctionInfo &funcInfo, const CIRGenCallee &callee, ReturnValueSlot returnValue, const CallArgList &args, cir::CIRCallOpInterface *callOp, bool isMustTail, mlir::Location loc)
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 emitOMPCapturedExpr(const OMPCapturedExprDecl &d)
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 ...
mlir::LogicalResult emitOMPParallelMasterTaskLoopDirective(const OMPParallelMasterTaskLoopDirective &s)
bool isLValueSuitableForInlineAtomic(LValue lv)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
mlir::LogicalResult emitOMPCancelDirective(const OMPCancelDirective &s)
Address createTempAllocaWithoutCast(mlir::Type ty, CharUnits align, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, mlir::OpBuilder::InsertPoint ip={})
This creates a alloca and inserts it into the entry block of the current region.
mlir::Value emitFromMemory(mlir::Value value, clang::QualType ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Address emitVAListRef(const Expr *e)
Build a "reference" to a va_list; this is either the address or the value of the expression,...
mlir::LogicalResult emitOMPStripeDirective(const OMPStripeDirective &s)
mlir::LogicalResult emitOMPTargetTeamsDistributeDirective(const OMPTargetTeamsDistributeDirective &s)
mlir::LogicalResult emitCompoundStmtWithoutScope(const clang::CompoundStmt &s, Address *lastValue=nullptr, AggValueSlot slot=AggValueSlot::ignored())
mlir::LogicalResult emitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &s)
mlir::LogicalResult emitOpenACCExitDataConstruct(const OpenACCExitDataConstruct &s)
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)
ConditionalInfo emitConditionalBlocks(const AbstractConditionalOperator *e, const FuncTy &branchGenFunc)
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)
mlir::LogicalResult emitOMPTargetSimdDirective(const OMPTargetSimdDirective &s)
LValue emitCXXConstructLValue(const CXXConstructExpr *e)
void finishThunk()
Finish generating a thunk function.
mlir::LogicalResult emitOMPAssumeDirective(const OMPAssumeDirective &s)
mlir::Value emitVAArg(VAArgExpr *ve)
Generate code to get an argument from the passed in pointer and update it accordingly.
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.
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
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:193
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:260
Represents a call to a CUDA kernel function.
Definition ExprCXX.h:238
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a C++ constructor within a class.
Definition DeclCXX.h:2641
Represents a C++ base or member initializer.
Definition DeclCXX.h:2406
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:485
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:1755
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2749
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Represents a C++ temporary.
Definition ExprCXX.h:1463
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1212
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:852
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
CaseStmt - Represent a case statement.
Definition Stmt.h:1932
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3720
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4344
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3649
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
ContinueStmt - This represents a continue.
Definition Stmt.h:3131
Represents a 'co_return' statement in the C++ Coroutines TS.
Definition StmtCXX.h:474
Represents the body of a coroutine.
Definition StmtCXX.h:321
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:1290
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2844
This represents one expression.
Definition Expr.h:113
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:145
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6660
Represents a member of a struct/union/class.
Definition Decl.h:3295
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Represents a function declaration or definition.
Definition Decl.h:2059
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
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:2981
IndirectGotoStmt - This represents an indirect goto.
Definition Stmt.h:3020
Describes an C or C++ initializer list.
Definition Expr.h:5352
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...
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
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:1198
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1248
Represents a parameter to a function.
Definition Decl.h:1820
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2049
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6854
A (possibly-)qualified type.
Definition TypeBase.h:938
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8541
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
Flags to identify the types for overloaded SVE builtins.
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
Exposes information about the current target.
Definition TargetInfo.h:226
Represents a declaration of a type.
Definition Decl.h:3648
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:2288
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:5001
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
Represents a variable declaration or definition.
Definition Decl.h:933
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4080
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &cgOpts, const LangOptions &langOpts)
shouldEmitLifetimeMarkers - Decide whether we need emit the life-time markers.
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.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
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
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
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
#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.
A cleanup that was pushed to the EH stack but whose deactivation is deferred until the enclosing Clea...
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)
A cleanup entry that will be promoted onto the EH scope stack at a later point.
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
The this pointer adjustment as well as an optional return adjustment for a thunk.
Definition Thunk.h:157