clang 24.0.0git
CIRGenFunction.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Internal per-function state used for AST-to-ClangIR code gen
10//
11//===----------------------------------------------------------------------===//
12
13#include "CIRGenFunction.h"
14
15#include "CIRGenCXXABI.h"
16#include "CIRGenCall.h"
18#include "CIRGenValue.h"
19#include "mlir/IR/Location.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/ExprCXX.h"
27#include "llvm/ADT/ScopeExit.h"
28#include "llvm/IR/FPEnv.h"
29
30#include <cassert>
31
32namespace clang::CIRGen {
33
34/// Does the statement tree rooted at \p s contain a label, switch, or indirect
35/// goto that could bypass a local's initialization? A coarse stand-in for
36/// classic CodeGen's per-decl bypass analysis (PR28267).
37static bool functionMightHaveBypass(const Stmt *s) {
38 if (!s)
39 return false;
41 return true;
42 for (const Stmt *child : s->children())
43 if (functionMightHaveBypass(child))
44 return true;
45 return false;
46}
47
49 bool suppressNewContext)
50 : CIRGenTypeCache(cgm), cgm{cgm}, builder(builder),
52 ehStack.setCGF(this);
53 shouldEmitLifetimeMarkers = CodeGenUtils::shouldEmitLifetimeMarkers(
54 cgm.getCodeGenOpts(), getContext().getLangOpts());
56}
57
59
61 cir::FastMathFlags flags = cir::FastMathFlags::none;
62 if (fpFeatures.getAllowFPReassociate())
63 flags = flags | cir::FastMathFlags::reassoc;
64 if (fpFeatures.getNoHonorNaNs())
65 flags = flags | cir::FastMathFlags::nnan;
66 if (fpFeatures.getNoHonorInfs())
67 flags = flags | cir::FastMathFlags::ninf;
68 if (fpFeatures.getNoSignedZero())
69 flags = flags | cir::FastMathFlags::nsz;
70 if (fpFeatures.getAllowReciprocal())
71 flags = flags | cir::FastMathFlags::arcp;
72 if (fpFeatures.getAllowApproxFunc())
73 flags = flags | cir::FastMathFlags::afn;
74 if (fpFeatures.allowFPContractAcrossStatement())
75 flags = flags | cir::FastMathFlags::contract;
76 builder.setFastMathFlags(flags);
77}
78
79// This is copied from clang/lib/CodeGen/CodeGenFunction.cpp
81 type = type.getCanonicalType();
82 while (true) {
83 switch (type->getTypeClass()) {
84#define TYPE(name, parent)
85#define ABSTRACT_TYPE(name, parent)
86#define NON_CANONICAL_TYPE(name, parent) case Type::name:
87#define DEPENDENT_TYPE(name, parent) case Type::name:
88#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
89#include "clang/AST/TypeNodes.inc"
90 llvm_unreachable("non-canonical or dependent type in IR-generation");
91
92 case Type::Auto:
93 case Type::DeducedTemplateSpecialization:
94 llvm_unreachable("undeduced type in IR-generation");
95
96 // Various scalar types.
97 case Type::Builtin:
98 case Type::Pointer:
99 case Type::BlockPointer:
100 case Type::LValueReference:
101 case Type::RValueReference:
102 case Type::MemberPointer:
103 case Type::Vector:
104 case Type::ExtVector:
105 case Type::ConstantMatrix:
106 case Type::FunctionProto:
107 case Type::FunctionNoProto:
108 case Type::Enum:
109 case Type::ObjCObjectPointer:
110 case Type::Pipe:
111 case Type::BitInt:
112 case Type::OverflowBehavior:
113 case Type::HLSLAttributedResource:
114 case Type::HLSLInlineSpirv:
115 return cir::TEK_Scalar;
116
117 // Complexes.
118 case Type::Complex:
119 return cir::TEK_Complex;
120
121 // Arrays, records, and Objective-C objects.
122 case Type::ConstantArray:
123 case Type::IncompleteArray:
124 case Type::VariableArray:
125 case Type::Record:
126 case Type::ObjCObject:
127 case Type::ObjCInterface:
128 case Type::ArrayParameter:
129 return cir::TEK_Aggregate;
130
131 // We operate on atomic values according to their underlying type.
132 case Type::Atomic:
133 type = cast<AtomicType>(type)->getValueType();
134 continue;
135 }
136 llvm_unreachable("unknown type kind!");
137 }
138}
139
141 return cgm.getTypes().convertTypeForMem(t);
142}
143
145 return cgm.getTypes().convertType(t);
146}
147
149 // Some AST nodes might contain invalid source locations (e.g.
150 // CXXDefaultArgExpr), workaround that to still get something out.
151 if (srcLoc.isValid()) {
153 PresumedLoc pLoc = sm.getPresumedLoc(srcLoc);
154 StringRef filename = pLoc.getFilename();
155 return mlir::FileLineColLoc::get(builder.getStringAttr(filename),
156 pLoc.getLine(), pLoc.getColumn());
157 }
158 // We expect to have a currSrcLoc set, but it isn't critical for the
159 // correctness of compilation, so in non-assert builds we fallback on using an
160 // unknown location.
161 if (currSrcLoc && currSrcLoc->isValid())
162 return getLoc(*currSrcLoc);
163 // We're brave, but time to give up.
164 return builder.getUnknownLoc();
165}
166
167mlir::Location CIRGenFunction::getLoc(SourceRange srcLoc) {
168 // Some AST nodes might contain invalid source locations (e.g.
169 // CXXDefaultArgExpr), workaround that to still get something out.
170
171 // SourceRange is only valid if BOTH are valid, so get the fused location from
172 // the 2-mlir::Location version of this.
173 if (srcLoc.isValid())
174 return getLoc(getLoc(srcLoc.getBegin()), getLoc(srcLoc.getEnd()));
175
176 // If only ONE of the two is valid, try our hardest to get this right.
177 if (srcLoc.getBegin().isValid())
178 return getLoc(srcLoc.getBegin());
179 if (srcLoc.getEnd().isValid())
180 return getLoc(srcLoc.getEnd());
181
182 // We expect to have a currSrcLoc set, but it isn't critical for the
183 // correctness of compilation, so in non-assert builds we fallback on using an
184 // unknown location.
185 if (currSrcLoc &&
186 (currSrcLoc->getBegin().isValid() || currSrcLoc->getEnd().isValid()))
187 return getLoc(*currSrcLoc);
188 // We're brave, but time to give up.
189 return builder.getUnknownLoc();
190}
191
192mlir::Location CIRGenFunction::getLoc(mlir::Location lhs, mlir::Location rhs) {
193 SmallVector<mlir::Location, 2> locs = {lhs, rhs};
194 mlir::Attribute metadata;
195 return mlir::FusedLoc::get(locs, metadata, &getMLIRContext());
196}
197
198bool CIRGenFunction::containsLabel(const Stmt *s, bool ignoreCaseStmts) {
199 // Null statement, not a label!
200 if (!s)
201 return false;
202
203 // If this is a label, we have to emit the code, consider something like:
204 // if (0) { ... foo: bar(); } goto foo;
205 //
206 // TODO: If anyone cared, we could track __label__'s, since we know that you
207 // can't jump to one from outside their declared region.
208 if (isa<LabelStmt>(s))
209 return true;
210
211 // If this is a case/default statement, and we haven't seen a switch, we
212 // have to emit the code.
213 if (isa<SwitchCase>(s) && !ignoreCaseStmts)
214 return true;
215
216 // If this is a switch statement, we want to ignore case statements when we
217 // recursively process the sub-statements of the switch. If we haven't
218 // encountered a switch statement, we treat case statements like labels, but
219 // if we are processing a switch statement, case statements are expected.
220 if (isa<SwitchStmt>(s))
221 ignoreCaseStmts = true;
222
223 // Scan subexpressions for verboten labels.
224 return std::any_of(s->child_begin(), s->child_end(),
225 [=](const Stmt *subStmt) {
226 return containsLabel(subStmt, ignoreCaseStmts);
227 });
228}
229
230/// If the specified expression does not fold to a constant, or if it does but
231/// contains a label, return false. If it constant folds return true and set
232/// the boolean result in Result.
233bool CIRGenFunction::constantFoldsToBool(const Expr *cond, bool &resultBool,
234 bool allowLabels) {
235 llvm::APSInt resultInt;
236 if (!constantFoldsToSimpleInteger(cond, resultInt, allowLabels))
237 return false;
238
239 resultBool = resultInt.getBoolValue();
240 return true;
241}
242
243/// If the specified expression does not fold to a constant, or if it does
244/// fold but contains a label, return false. If it constant folds, return
245/// true and set the folded value.
247 llvm::APSInt &resultInt,
248 bool allowLabels) {
249 // FIXME: Rename and handle conversion of other evaluatable things
250 // to bool.
251 Expr::EvalResult result;
252 if (!cond->EvaluateAsInt(result, getContext()))
253 return false; // Not foldable, not integer or not fully evaluatable.
254
255 llvm::APSInt intValue = result.Val.getInt();
256 if (!allowLabels && containsLabel(cond))
257 return false; // Contains a label.
258
259 resultInt = intValue;
260 return true;
261}
262
263void CIRGenFunction::emitAndUpdateRetAlloca(QualType type, mlir::Location loc,
264 CharUnits alignment) {
265 if (!type->isVoidType()) {
266 Address allocaAddr = Address::invalid();
267 returnValue = createMemTemp(type, alignment, loc, "", &allocaAddr);
268 mlir::cast<cir::AllocaOp>(allocaAddr.getDefiningOp()).setReturnSlot(true);
269 fnRetAlloca = allocaAddr.getPointer();
270 }
271}
272
273void CIRGenFunction::declare(mlir::Value addrVal, const Decl *var, QualType ty,
274 mlir::Location loc, CharUnits alignment,
275 bool isParam) {
276 assert(isa<NamedDecl>(var) && "Needs a named decl");
277 assert(!symbolTable.count(var) && "not supposed to be available just yet");
278
279 Address addr(addrVal, alignment);
280 cir::AllocaOp allocaOp = addr.getUnderlyingAllocaOp();
281 assert(allocaOp && "expected cir::AllocaOp");
282
283 if (isParam)
284 allocaOp.setInitAttr(mlir::UnitAttr::get(&getMLIRContext()));
285 if (ty->isReferenceType() || ty.isConstQualified())
286 allocaOp.setConstantAttr(mlir::UnitAttr::get(&getMLIRContext()));
287
288 symbolTable.insert(var, addrVal);
289}
290
291void CIRGenFunction::emitVarAnnotations(const VarDecl *d, mlir::Value addr) {
292 assert(d->hasAttr<AnnotateAttr>() && "no annotate attribute");
293 for (const auto *attr : d->specific_attrs<AnnotateAttr>())
294 cir::VarAnnotationOp::create(builder, getLoc(d->getLocation()), addr,
295 cgm.emitAnnotateAttr(attr));
296}
297
299 Address addr) {
300 assert(field->hasAttr<AnnotateAttr>() && "no annotate attribute");
301 mlir::Value ptr = addr.getPointer();
302 for (const auto *attr : field->specific_attrs<AnnotateAttr>())
303 ptr = cir::PtrAnnotationOp::create(builder, getLoc(field->getLocation()),
304 ptr, cgm.emitAnnotateAttr(attr));
305 return addr.withPointer(ptr);
306}
307
309 CIRGenBuilderTy &builder = cgf.builder;
310 LexicalScope *localScope = cgf.curLexScope;
311
312 // Process all return blocks — emit cir.return ops.
313 // TODO(cir): Handle returning from a switch statement through a cleanup
314 // block. We can't simply jump to the cleanup block, because the cleanup block
315 // is not part of the case region. Either reemit all cleanups in the return
316 // block or wait for MLIR structured control flow to support early exits.
318 for (mlir::Block *retBlock : localScope->getRetBlocks()) {
319 mlir::OpBuilder::InsertionGuard guard(builder);
320 builder.setInsertionPointToEnd(retBlock);
321 retBlocks.push_back(retBlock);
322 mlir::Location retLoc = localScope->getRetLoc(retBlock);
323 emitReturn(retLoc);
324 }
325
326 // Pop cleanup scopes from the EH stack. In CIR, this emits cleanup code
327 // into the cleanup regions of cir.cleanup.scope ops — no CFG-level cleanup
328 // blocks or branches are needed.
329 if (performCleanup) {
331 forceCleanup();
332 }
333
334 mlir::Block *curBlock = builder.getBlock();
335 if (isGlobalInit() && !curBlock)
336 return;
337 if (curBlock->mightHaveTerminator() && curBlock->getTerminator())
338 return;
339
340 // Get rid of any empty block at the end of the scope. An empty non-entry
341 // block is created when a terminator (return/break/continue) is followed
342 // by unreachable code.
343 bool isEntryBlock = builder.getInsertionBlock()->isEntryBlock();
344 if (!isEntryBlock && curBlock->empty()) {
345 curBlock->erase();
346 for (mlir::Block *retBlock : retBlocks) {
347 if (retBlock->getUses().empty())
348 retBlock->erase();
349 }
350 return;
351 }
352
353 if (localScope->depth == 0) {
354 // Reached the end of the function.
355 if (localScope->getRetBlocks().size() == 1) {
356 mlir::Block *retBlock = localScope->getRetBlocks()[0];
357 mlir::Location retLoc = localScope->getRetLoc(retBlock);
358 if (retBlock->getUses().empty()) {
359 retBlock->erase();
360 } else {
361 cir::BrOp::create(builder, retLoc, retBlock);
362 return;
363 }
364 }
365 emitImplicitReturn();
366 return;
367 }
368
369 // End of any local scope != function.
370 // Ternary ops have to deal with matching arms for yielding types
371 // and do return a value, it must do its own cir.yield insertion.
372 if (!localScope->isTernary() && !curBlock->mightHaveTerminator()) {
373 !retVal ? cir::YieldOp::create(builder, localScope->endLoc)
374 : cir::YieldOp::create(builder, localScope->endLoc, retVal);
375 }
376}
377
378cir::ReturnOp CIRGenFunction::LexicalScope::emitReturn(mlir::Location loc) {
379 CIRGenBuilderTy &builder = cgf.getBuilder();
380
381 auto fn = dyn_cast<cir::FuncOp>(cgf.curFn);
382 assert(fn && "emitReturn from non-function");
383
384 if (!fn.getFunctionType().hasVoidReturn()) {
385 // Load the value from the return slot and return it via `cir.return`.
386 auto value = cir::LoadOp::create(
387 builder, loc, fn.getFunctionType().getReturnType(), *cgf.fnRetAlloca);
388 return cir::ReturnOp::create(builder, loc,
389 llvm::ArrayRef(value.getResult()));
390 }
391 return cir::ReturnOp::create(builder, loc);
392}
393
394// This is copied from CodeGenModule::MayDropFunctionReturn. This is a
395// candidate for sharing between CIRGen and CodeGen.
396static bool mayDropFunctionReturn(const ASTContext &astContext,
397 QualType returnType) {
398 // We can't just discard the return value for a record type with a complex
399 // destructor or a non-trivially copyable type.
400 if (const auto *classDecl = returnType->getAsCXXRecordDecl())
401 return classDecl->hasTrivialDestructor();
402 return returnType.isTriviallyCopyableType(astContext);
403}
404
405static bool previousOpIsNonYieldingCleanup(mlir::Block *block) {
406 if (block->empty())
407 return false;
408 mlir::Operation *op = &block->back();
409 auto cleanupScopeOp = mlir::dyn_cast<cir::CleanupScopeOp>(op);
410 if (!cleanupScopeOp)
411 return false;
412
413 // Check whether the body region of the cleanup scope exits via cir.yield.
414 // Exits via cir.return or cir.goto do not fall through to the operation
415 // following the cleanup scope, and exits via break, continue, and resume
416 // are not expected here.
417 for (mlir::Block &bodyBlock : cleanupScopeOp.getBodyRegion()) {
418 if (bodyBlock.mightHaveTerminator()) {
419 if (mlir::isa<cir::YieldOp>(bodyBlock.getTerminator()))
420 return false;
421 assert(!mlir::isa<cir::BreakOp>(bodyBlock.getTerminator()) &&
422 !mlir::isa<cir::ContinueOp>(bodyBlock.getTerminator()) &&
423 !mlir::isa<cir::ResumeOp>(bodyBlock.getTerminator()));
424 }
425 }
426 return true;
427}
428
429void CIRGenFunction::LexicalScope::emitImplicitReturn() {
430 CIRGenBuilderTy &builder = cgf.getBuilder();
431 LexicalScope *localScope = cgf.curLexScope;
432
433 // Synthesized functions (e.g. SYCL kernel caller entry points) have no
434 // FunctionDecl; the non-void flow-off-the-end handling below is guarded on
435 // fd.
436 const auto *fd = dyn_cast_or_null<clang::FunctionDecl>(cgf.curGD.getDecl());
437
438 // In C++, flowing off the end of a non-void function is always undefined
439 // behavior. In C, flowing off the end of a non-void function is undefined
440 // behavior only if the non-existent return value is used by the caller.
441 // That influences whether the terminating op is trap, unreachable, or
442 // return.
443 if (fd && cgf.getLangOpts().CPlusPlus && !fd->hasImplicitReturnZero() &&
444 !cgf.sawAsmBlock && !fd->getReturnType()->isVoidType() &&
445 builder.getInsertionBlock() &&
446 !previousOpIsNonYieldingCleanup(builder.getInsertionBlock())) {
447 bool shouldEmitUnreachable =
448 cgf.cgm.getCodeGenOpts().StrictReturn ||
449 !mayDropFunctionReturn(fd->getASTContext(), fd->getReturnType());
450
451 if (shouldEmitUnreachable) {
453 if (cgf.cgm.getCodeGenOpts().OptimizationLevel == 0)
454 cir::TrapOp::create(builder, localScope->endLoc, /*implicit=*/true);
455 else
456 cir::UnreachableOp::create(builder, localScope->endLoc,
457 /*implicit=*/true);
458 builder.clearInsertionPoint();
459 return;
460 }
461 }
462
463 emitReturn(localScope->endLoc).setImplicit(true);
464}
465
467 LexicalScope *scope = this;
468 while (scope) {
469 if (scope->isTry())
470 return scope->getTry();
471 scope = scope->parentScope;
472 }
473 return nullptr;
474}
475
476/// An argument came in as a promoted argument; demote it back to its
477/// declared type.
478static mlir::Value emitArgumentDemotion(CIRGenFunction &cgf, const VarDecl *var,
479 mlir::Value value) {
480 mlir::Type ty = cgf.convertType(var->getType());
481
482 // This can happen with promotions that actually don't change the
483 // underlying type, like the enum promotions.
484 if (value.getType() == ty)
485 return value;
486
487 assert((mlir::isa<cir::IntType>(ty) || cir::isAnyFloatingPointType(ty)) &&
488 "unexpected promotion type");
489
490 if (mlir::isa<cir::IntType>(ty))
491 return cgf.getBuilder().CIRBaseBuilderTy::createIntCast(value, ty);
492
493 return cgf.getBuilder().createFloatingCast(value, ty);
494}
495
497 mlir::Block *entryBB,
498 const FunctionDecl *fd,
499 SourceLocation bodyBeginLoc) {
500 // Naked functions don't have prologues.
501 if (fd && fd->hasAttr<NakedAttr>()) {
502 cgm.errorNYI(bodyBeginLoc, "naked function decl");
503 }
504
505 // If this is an implicit-return-zero function, initialize the return value.
506 if (fd && fd->hasImplicitReturnZero()) {
507 mlir::Type retTy = convertType(fd->getReturnType().getUnqualifiedType());
508 mlir::Location loc = getLoc(bodyBeginLoc);
509 mlir::Value zero = builder.getNullValue(retTy, loc);
510 builder.CIRBaseBuilderTy::createStore(loc, zero, returnValue.getPointer());
511 }
512
513 // Declare all the function arguments in the symbol table.
514 for (const auto nameValue : llvm::zip(args, entryBB->getArguments())) {
515 const VarDecl *paramVar = std::get<0>(nameValue);
516 mlir::Value paramVal = std::get<1>(nameValue);
517 CharUnits alignment = getContext().getDeclAlign(paramVar);
518 mlir::Location paramLoc = getLoc(paramVar->getSourceRange());
519 paramVal.setLoc(paramLoc);
520
521 mlir::Value addrVal =
522 emitAlloca(cast<NamedDecl>(paramVar)->getName(),
523 convertType(paramVar->getType()), paramLoc, alignment,
524 /*insertIntoFnEntryBlock=*/true);
525
526 mlir::ptr::MemorySpaceAttrInterface destAddrSpace =
528 paramVar->getType().getAddressSpace());
529 Address addr = Address(addrVal, alignment);
530 addr = maybeCastStackAddressSpace(addr, destAddrSpace);
531
532 declare(addr.getPointer(), paramVar, paramVar->getType(), paramLoc,
533 alignment,
534 /*isParam=*/true);
535
536 setAddrOfLocalVar(paramVar, addr);
537
538 bool isPromoted = isa<ParmVarDecl>(paramVar) &&
539 cast<ParmVarDecl>(paramVar)->isKNRPromoted();
541 if (isPromoted)
542 paramVal = emitArgumentDemotion(*this, paramVar, paramVal);
543
544 // Location of the store to the param storage tracked as beginning of
545 // the function body.
546 mlir::Location fnBodyBegin = getLoc(bodyBeginLoc);
547 builder.CIRBaseBuilderTy::createStore(fnBodyBegin, paramVal,
548 addr.getPointer());
549
550 if (paramVar->hasAttr<AnnotateAttr>())
551 emitVarAnnotations(paramVar, addr.getPointer());
552 }
553 assert(builder.getInsertionBlock() && "Should be valid");
554}
555
557 cir::FuncOp fn, cir::FuncType funcType,
559 SourceLocation startLoc) {
560 assert(!curFn &&
561 "CIRGenFunction can only be used for one function at a time");
562
563 curFn = fn;
564
565 const Decl *d = gd.getDecl();
566
567 didCallStackSave = false;
568 curCodeDecl = d;
569 const auto *fd = dyn_cast_or_null<FunctionDecl>(d);
570 curFuncDecl = (d ? d->getNonClosureContext() : nullptr);
571
572 // Recursion is disallowed for C++ main, OpenCL, HLSL, SYCL device code and
573 // CUDA/HIP kernels.
574 if (fd &&
575 ((getLangOpts().CPlusPlus && fd->isMain()) || getLangOpts().OpenCL ||
576 getLangOpts().HLSL || getLangOpts().SYCLIsDevice ||
577 (getLangOpts().CUDA && fd->hasAttr<CUDAGlobalAttr>())))
578 fn->setAttr(cir::CIRDialect::getNoRecurseAttrName(),
579 mlir::UnitAttr::get(fn.getContext()));
580
581 // This is an artifact of the legacy handling of constrained floating-point
582 // modes. The rounding mode and exception behavior tracked in
583 // clang::LangOptions don't correspond directly to the representation we
584 // use in CIR, but the CIR settings can be derived from them. We track the
585 // default state using the legacy settings because it keeps the tracking in
586 // sync with classic codegen.
587 llvm::RoundingMode rm = getLangOpts().getDefaultRoundingMode();
589 builder.setDefaultConstrainedRounding(rm);
590 builder.setDefaultConstrainedExcept(eb);
591 builder.setIsFPConstrained(false);
592 if ((fd && (fd->UsesFPIntrin() || fd->hasAttr<StrictFPAttr>())) ||
594 rm != llvm::RoundingMode::NearestTiesToEven))) {
595 builder.setIsFPConstrained(true);
596 fn->setAttr(cir::CIRDialect::getStrictFPAttrName(),
597 mlir::UnitAttr::get(fn.getContext()));
598 }
599 mlir::Block *entryBB = &fn.getBlocks().front();
600 builder.setInsertionPointToStart(entryBB);
601
602 // When the current function is not void, create an address to store the
603 // result value.
604 if (!returnType->isVoidType()) {
605 // Determine the function body end location. A function without a body
606 // uses its declaration's location, and a null fd uses loc.
607 SourceLocation bodyEndLoc = loc;
608 if (fd) {
609 if (Stmt *body = fd->getBody())
610 bodyEndLoc = body->getEndLoc();
611 else
612 bodyEndLoc = fd->getLocation();
613 }
614 emitAndUpdateRetAlloca(returnType, getLoc(bodyEndLoc),
615 getContext().getTypeAlignInChars(returnType));
616 }
617
618 // Wrap the rest of the function in a filter try when this declaration has
619 // a dynamic exception specification. Parameter cleanups are pushed after
620 // this so they nest inside the specification, matching classic codegen.
622 prologueCleanupDepth = ehStack.stable_begin();
623
624 // Determine the function body begin location for the prolog. A function
625 // without a body uses its declaration's location, and a null fd uses
626 // startLoc.
627 SourceLocation bodyBeginLoc = startLoc;
628 if (fd) {
629 if (Stmt *body = fd->getBody())
630 bodyBeginLoc = body->getBeginLoc();
631 else
632 bodyBeginLoc = fd->getLocation();
633 }
634
635 emitFunctionProlog(args, entryBB, fd, bodyBeginLoc);
636
637 if (const auto *md = dyn_cast_if_present<CXXMethodDecl>(d);
638 md && !md->isStatic()) {
639 bool isInLambda =
640 md->getParent()->isLambda() && md->getOverloadedOperator() == OO_Call;
641
642 if (md->isImplicitObjectMemberFunction())
643 cgm.getCXXABI().emitInstanceFunctionProlog(loc, *this);
644
645 if (isInLambda) {
646 // We're in a lambda; figure out the captures.
647 auto fn = cast<cir::FuncOp>(curFn);
648 fn.setLambda(true);
649
650 md->getParent()->getCaptureFields(lambdaCaptureFields,
653 // If the lambda captures the object referred to by '*this' - either by
654 // value or by reference, make sure CXXThisValue points to the correct
655 // object.
656
657 // Get the lvalue for the field (which is a copy of the enclosing object
658 // or contains the address of the enclosing object).
659 LValue thisFieldLValue =
661 if (!lambdaThisCaptureField->getType()->isPointerType()) {
662 // If the enclosing object was captured by value, just use its
663 // address. Sign this pointer.
664 cxxThisValue = thisFieldLValue.getPointer();
665 } else {
666 // Load the lvalue pointed to by the field, since '*this' was captured
667 // by reference.
669 emitLoadOfLValue(thisFieldLValue, SourceLocation()).getValue();
670 }
671 }
672 for (auto *fd : md->getParent()->fields()) {
673 if (fd->hasCapturedVLAType()) {
674 mlir::Value exprArg =
676 .getValue();
677 const VariableArrayType *vat = fd->getCapturedVLAType();
678 vlaSizeMap[vat->getSizeExpr()] = exprArg;
679 }
680 }
681 } else if (md->isImplicitObjectMemberFunction()) {
682 // Not in a lambda; just use 'this' from the method.
683 // FIXME: Should we generate a new load for each use of 'this'? The fast
684 // register allocator would be happier...
686 }
687
690 }
691
692 // If any of the arguments have a variably modified type, make sure to
693 // emit the type size, but only if the function is not naked. Naked functions
694 // have no prolog to run this evaluation.
695 if (!fd || !fd->hasAttr<NakedAttr>()) {
696 for (const VarDecl *vd : args) {
697 // Dig out the type as written from ParmVarDecls; it's unclear whether
698 // the standard (C99 6.9.1p10) requires this, but we're following the
699 // precedent set by gcc.
700 QualType ty;
701 if (const auto *pvd = dyn_cast<ParmVarDecl>(vd))
702 ty = pvd->getOriginalType();
703 else
704 ty = vd->getType();
705 if (ty->isVariablyModifiedType())
707 }
708 }
709}
710
712 // Pop any cleanups that might have been associated with the
713 // parameters. Do this in whatever block we're currently in; it's
714 // important to do this before we enter the return block or return
715 // edges will be *really* confused.
716 // TODO(cir): Use prologueCleanupDepth here.
717 bool hasCleanups = ehStack.stable_begin() != prologueCleanupDepth;
718 if (hasCleanups) {
720 // FIXME(cir): should we clearInsertionPoint? breaks many testcases
722 }
723
724 assert(deferredConditionalCleanupStack.empty() &&
725 "deferred conditional cleanups were not consumed by a "
726 "FullExprCleanupScope");
727
729}
730
731mlir::LogicalResult CIRGenFunction::emitFunctionBody(const clang::Stmt *body) {
732 // We start with function level scope for variables.
734
735 if (const CompoundStmt *block = dyn_cast<CompoundStmt>(body))
736 return emitCompoundStmtWithoutScope(*block);
737
738 return emitStmt(body, /*useCurrentScope=*/true);
739}
740
742 // Remove any leftover blocks that are unreachable and empty, since they do
743 // not represent unreachable code useful for warnings nor anything deemed
744 // useful in general.
745 SmallVector<mlir::Block *> blocksToDelete;
746 for (mlir::Block &block : func.getBlocks()) {
747 if (block.empty() && block.getUses().empty())
748 blocksToDelete.push_back(&block);
749 }
750 for (mlir::Block *block : blocksToDelete)
751 block->erase();
752}
753
754cir::FuncOp CIRGenFunction::generateCode(clang::GlobalDecl gd, cir::FuncOp fn,
755 cir::FuncType funcType) {
756 const auto *funcDecl = cast<FunctionDecl>(gd.getDecl());
757 curGD = gd;
758
759 if (funcDecl->isInlineBuiltinDeclaration()) {
760 // When generating code for a builtin with an inline declaration, use a
761 // mangled name to hold the actual body, while keeping an external
762 // declaration in case the function pointer is referenced somewhere.
763 std::string fdInlineName = (cgm.getMangledName(funcDecl) + ".inline").str();
764 cir::FuncOp clone =
765 mlir::cast_or_null<cir::FuncOp>(cgm.getGlobalValue(fdInlineName));
766 if (!clone) {
767 mlir::OpBuilder::InsertionGuard guard(builder);
768 builder.setInsertionPoint(fn);
769 clone = cir::FuncOp::create(builder, fn.getLoc(), fdInlineName,
770 fn.getFunctionType());
771 cgm.insertGlobalSymbol(clone);
772 clone.setLinkage(cir::GlobalLinkageKind::InternalLinkage);
773 clone.setSymVisibility("private");
774 clone.setInlineKind(cir::InlineKind::AlwaysInline);
775 }
776 fn.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
777 fn.setSymVisibility("private");
778 fn = clone;
779 } else {
780 // Detect the unusual situation where an inline version is shadowed by a
781 // non-inline version. In that case we should pick the external one
782 // everywhere. That's GCC behavior too.
783 for (const FunctionDecl *pd = funcDecl->getPreviousDecl(); pd;
784 pd = pd->getPreviousDecl()) {
785 if (LLVM_UNLIKELY(pd->isInlineBuiltinDeclaration())) {
786 std::string inlineName = funcDecl->getName().str() + ".inline";
787 if (auto inlineFn = mlir::cast_or_null<cir::FuncOp>(
788 cgm.getGlobalValue(inlineName))) {
789 // Replace all uses of the .inline function with the regular function
790 // FIXME: This performs a linear walk over the module. Introduce some
791 // caching here.
792 if (inlineFn
793 .replaceAllSymbolUses(fn.getSymNameAttr(), cgm.getModule())
794 .failed())
795 llvm_unreachable("Failed to replace inline builtin symbol uses");
796 cgm.eraseGlobalSymbol(inlineFn);
797 inlineFn.erase();
798 }
799 break;
800 }
801 }
802 }
803
804 SourceLocation loc = funcDecl->getLocation();
805 Stmt *body = funcDecl->getBody();
806 SourceRange bodyRange =
807 body ? body->getSourceRange() : funcDecl->getLocation();
808
809 SourceLocRAIIObject fnLoc{*this, funcDecl->getSourceRange()};
810
811 auto validMLIRLoc = [&](clang::SourceLocation clangLoc) {
812 return clangLoc.isValid() ? getLoc(clangLoc) : builder.getUnknownLoc();
813 };
814 const mlir::Location fusedLoc = mlir::FusedLoc::get(
816 {validMLIRLoc(bodyRange.getBegin()), validMLIRLoc(bodyRange.getEnd())});
817 mlir::Block *entryBB = fn.addEntryBlock();
818
819 FunctionArgList args;
820 QualType retTy = buildFunctionArgList(gd, args);
821
822 // Create a scope in the symbol table to hold variable declarations.
824 {
825 LexicalScope lexScope(*this, fusedLoc, entryBB);
826
827 // Emit the standard function prologue.
828 startFunction(gd, retTy, fn, funcType, args, loc, bodyRange.getBegin());
829
830 // Save parameters for coroutine function.
831 if (body && isa_and_nonnull<CoroutineBodyStmt>(body))
832 llvm::append_range(fnArgs, funcDecl->parameters());
833
835 fn->setAttr(cir::CIRDialect::getMustProgressAttrName(),
836 mlir::UnitAttr::get(&getMLIRContext()));
837
838 if (shouldEmitLifetimeMarkers)
839 fnHasBypassStmt = functionMightHaveBypass(body);
840
841 if (isa<CXXDestructorDecl>(funcDecl)) {
842 emitDestructorBody(args);
843 } else if (isa<CXXConstructorDecl>(funcDecl)) {
845 } else if (getLangOpts().CUDA && !getLangOpts().CUDAIsDevice &&
846 funcDecl->hasAttr<CUDAGlobalAttr>()) {
847 cgm.getCUDARuntime().emitDeviceStub(*this, fn, args);
848 } else if (isa<CXXMethodDecl>(funcDecl) &&
849 cast<CXXMethodDecl>(funcDecl)->isLambdaStaticInvoker()) {
850 // The lambda static invoker function is special, because it forwards or
851 // clones the body of the function call operator (but is actually
852 // static).
854 } else if (funcDecl->isDefaulted() && isa<CXXMethodDecl>(funcDecl) &&
855 (cast<CXXMethodDecl>(funcDecl)->isCopyAssignmentOperator() ||
856 cast<CXXMethodDecl>(funcDecl)->isMoveAssignmentOperator())) {
857 // Implicit copy-assignment gets the same special treatment as implicit
858 // copy-constructors.
860 } else if (body) {
861 // Emit standard function body.
862 if (mlir::failed(emitFunctionBody(body))) {
863 return nullptr;
864 }
865 } else {
866 // Anything without a body should have been handled above.
867 llvm_unreachable("no definition for normal function");
868 }
869
870 // Finish the function (including closing a dynamic exception
871 // specification try) before verifying so the try body is terminated.
872 finishFunction(bodyRange.getEnd());
873
874 if (mlir::failed(fn.verifyBody()))
875 return nullptr;
876 }
877
878 if (getLangOpts().OpenCL && funcDecl->hasAttr<DeviceKernelAttr>())
879 cgm.emitOpenCLKernelArgMetadata(fn, funcDecl);
880
882 return fn;
883}
884
887 const auto *ctor = cast<CXXConstructorDecl>(curGD.getDecl());
888 CXXCtorType ctorType = curGD.getCtorType();
889
890 assert((cgm.getTarget().getCXXABI().hasConstructorVariants() ||
891 ctorType == Ctor_Complete) &&
892 "can only generate complete ctor for this ABI");
893
894 cgm.setFuncInfoAttr(cast<cir::FuncOp>(curFn), ctor);
895
896 if (ctorType == Ctor_Complete && isConstructorDelegationValid(ctor) &&
897 cgm.getTarget().getCXXABI().hasConstructorVariants()) {
898 emitDelegateCXXConstructorCall(ctor, Ctor_Base, args, ctor->getEndLoc());
899 return;
900 }
901
902 const FunctionDecl *definition = nullptr;
903 Stmt *body = ctor->getBody(definition);
904 assert(definition == ctor && "emitting wrong constructor body");
905
906 bool isTryBody = isa_and_nonnull<CXXTryStmt>(body);
907
908 // A type that handles the emission of the constructor body, that can be
909 // called directly for cases where we don't have a try-body, or passed to
910 // emitCXXTryStmt.
911 struct ctorTryBodyEmitter final : cxxTryBodyEmitter {
912 const CXXConstructorDecl *ctor = nullptr;
913 CXXCtorType ctorType;
914 FunctionArgList &args;
915 Stmt *emitterBody = nullptr;
916 ctorTryBodyEmitter(const CXXConstructorDecl *ctor, CXXCtorType ctorType,
917 FunctionArgList &args, bool isTryBody, Stmt *b)
918 : ctor(ctor), ctorType(ctorType), args(args),
919 emitterBody(isTryBody ? cast<CXXTryStmt>(b)->getTryBlock() : b) {}
920 ~ctorTryBodyEmitter() override = default;
921
922 mlir::LogicalResult operator()(CIRGenFunction &cgf) override {
925
926 //// TODO: in restricted cases, we can emit the vbase initializers of a
927 //// complete ctor and then delegate to the base ctor.
928
929 cgf.emitCtorPrologue(ctor, ctorType, args);
930 return cgf.emitStmt(emitterBody, /*useCurrentScope=*/true);
931 }
932 };
933
934 ctorTryBodyEmitter emitter{ctor, ctorType, args, isTryBody, body};
935 mlir::LogicalResult bodyRes =
936 isTryBody ? emitCXXTryStmt(*cast<CXXTryStmt>(body), emitter,
937 /*isFnTryBlock=*/true)
938 : emitter(*this);
939
940 // TODO(cir): propagate this result via mlir::logical result. Just
941 // unreachable now just to have it handled.
942 if (bodyRes.failed())
943 cgm.errorNYI(ctor->getSourceRange(),
944 "emitConstructorBody: emit body statement failed.");
945}
946
947/// Emits the body of the current destructor.
949 const CXXDestructorDecl *dtor = cast<CXXDestructorDecl>(curGD.getDecl());
950 CXXDtorType dtorType = curGD.getDtorType();
951
952 cgm.setFuncInfoAttr(cast<cir::FuncOp>(curFn), dtor);
953
954 // For an abstract class, non-base destructors are never used (and can't
955 // be emitted in general, because vbase dtors may not have been validated
956 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
957 // in fact emit references to them from other compilations, so emit them
958 // as functions containing a trap instruction.
959 Stmt *body = dtor->getBody();
960 if (dtorType != Dtor_Base && dtor->getParent()->isAbstract()) {
961 SourceLocation loc = body ? body->getBeginLoc() : dtor->getLocation();
962 emitTrap(getLoc(loc), true);
963 return;
964 }
965
967
968 // The call to operator delete in a deleting destructor happens
969 // outside of the function-try-block, which means it's always
970 // possible to delegate the destructor body to the complete
971 // destructor. Do so.
972 if (dtorType == Dtor_Deleting || dtorType == Dtor_VectorDeleting) {
974 cgm.errorNYI(dtor->getSourceRange(), "emitConditionalArrayDtorCall");
975
976 // A destroying operator delete destroys the object and deallocates its
977 // storage, so the deleting destructor only calls the operator delete.
978 const FunctionDecl *operatorDelete = dtor->getOperatorDelete();
979 if (operatorDelete->isDestroyingOperatorDelete()) {
981 // The implicit parameter of a deleting destructor is the Microsoft ABI.
982 cgm.errorNYI(dtor->getSourceRange(), "emitConditionalArrayDtorCall");
983 }
984 emitDeleteCall(operatorDelete, loadThisForDtorDelete(dtor),
985 getContext().getCanonicalTagType(dtor->getParent()));
986 return;
987 }
988
989 RunCleanupsScope dtorEpilogue(*this);
992 emitCXXDestructorCall(dtor, Dtor_Complete, /*forVirtualBase=*/false,
993 /*delegating=*/false, loadCXXThisAddress(), thisTy);
994 return;
995 }
996
997 // If the body is a function-try-block, enter the try before
998 // anything else.
999 const bool isTryBody = isa_and_nonnull<CXXTryStmt>(body);
1000 if (isTryBody)
1001 cgm.errorNYI(dtor->getSourceRange(), "function-try-block destructor");
1002
1004
1005 // Enter the epilogue cleanups.
1006 RunCleanupsScope dtorEpilogue(*this);
1007
1008 // If this is the complete variant, just invoke the base variant;
1009 // the epilogue will destruct the virtual bases. But we can't do
1010 // this optimization if the body is a function-try-block, because
1011 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1012 // always delegate because we might not have a definition in this TU.
1013 switch (dtorType) {
1014 case Dtor_Unified:
1015 llvm_unreachable("not expecting a unified dtor");
1016 case Dtor_Comdat:
1017 llvm_unreachable("not expecting a COMDAT");
1018 case Dtor_Deleting:
1020 llvm_unreachable("already handled deleting case");
1021
1022 case Dtor_Complete:
1023 assert((body || getTarget().getCXXABI().isMicrosoft()) &&
1024 "can't emit a dtor without a body for non-Microsoft ABIs");
1025
1026 // Enter the cleanup scopes for virtual bases.
1028
1029 if (!isTryBody) {
1031 emitCXXDestructorCall(dtor, Dtor_Base, /*forVirtualBase=*/false,
1032 /*delegating=*/false, loadCXXThisAddress(), thisTy);
1033 break;
1034 }
1035
1036 // Fallthrough: act like we're in the base variant.
1037 [[fallthrough]];
1038
1039 case Dtor_Base:
1040 assert(body);
1041
1042 bool needsVTableInit =
1044 // Launder 'this' if necessary.
1045 if (needsVTableInit && cgm.getCodeGenOpts().StrictVTablePointers &&
1046 cgm.getCodeGenOpts().OptimizationLevel > 0) {
1047 cxxThisValue = cir::LaunderOp::create(
1048 builder, getLoc(dtor->getBeginLoc()), loadCXXThis());
1049 }
1050
1051 // Enter the cleanup scopes for fields and non-virtual bases.
1053
1054 // Initialize the vtable pointers before entering the body.
1055 if (needsVTableInit)
1057
1058 if (isTryBody) {
1059 cgm.errorNYI(dtor->getSourceRange(), "function-try-block destructor");
1060 } else if (body) {
1061 (void)emitStmt(body, /*useCurrentScope=*/true);
1062 } else {
1063 assert(dtor->isImplicit() && "bodyless dtor not implicit");
1064 // nothing to do besides what's in the epilogue
1065 }
1066 // -fapple-kext must inline any call to this dtor into
1067 // the caller's body.
1069
1070 break;
1071 }
1072
1073 // Jump out through the epilogue cleanups.
1074 dtorEpilogue.forceCleanup();
1075
1076 // Exit the try if applicable.
1077 if (isTryBody)
1078 cgm.errorNYI(dtor->getSourceRange(), "function-try-block destructor");
1079}
1080
1081/// Given a value of type T* that may not be to a complete object, construct
1082/// an l-vlaue withi the natural pointee alignment of T.
1084 QualType ty) {
1085 // FIXME(cir): is it safe to assume Op->getResult(0) is valid? Perhaps
1086 // assert on the result type first.
1087 LValueBaseInfo baseInfo;
1089 CharUnits align = cgm.getNaturalTypeAlignment(ty, &baseInfo);
1090 return makeAddrLValue(Address(val, align), ty, baseInfo);
1091}
1092
1094 QualType ty) {
1095 LValueBaseInfo baseInfo;
1096 CharUnits alignment = cgm.getNaturalTypeAlignment(ty, &baseInfo);
1097 Address addr(val, convertTypeForMem(ty), alignment);
1099 return makeAddrLValue(addr, ty, baseInfo);
1100}
1101
1103 FunctionArgList &args) {
1104 const auto *fd = cast<FunctionDecl>(gd.getDecl());
1105 QualType retTy = fd->getReturnType();
1106
1107 // Only implicit-object member functions need the CXXABI-supplied `this`
1108 // parameter prepended to the arg list. Explicit-object members carry the
1109 // object as a regular parameter that fd->parameters() already enumerates.
1110 const auto *md = dyn_cast<CXXMethodDecl>(fd);
1111 if (md && md->isImplicitObjectMemberFunction()) {
1112 if (cgm.getCXXABI().hasThisReturn(gd))
1113 retTy = md->getThisType();
1114 else if (cgm.getCXXABI().hasMostDerivedReturn(gd))
1115 cgm.errorNYI(fd->getSourceRange(), "most derived return");
1116 cgm.getCXXABI().buildThisParam(*this, args);
1117 }
1118
1119 bool passedParams = true;
1120 if (const auto *cd = dyn_cast<CXXConstructorDecl>(fd))
1121 if (auto inherited = cd->getInheritedConstructor())
1122 passedParams =
1123 getTypes().inheritingCtorHasParams(inherited, gd.getCtorType());
1124
1125 if (passedParams) {
1126 for (auto *param : fd->parameters()) {
1127 args.push_back(param);
1128 if (!param->hasAttr<PassObjectSizeAttr>())
1129 continue;
1130
1131 auto *implicit = ImplicitParamDecl::Create(
1132 getContext(), param->getDeclContext(), param->getLocation(),
1133 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
1134 sizeArguments[param] = implicit;
1135 args.push_back(implicit);
1136 }
1137 }
1138
1139 if (md && (isa<CXXConstructorDecl>(md) || isa<CXXDestructorDecl>(md)))
1140 cgm.getCXXABI().addImplicitStructorParams(*this, retTy, args);
1141
1142 return retTy;
1143}
1144
1146 // Initializing an aggregate temporary in C++11: T{...}.
1147 if (!e->isGLValue())
1148 return emitAggExprToLValue(e);
1149
1150 // An lvalue initializer list must be initializing a reference.
1151 assert(e->isTransparent() && "non-transparent glvalue init list");
1152 return emitLValue(e->getInit(0));
1153}
1154
1155static std::variant<LValue, RValue>
1157 bool forLValue, AggValueSlot slot) {
1159 SmallVector<OVMD> opaques;
1160 llvm::scope_exit opaque_cleanup{
1161 [&]() { llvm::for_each(opaques, [&](OVMD &o) { o.unbind(cgf); }); }};
1162
1163 // Find the result expression, if any.
1164 const Expr *resultExpr = e->getResultExpr();
1165 std::variant<LValue, RValue> result;
1166
1167 for (const Expr *semantic : e->semantics()) {
1168 // If this semantic expression is an opaque value, bind it
1169 // to the result of its source expression.
1170 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
1171
1172 // Skip unique OVEs.
1173 if (ov->isUnique()) {
1174 assert(ov != resultExpr &&
1175 "A unique OVE cannot be used as the result expression");
1176 continue;
1177 }
1178
1179 // If this is the result expression, we may need to evaluate
1180 // directly into the slot.
1181 OVMD opaqueData;
1182 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
1184 cgf.cgm.errorNYI(e->getSourceRange(),
1185 "emitPseudoObjectExpr for RValue & aggregate kind");
1186 } else {
1187 opaqueData = OVMD::bind(cgf, ov, ov->getSourceExpr());
1188
1189 // If this is the result, also evaluate the result now.
1190 if (ov == resultExpr) {
1191 // FIXME: This doesn't really affect anything, but I cannot find a
1192 // test for this, so leave an ErrorNYI here until we can find one.
1193 cgf.cgm.errorNYI(e->getSourceRange(),
1194 "emitPseudoObjectExpr as result");
1195 if (forLValue)
1196 result = cgf.emitLValue(ov);
1197 else
1198 cgf.cgm.errorNYI(e->getSourceRange(),
1199 "emitPseudoObjectExpr as an RValue");
1200 }
1201 }
1202 opaques.push_back(opaqueData);
1203 } else if (semantic == resultExpr) {
1204 // Otherwise, if the expression is the result, evaluate it
1205 // and remember the result.
1206 if (forLValue)
1207 result = cgf.emitLValue(semantic);
1208 else
1209 result = cgf.emitAnyExpr(semantic, slot);
1210 } else {
1211 // FIXME: best I can tell, this is only reachable as an r-value, so this
1212 // isn't properly tested.
1213 cgf.cgm.errorNYI(e->getSourceRange(),
1214 "emitPseudoObjectExpr as an ignored value");
1215 // Otherwise, evaluate the expression in an ignored context.
1216 cgf.emitIgnoredExpr(semantic);
1217 }
1218 }
1219
1220 return result;
1221}
1222
1224 AggValueSlot slot) {
1225 return std::get<RValue>(
1226 emitPseudoObjectExpr(*this, e, /*forLValue=*/false, slot));
1227}
1228
1230 return std::get<LValue>(emitPseudoObjectExpr(*this, e, /*forLValue=*/true,
1232}
1233
1234/// Emit code to compute a designator that specifies the location
1235/// of the expression.
1236/// FIXME: document this function better.
1239 switch (e->getStmtClass()) {
1240 default:
1241 cgm.errorNYI(e->getSourceRange(),
1242 std::string("emitLValue: unsupported l-value class: ") +
1243 e->getStmtClassName());
1244 return LValue();
1245
1246 case Expr::ObjCPropertyRefExprClass:
1247 llvm_unreachable("cannot emit a property reference directly");
1248
1249 case Expr::ObjCSelectorExprClass:
1251 "emitLValue: ObjCSelectorExpr");
1252 return LValue();
1253 case Expr::ObjCIsaExprClass:
1254 getCIRGenModule().errorNYI(e->getSourceRange(), "emitLValue: ObjCIsaExpr");
1255 return LValue();
1256 case Expr::BinaryOperatorClass:
1258 case Expr::CompoundAssignOperatorClass: {
1259 QualType ty = e->getType();
1260 if (const AtomicType *at = ty->getAs<AtomicType>())
1261 ty = at->getValueType();
1262 if (!ty->isAnyComplexType())
1264
1266 }
1267 case Expr::CallExprClass:
1268 case Expr::CXXMemberCallExprClass:
1269 case Expr::CXXOperatorCallExprClass:
1270 case Expr::UserDefinedLiteralClass:
1272 case Expr::CXXRewrittenBinaryOperatorClass:
1274 return emitLValue(cast<CXXRewrittenBinaryOperator>(e)->getSemanticForm());
1275 case Expr::VAArgExprClass:
1276 getCIRGenModule().errorNYI(e->getSourceRange(), "emitLValue: VAArgExpr");
1277 return LValue();
1278 case Expr::DeclRefExprClass:
1280 case Expr::ConstantExprClass: {
1281 const ConstantExpr *ce = cast<ConstantExpr>(e);
1282 if (mlir::Attribute result =
1284 mlir::Value val = builder.getConstant(
1285 getLoc(e->getSourceRange()), mlir::cast<mlir::TypedAttr>(result));
1286 return makeNaturalAlignPointeeAddrLValue(val, ce->getType());
1287 }
1288 return emitLValue(ce->getSubExpr());
1289 }
1290 case Expr::ParenExprClass:
1291 return emitLValue(cast<ParenExpr>(e)->getSubExpr());
1292 case Expr::GenericSelectionExprClass:
1293 return emitLValue(cast<GenericSelectionExpr>(e)->getResultExpr());
1294 case Expr::PredefinedExprClass:
1296 case Expr::StringLiteralClass:
1298 case Expr::ObjCEncodeExprClass:
1300 "emitLValue: ObjCEncodeExpr");
1301 return LValue();
1302 case Expr::PseudoObjectExprClass:
1304 case Expr::InitListExprClass:
1306 case Expr::CXXTemporaryObjectExprClass:
1307 case Expr::CXXConstructExprClass:
1309 case Expr::CXXBindTemporaryExprClass:
1311 case Expr::CXXUuidofExprClass:
1313 "emitLValue: CXXUuidofExpr");
1314 return LValue();
1315 case Expr::LambdaExprClass:
1316 getCIRGenModule().errorNYI(e->getSourceRange(), "emitLValue: LambdaExpr");
1317 return LValue();
1318 case Expr::ExprWithCleanupsClass: {
1319 const auto *cleanups = cast<ExprWithCleanups>(e);
1320 FullExprCleanupScope scope(*this, cleanups->getSubExpr());
1321 LValue lv = emitLValue(cleanups->getSubExpr());
1322 if (lv.isSimple()) {
1323 // Defend against branches out of gnu statement expressions surrounded by
1324 // cleanups.
1325 Address addr = lv.getAddress();
1326 mlir::Value v = addr.getPointer();
1327 scope.exit({&v});
1328 return LValue::makeAddr(addr.withPointer(v), lv.getType(),
1329 lv.getBaseInfo());
1330 }
1331 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1332 // bitfield lvalue or some other non-simple lvalue?
1333 return lv;
1334 }
1335 case Expr::CXXDefaultArgExprClass: {
1336 auto *dae = cast<CXXDefaultArgExpr>(e);
1337 CXXDefaultArgExprScope scope(*this, dae);
1338 return emitLValue(dae->getExpr());
1339 }
1340 case Expr::CXXDefaultInitExprClass: {
1341 auto *die = cast<CXXDefaultInitExpr>(e);
1342 CXXDefaultInitExprScope scope(*this, die);
1343 return emitLValue(die->getExpr());
1344 }
1345 case Expr::CXXTypeidExprClass:
1347 case Expr::ObjCMessageExprClass:
1349 "emitLValue: ObjCMessageExpr");
1350 return LValue();
1351 case Expr::ObjCIvarRefExprClass:
1353 "emitLValue: ObjCIvarRefExpr");
1354 return LValue();
1355 case Expr::StmtExprClass:
1356 getCIRGenModule().errorNYI(e->getSourceRange(), "emitLValue: StmtExpr");
1357 return LValue();
1358 case Expr::UnaryOperatorClass:
1360 case Expr::ArraySubscriptExprClass:
1362 case Expr::MatrixSingleSubscriptExprClass:
1364 "emitLValue: MatrixSingleSubscriptExpr");
1365 return LValue();
1366 case Expr::MatrixSubscriptExprClass:
1368 case Expr::ArraySectionExprClass:
1370 "emitLValue: ArraySectionExpr");
1371 return LValue();
1372 case Expr::ExtVectorElementExprClass:
1374 case Expr::MatrixElementExprClass:
1376 case Expr::CXXThisExprClass:
1378 case Expr::MemberExprClass:
1380 case Expr::CompoundLiteralExprClass:
1382 case Expr::ConditionalOperatorClass:
1384 case Expr::BinaryConditionalOperatorClass:
1386 case Expr::ChooseExprClass:
1387 return emitLValue(cast<ChooseExpr>(e)->getChosenSubExpr());
1388 case Expr::OpaqueValueExprClass:
1390 case Expr::SubstNonTypeTemplateParmExprClass:
1391 return emitLValue(cast<SubstNonTypeTemplateParmExpr>(e)->getReplacement());
1392 case Expr::ImplicitCastExprClass:
1393 case Expr::CStyleCastExprClass:
1394 case Expr::CXXFunctionalCastExprClass:
1395 case Expr::CXXStaticCastExprClass:
1396 case Expr::CXXDynamicCastExprClass:
1397 case Expr::CXXReinterpretCastExprClass:
1398 case Expr::CXXConstCastExprClass:
1399 return emitCastLValue(cast<CastExpr>(e));
1400 case Expr::CXXAddrspaceCastExprClass:
1401 case Expr::ObjCBridgedCastExprClass:
1402 // TODO(cir): These can just be moved into the cast handling above, but
1403 // they need test cases.
1405 "emitLValue: addrspace or ObjC bridged cast");
1406 return LValue();
1407 case Expr::MaterializeTemporaryExprClass:
1409 case Expr::CoawaitExprClass:
1411 case Expr::CoyieldExprClass:
1413 case Expr::PackIndexingExprClass:
1414 return emitLValue(cast<PackIndexingExpr>(e)->getSelectedExpr());
1415 case Expr::HLSLOutArgExprClass:
1416 llvm_unreachable("cannot emit a HLSL out argument directly");
1417 }
1418}
1419
1420static std::string getVersionedTmpName(llvm::StringRef name, unsigned cnt) {
1421 SmallString<256> buffer;
1422 llvm::raw_svector_ostream out(buffer);
1423 out << name << cnt;
1424 return std::string(out.str());
1425}
1426
1428 return getVersionedTmpName("ref.tmp", counterRefTmp++);
1429}
1430
1432 return getVersionedTmpName("agg.tmp", counterAggTmp++);
1433}
1434
1435void CIRGenFunction::emitNullInitialization(mlir::Location loc, Address destPtr,
1436 QualType ty) {
1437 // Ignore empty classes in C++.
1438 if (getLangOpts().CPlusPlus)
1439 if (const auto *rd = ty->getAsCXXRecordDecl(); rd && rd->isEmpty())
1440 return;
1441
1442 // Cast the dest ptr to the appropriate i8 pointer type.
1443 if (!builder.isInt8Ty(destPtr.getElementType()))
1444 destPtr = destPtr.withElementType(builder, uInt8Ty);
1445
1446 // Get size and alignment info for this aggregate.
1447 mlir::IntegerAttr sizeVal;
1448 const CharUnits size = getContext().getTypeSizeInChars(ty);
1449 if (size.isZero()) {
1450 // But note that getTypeInfo returns 0 for a VLA.
1451 if (isa_and_nonnull<VariableArrayType>(getContext().getAsArrayType(ty))) {
1452 cgm.errorNYI(loc,
1453 "emitNullInitialization for zero size VariableArrayType");
1454 } else {
1455 return;
1456 }
1457 } else {
1458 sizeVal = cgm.getSize(size);
1459 }
1460
1461 // If the type contains a pointer to data member we can't memset it to zero.
1462 // Instead, create a null constant and copy it to the destination.
1463 // TODO: there are other patterns besides zero that we can usefully memset,
1464 // like -1, which happens to be the pattern used by member-pointers.
1465 if (!cgm.getTypes().isZeroInitializable(ty)) {
1466 // Only the pointer-to-data-member case is tested here; emitNullConstant
1467 // owns the NYIs for shapes it cannot build (virtual bases, non-zero-init
1468 // arrays).
1469 assert((ty->isMemberDataPointerType() || ty->isRecordType()) &&
1470 "emitNullInitialization: only pointer-to-data-member (directly or "
1471 "within a record) null initialization is implemented");
1472 mlir::Value nullVal = cgm.emitNullConstant(ty, loc);
1473 builder.createStore(loc, nullVal, destPtr);
1474 return;
1475 }
1476
1477 // Otherwise, just memset the whole thing to zero. This is legal
1478 // because in LLVM, all default initializers (other than the ones we just
1479 // handled above, and the case handled below) are guaranteed to have a bit
1480 // pattern of all zeros.
1481 mlir::Value zero = builder.getNullValue(builder.getUInt8Ty(), loc);
1482 mlir::Value sizeValue =
1483 builder.getConstAPInt(loc, cgm.uInt64Ty, sizeVal.getValue());
1484 destPtr = destPtr.withElementType(builder, cgm.voidTy);
1485 builder.createMemSet(loc, destPtr, zero, sizeValue);
1486}
1487
1489 const clang::Expr *e)
1490 : cgf(cgf) {
1491 ConstructorHelper(e->getFPFeaturesInEffect(cgf.getLangOpts()));
1492}
1493
1495 FPOptions fpFeatures)
1496 : cgf(cgf) {
1497 ConstructorHelper(fpFeatures);
1498}
1499
1500void CIRGenFunction::CIRGenFPOptionsRAII::ConstructorHelper(
1501 FPOptions fpFeatures) {
1502 oldFPFeatures = cgf.curFPFeatures;
1503 cgf.curFPFeatures = fpFeatures;
1504
1505 oldExcept = cgf.builder.getDefaultConstrainedExcept();
1506 oldRounding = cgf.builder.getDefaultConstrainedRounding();
1507
1508 if (oldFPFeatures == fpFeatures)
1509 return;
1510
1511 oldFastMathFlags = cgf.builder.getFastMathFlags();
1512
1513 llvm::RoundingMode newRoundingMode = fpFeatures.getRoundingMode();
1514 LangOptions::FPExceptionModeKind newExceptionBehavior =
1515 fpFeatures.getExceptionMode();
1516
1517 cgf.builder.setDefaultConstrainedRounding(newRoundingMode);
1518 cgf.builder.setDefaultConstrainedExcept(newExceptionBehavior);
1519
1520 cgf.setFastMathFlags(fpFeatures);
1521
1522 assert((cgf.curFuncDecl == nullptr || cgf.builder.getIsFPConstrained() ||
1523 isa<CXXConstructorDecl>(cgf.curFuncDecl) ||
1524 isa<CXXDestructorDecl>(cgf.curFuncDecl) ||
1525 (newExceptionBehavior == LangOptions::FPE_Ignore &&
1526 newRoundingMode == llvm::RoundingMode::NearestTiesToEven)) &&
1527 "FPConstrained should be enabled on entire function");
1528
1529 // TODO(cir): mark CIR function with fast math attributes.
1531}
1532
1534 cgf.curFPFeatures = oldFPFeatures;
1535 cgf.builder.setDefaultConstrainedExcept(oldExcept);
1536 cgf.builder.setDefaultConstrainedRounding(oldRounding);
1537 if (oldFastMathFlags)
1538 cgf.builder.setFastMathFlags(*oldFastMathFlags);
1539}
1540
1542 cir::FastMathFlags flags = cir::FastMathFlags::none;
1543 if (curFPFeatures.getAllowFPReassociate())
1544 flags |= cir::FastMathFlags::reassoc;
1545 if (curFPFeatures.getNoHonorNaNs())
1546 flags |= cir::FastMathFlags::nnan;
1547 if (curFPFeatures.getNoHonorInfs())
1548 flags |= cir::FastMathFlags::ninf;
1549 if (curFPFeatures.getNoSignedZero())
1550 flags |= cir::FastMathFlags::nsz;
1551 if (curFPFeatures.getAllowReciprocal())
1552 flags |= cir::FastMathFlags::arcp;
1553 if (curFPFeatures.getAllowApproxFunc())
1554 flags |= cir::FastMathFlags::afn;
1555 if (curFPFeatures.allowFPContractAcrossStatement())
1556 flags |= cir::FastMathFlags::contract;
1557
1558 return flags;
1559}
1560
1561cir::FastMathFlagsAttr
1562CIRGenFunction::getFastMathFlagsAttr(cir::FastMathFlags fastMathFlags) {
1563 if (fastMathFlags == cir::FastMathFlags::none)
1564 return {};
1565 return cir::FastMathFlagsAttr::get(&getMLIRContext(), fastMathFlags);
1566}
1567
1568// TODO(cir): should be shared with LLVM codegen.
1570 const Expr *e = ce->getSubExpr();
1571
1572 if (ce->getCastKind() == CK_UncheckedDerivedToBase)
1573 return false;
1574
1575 if (isa<CXXThisExpr>(e->IgnoreParens())) {
1576 // We always assume that 'this' is never null.
1577 return false;
1578 }
1579
1580 if (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(ce)) {
1581 // And that glvalue casts are never null.
1582 if (ice->isGLValue())
1583 return false;
1584 }
1585
1586 return true;
1587}
1588
1589/// Computes the length of an array in elements, as well as the base
1590/// element type and a properly-typed first element pointer.
1591mlir::Value
1593 QualType &baseType, Address &addr) {
1594 const clang::ArrayType *arrayType = origArrayType;
1595
1596 // If it's a VLA, we have to load the stored size. Note that
1597 // this is the size of the VLA in bytes, not its size in elements.
1598 mlir::Value numVLAElements = nullptr;
1601
1602 // Walk into all VLAs. This doesn't require changes to addr,
1603 // which has type T* where T is the first non-VLA element type.
1604 do {
1605 QualType elementType = arrayType->getElementType();
1606 arrayType = getContext().getAsArrayType(elementType);
1607
1608 // If we only have VLA components, 'addr' requires no adjustment.
1609 if (!arrayType) {
1610 baseType = elementType;
1611 return numVLAElements;
1612 }
1614
1615 // We get out here only if we find a constant array type
1616 // inside the VLA.
1617 }
1618
1619 // Classic codegen emits an all-zero inbounds GEP to convert addr from
1620 // [M x [N x T]]* to T*. CIR doesn't need this because callers handle
1621 // the array-to-element pointer conversion themselves (via array_to_ptrdecay
1622 // casts, ptr_bitcast, or manual array type peeling).
1623
1624 uint64_t countFromCLAs = 1;
1625 QualType eltType;
1626
1627 auto cirArrayType = mlir::dyn_cast<cir::ArrayType>(addr.getElementType());
1628
1629 while (cirArrayType) {
1631 countFromCLAs *= cirArrayType.getSize();
1632 eltType = arrayType->getElementType();
1633
1634 cirArrayType =
1635 mlir::dyn_cast<cir::ArrayType>(cirArrayType.getElementType());
1636
1637 arrayType = getContext().getAsArrayType(arrayType->getElementType());
1638 assert((!cirArrayType || arrayType) &&
1639 "CIR and Clang types are out-of-sync");
1640 }
1641
1642 if (arrayType) {
1643 // From this point onwards, the Clang array type has been emitted
1644 // as some other type (probably a packed struct). Compute the array
1645 // size, and just emit the 'begin' expression as a bitcast.
1646 cgm.errorNYI(*currSrcLoc, "length for non-array underlying types");
1647 }
1648
1649 baseType = eltType;
1650
1651 mlir::Value numElements =
1652 builder.getConstInt(getLoc(*currSrcLoc), sizeTy, countFromCLAs);
1653
1654 // If we had any VLA dimensions, factor them in.
1655 if (numVLAElements)
1656 numElements =
1657 builder.createMul(numVLAElements.getLoc(), numVLAElements, numElements,
1658 cir::OverflowFlags::NoUnsignedWrap);
1659
1660 return numElements;
1661}
1662
1664 mlir::Value ptrValue, QualType ty, SourceLocation loc,
1665 SourceLocation assumptionLoc, int64_t alignment, mlir::Value offsetValue) {
1667 mlir::Location assumeLoc = getLoc(assumptionLoc);
1668 mlir::Value alignValue = builder.getUInt64(alignment, assumeLoc);
1669 mlir::Value cond = builder.getBool(true, assumeLoc);
1670 llvm::SmallVector<mlir::Value> bundleArgs{ptrValue, alignValue};
1671 if (offsetValue)
1672 bundleArgs.push_back(offsetValue);
1673 cir::AssumeOp::create(builder, assumeLoc, cond, cir::AssumeBundleKind::Align,
1674 bundleArgs);
1675 return ptrValue;
1676}
1677
1679 mlir::Value ptrValue, const Expr *expr, SourceLocation assumptionLoc,
1680 int64_t alignment, mlir::Value offsetValue) {
1681 QualType ty = expr->getType();
1682 SourceLocation loc = expr->getExprLoc();
1683 return emitAlignmentAssumption(ptrValue, ty, loc, assumptionLoc, alignment,
1684 offsetValue);
1685}
1686
1688 const VariableArrayType *vla =
1689 cgm.getASTContext().getAsVariableArrayType(type);
1690 assert(vla && "type was not a variable array type!");
1691 return getVLASize(vla);
1692}
1693
1696 // The number of elements so far; always size_t.
1697 mlir::Value numElements;
1698
1699 QualType elementType;
1700 do {
1701 elementType = type->getElementType();
1702 mlir::Value vlaSize = vlaSizeMap[type->getSizeExpr()];
1703 assert(vlaSize && "no size for VLA!");
1704 assert(vlaSize.getType() == sizeTy);
1705
1706 if (!numElements) {
1707 numElements = vlaSize;
1708 } else {
1709 // It's undefined behavior if this wraps around, so mark it that way.
1710 // FIXME: Teach -fsanitize=undefined to trap this.
1711
1712 numElements =
1713 builder.createMul(numElements.getLoc(), numElements, vlaSize,
1714 cir::OverflowFlags::NoUnsignedWrap);
1715 }
1716 } while ((type = getContext().getAsVariableArrayType(elementType)));
1717
1718 assert(numElements && "Undefined elements number");
1719 return {numElements, elementType};
1720}
1721
1724 mlir::Value vlaSize = vlaSizeMap[vla->getSizeExpr()];
1725 assert(vlaSize && "no size for VLA!");
1726 assert(vlaSize.getType() == sizeTy);
1727 return {vlaSize, vla->getElementType()};
1728}
1729
1730// TODO(cir): Most of this function can be shared between CIRGen
1731// and traditional LLVM codegen
1733 assert(type->isVariablyModifiedType() &&
1734 "Must pass variably modified type to EmitVLASizes!");
1735
1736 // We're going to walk down into the type and look for VLA
1737 // expressions.
1738 do {
1739 assert(type->isVariablyModifiedType());
1740
1741 const Type *ty = type.getTypePtr();
1742 switch (ty->getTypeClass()) {
1743 case Type::CountAttributed:
1744 case Type::PackIndexing:
1745 case Type::ArrayParameter:
1746 case Type::HLSLAttributedResource:
1747 case Type::HLSLInlineSpirv:
1748 case Type::PredefinedSugar:
1749 case Type::LateParsedAttr:
1750 cgm.errorNYI("CIRGenFunction::emitVariablyModifiedType");
1751 break;
1752
1753#define TYPE(Class, Base)
1754#define ABSTRACT_TYPE(Class, Base)
1755#define NON_CANONICAL_TYPE(Class, Base)
1756#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1757#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1758#include "clang/AST/TypeNodes.inc"
1759 llvm_unreachable(
1760 "dependent type must be resolved before the CIR codegen");
1761
1762 // These types are never variably-modified.
1763 case Type::Builtin:
1764 case Type::Complex:
1765 case Type::Vector:
1766 case Type::ExtVector:
1767 case Type::ConstantMatrix:
1768 case Type::Record:
1769 case Type::Enum:
1770 case Type::Using:
1771 case Type::TemplateSpecialization:
1772 case Type::ObjCTypeParam:
1773 case Type::ObjCObject:
1774 case Type::ObjCInterface:
1775 case Type::ObjCObjectPointer:
1776 case Type::BitInt:
1777 case Type::OverflowBehavior:
1778 llvm_unreachable("type class is never variably-modified!");
1779
1780 case Type::Adjusted:
1781 type = cast<clang::AdjustedType>(ty)->getAdjustedType();
1782 break;
1783
1784 case Type::Decayed:
1785 type = cast<clang::DecayedType>(ty)->getPointeeType();
1786 break;
1787
1788 case Type::Pointer:
1789 type = cast<clang::PointerType>(ty)->getPointeeType();
1790 break;
1791
1792 case Type::BlockPointer:
1793 type = cast<clang::BlockPointerType>(ty)->getPointeeType();
1794 break;
1795
1796 case Type::LValueReference:
1797 case Type::RValueReference:
1798 type = cast<clang::ReferenceType>(ty)->getPointeeType();
1799 break;
1800
1801 case Type::MemberPointer:
1802 type = cast<clang::MemberPointerType>(ty)->getPointeeType();
1803 break;
1804
1805 case Type::ConstantArray:
1806 case Type::IncompleteArray:
1807 // Losing element qualification here is fine.
1808 type = cast<clang::ArrayType>(ty)->getElementType();
1809 break;
1810
1811 case Type::VariableArray: {
1812 // Losing element qualification here is fine.
1814
1815 // Unknown size indication requires no size computation.
1816 // Otherwise, evaluate and record it.
1817 if (const Expr *sizeExpr = vat->getSizeExpr()) {
1818 // It's possible that we might have emitted this already,
1819 // e.g. with a typedef and a pointer to it.
1820 mlir::Value &entry = vlaSizeMap[sizeExpr];
1821 if (!entry) {
1822 mlir::Value size = emitScalarExpr(sizeExpr);
1824
1825 // Always zexting here would be wrong if it weren't
1826 // undefined behavior to have a negative bound.
1827 // FIXME: What about when size's type is larger than size_t?
1828 entry = builder.createBoolIntToIntCast(size, sizeTy);
1829 }
1830 }
1831 type = vat->getElementType();
1832 break;
1833 }
1834
1835 case Type::FunctionProto:
1836 case Type::FunctionNoProto:
1837 type = cast<clang::FunctionType>(ty)->getReturnType();
1838 break;
1839
1840 case Type::Paren:
1841 case Type::TypeOf:
1842 case Type::UnaryTransform:
1843 case Type::Attributed:
1844 case Type::BTFTagAttributed:
1845 case Type::SubstTemplateTypeParm:
1846 case Type::MacroQualified:
1847 // Keep walking after single level desugaring.
1848 type = type.getSingleStepDesugaredType(getContext());
1849 break;
1850
1851 case Type::Typedef:
1852 case Type::Decltype:
1853 case Type::Auto:
1854 case Type::DeducedTemplateSpecialization:
1855 // Stop walking: nothing to do.
1856 return;
1857
1858 case Type::TypeOfExpr:
1859 // Stop walking: emit typeof expression.
1860 emitIgnoredExpr(cast<clang::TypeOfExprType>(ty)->getUnderlyingExpr());
1861 return;
1862
1863 case Type::Atomic:
1864 type = cast<clang::AtomicType>(ty)->getValueType();
1865 break;
1866
1867 case Type::Pipe:
1868 type = cast<clang::PipeType>(ty)->getElementType();
1869 break;
1870 }
1871 } while (type->isVariablyModifiedType());
1872}
1873
1875 if (getContext().getBuiltinVaListType()->isArrayType())
1876 return emitPointerWithAlignment(e);
1877 return emitLValue(e).getAddress();
1878}
1879
1880} // namespace clang::CIRGen
Defines the clang::Expr interface and subclasses for C++ expressions.
APSInt & getInt()
Definition APValue.h:577
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:916
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
Address withPointer(mlir::Value newPtr) const
Return address with different pointer, but same element type and alignment.
Definition Address.h:83
mlir::Value getPointer() const
Definition Address.h:98
mlir::Type getElementType() const
Definition Address.h:125
static Address invalid()
Definition Address.h:76
Address withElementType(CIRGenBuilderTy &builder, mlir::Type ElemTy) const
Return address with different element type, a bitcast pointer, and the same alignment.
mlir::Operation * getDefiningOp() const
Get the operation which defines this address.
Definition Address.h:141
An aggregate value slot.
static AggValueSlot ignored()
Returns an aggregate value slot indicating that the aggregate value is being ignored.
mlir::Value createFloatingCast(mlir::Value v, mlir::Type destType)
CIRGenFPOptionsRAII(CIRGenFunction &cgf, FPOptions FPFeatures)
void exit(ArrayRef< mlir::Value * > valuesToReload={})
A non-RAII class containing all the information about a bound opaque value.
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
void forceCleanup(ArrayRef< mlir::Value * > valuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
static bool isConstructorDelegationValid(const clang::CXXConstructorDecl *ctor)
Checks whether the given constructor is a valid subject for the complete-to-base constructor delegati...
void emitFunctionProlog(const FunctionArgList &args, mlir::Block *entryBB, const FunctionDecl *fd, SourceLocation bodyBeginLoc)
Emit the function prologue: initialize the return value of an implicit-return-zero function and decla...
mlir::Type convertType(clang::QualType t)
LValue emitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *e)
LValue emitOpaqueValueLValue(const OpaqueValueExpr *e)
static cir::TypeEvaluationKind getEvaluationKind(clang::QualType type)
Return the cir::TypeEvaluationKind of QualType type.
clang::GlobalDecl curGD
The GlobalDecl for the current function being compiled or the global variable currently being initial...
EHScopeStack::stable_iterator prologueCleanupDepth
The cleanup depth enclosing all the cleanups associated with the parameters.
cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn, cir::FuncType funcType)
Address emitFieldAnnotations(const clang::FieldDecl *field, Address addr)
Annotate the address of field; accesses must use the result.
CIRGenTypes & getTypes() const
Address emitPointerWithAlignment(const clang::Expr *expr, LValueBaseInfo *baseInfo=nullptr)
Given an expression with a pointer type, emit the value and compute our best estimate of the alignmen...
void emitVariablyModifiedType(QualType ty)
RValue emitLoadOfLValue(LValue lv, SourceLocation loc)
Given an expression that represents a value lvalue, this method emits the address of the lvalue,...
const clang::LangOptions & getLangOpts() const
void emitTrap(mlir::Location loc, bool createNewBlock)
Emit a trap instruction, which is used to abort the program in an abnormal way, usually for debugging...
VlaSizePair getVLASize(const VariableArrayType *type)
Returns an MLIR::Value+QualType pair that corresponds to the size, in non-variably-sized elements,...
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...
void emitDeleteCall(const FunctionDecl *deleteFD, mlir::Value ptr, QualType deleteTy)
LValue emitMemberExpr(const MemberExpr *e)
const TargetInfo & getTarget() const
LValue emitConditionalOperatorLValue(const AbstractConditionalOperator *expr)
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
const clang::Decl * curFuncDecl
LValue emitLValueForLambdaField(const FieldDecl *field)
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,...
LValue emitComplexCompoundAssignmentLValue(const CompoundAssignOperator *e)
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
void initializeVTablePointers(mlir::Location loc, const clang::CXXRecordDecl *rd)
bool constantFoldsToBool(const clang::Expr *cond, bool &resultBool, bool allowLabels=false)
If the specified expression does not fold to a constant, or if it does but contains a label,...
void emitVarAnnotations(const clang::VarDecl *d, mlir::Value addr)
Annotate the storage of d at addr.
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.
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)
LValue emitArraySubscriptExpr(const clang::ArraySubscriptExpr *e)
llvm::ScopedHashTableScope< const clang::Decl *, mlir::Value > SymTableScopeTy
LValue emitCoawaitLValue(const CoawaitExpr *e)
mlir::Operation * curFn
The current function or global initializer that is generated code for.
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.
Address maybeCastStackAddressSpace(Address alloca, mlir::ptr::MemorySpaceAttrInterface destAddrSpace, mlir::Value arraySize=nullptr)
llvm::SmallVector< const ParmVarDecl * > fnArgs
Save Parameter Decl for coroutine.
llvm::SmallVector< PendingCleanupEntry > deferredConditionalCleanupStack
Cleanups for temporaries constructed inside a conditional.
std::optional< mlir::Value > fnRetAlloca
The compiler-generated variable that holds the return value.
void emitImplicitAssignmentOperatorBody(FunctionArgList &args)
cir::FastMathFlagsAttr getFastMathFlagsAttr(cir::FastMathFlags fastMathFlags)
Create a CIR fast-math attribute from the specified flags.
mlir::Type convertTypeForMem(QualType t)
clang::QualType buildFunctionArgList(clang::GlobalDecl gd, FunctionArgList &args)
void emitCtorPrologue(const clang::CXXConstructorDecl *ctor, clang::CXXCtorType ctorType, FunctionArgList &args)
This routine generates necessary code to initialize base classes and non-static data members belongin...
mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty, mlir::Location loc, clang::CharUnits alignment, bool insertIntoFnEntryBlock, mlir::Value arraySize=nullptr)
mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s, cxxTryBodyEmitter &bodyCallback, bool isFnTryBlock=false)
cir::FastMathFlags getCurrentFastMathFlags() const
Convert the active Clang floating-point options to CIR fast-math flags.
LValue emitAggExprToLValue(const Expr *e)
LValue emitCompoundAssignmentLValue(const clang::CompoundAssignOperator *e)
Address returnValue
The temporary alloca to hold the return value.
static bool hasAggregateEvaluationKind(clang::QualType type)
void finishFunction(SourceLocation endLoc)
mlir::LogicalResult emitFunctionBody(const clang::Stmt *body)
LValue emitUnaryOpLValue(const clang::UnaryOperator *e)
LValue emitMatrixSubscriptExpr(const MatrixSubscriptExpr *e)
clang::FieldDecl * lambdaThisCaptureField
const clang::Decl * curCodeDecl
This is the inner-most code context, which includes blocks.
void emitConstructorBody(FunctionArgList &args)
LValue emitCallExprLValue(const clang::CallExpr *e)
LValue emitStringLiteralLValue(const StringLiteral *e, llvm::StringRef name=".str")
LValue emitCoyieldLValue(const CoyieldExpr *e)
llvm::SmallDenseMap< const ParmVarDecl *, const ImplicitParamDecl * > sizeArguments
If a ParmVarDecl had the pass_object_size attribute, this will contain a mapping from said ParmVarDec...
mlir::Value loadThisForDtorDelete(const CXXDestructorDecl *dd)
Return the pointer to pass to the operator delete of the given destructor, converted to the type of i...
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
LValue emitPseudoObjectLValue(const PseudoObjectExpr *E)
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.
bool shouldNullCheckClassCastValue(const CastExpr *ce)
CIRGenBuilderTy & getBuilder()
bool didCallStackSave
Whether a cir.stacksave operation has been added.
LValue emitBinaryOperatorLValue(const BinaryOperator *e)
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.
unsigned counterRefTmp
Hold counters for incrementally naming temporaries.
mlir::MLIRContext & getMLIRContext()
void emitDestructorBody(FunctionArgList &args)
Emits the body of the current destructor.
LValue emitInitListLValue(const InitListExpr *e)
std::optional< SourceRange > currSrcLoc
Use to track source locations across nested visitor traversals.
LValue emitCastLValue(const CastExpr *e)
Casts are never lvalues unless that cast is to a reference type.
LValue emitCXXTypeidLValue(const CXXTypeidExpr *e)
bool containsLabel(const clang::Stmt *s, bool ignoreCaseStmts=false)
Return true if the statement contains a label in it.
RValue emitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
LValue emitDeclRefLValue(const clang::DeclRefExpr *e)
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::Value emitAlignmentAssumption(mlir::Value ptrValue, QualType ty, SourceLocation loc, SourceLocation assumptionLoc, int64_t alignment, mlir::Value offsetValue=nullptr)
void setFastMathFlags(FPOptions fpFeatures)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
LValue emitMatrixElementExpr(const MatrixElementExpr *e)
LValue emitPredefinedLValue(const PredefinedExpr *e)
RValue emitAnyExpr(const clang::Expr *e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Emit code to compute the specified expression which can have any type.
void emitCXXDestructorCall(const CXXDestructorDecl *dd, CXXDtorType type, bool forVirtualBase, bool delegating, Address thisAddr, QualType thisTy)
void emitLambdaStaticInvokeBody(const CXXMethodDecl *md)
void emitEndEHSpec(const clang::Decl *d)
Close the cir.try opened by emitStartEHSpec.
CIRGenFunction(CIRGenModule &cgm, CIRGenBuilderTy &builder, bool suppressNewContext=false)
LValue emitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e)
LValue emitExtVectorElementExpr(const ExtVectorElementExpr *e)
clang::ASTContext & getContext() const
void setAddrOfLocalVar(const clang::VarDecl *vd, Address addr)
Set the address of a local variable.
void emitStartEHSpec(const clang::Decl *d)
Wrap the function body in a cir.try that enforces the exception specification of d: a filter handler ...
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
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 emitCompoundStmtWithoutScope(const clang::CompoundStmt &s, Address *lastValue=nullptr, AggValueSlot slot=AggValueSlot::ignored())
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...
LValue emitCXXConstructLValue(const CXXConstructExpr *e)
LValue emitCompoundLiteralLValue(const CompoundLiteralExpr *e)
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.
bool inheritingCtorHasParams(const InheritedConstructor &inherited, CXXCtorType type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
mlir::Attribute tryEmitConstantExpr(const ConstantExpr *ce)
Type for representing both the decl and type of parameters to a function.
Definition CIRGenCall.h:195
Address getAddress() const
static LValue makeAddr(Address address, clang::QualType t, LValueBaseInfo baseInfo)
clang::QualType getType() const
mlir::Value getPointer() const
LValueBaseInfo getBaseInfo() const
bool isSimple() const
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
const FunctionDecl * getOperatorDelete() const
Definition DeclCXX.cpp:3230
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2320
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1231
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1751
An expression that occurs in a constant context and the result of evaluating the expression.
Definition Expr.h:1127
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
SourceLocation getLocation() const
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:586
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isGLValue() const
Definition Expr.h:289
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:4031
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
QualType getType() const
Definition Expr.h:146
LangOptions::FPExceptionModeKind getExceptionMode() const
bool allowFPContractAcrossStatement() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3341
const Expr * getSubExpr() const
Definition Expr.h:1107
Represents a function declaration or definition.
Definition Decl.h:2082
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3285
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3625
QualType getReturnType() const
Definition Decl.h:3022
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2597
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4646
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
CXXCtorType getCtorType() const
Definition GlobalDecl.h:117
const Decl * getDecl() const
Definition GlobalDecl.h:115
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3922
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5710
Describes an C or C++ initializer list.
Definition Expr.h:5377
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2501
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
FPExceptionModeKind
Possible floating point exception behavior.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
FPExceptionModeKind getDefaultExceptionMode() const
RoundingMode getDefaultRoundingMode() const
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6890
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6938
ArrayRef< Expr * > semantics()
Definition Expr.h:6962
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3094
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
child_iterator child_begin()
Definition Stmt.h:1602
StmtClass getStmtClass() const
Definition Stmt.h:1504
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
child_iterator child_end()
Definition Stmt.h:1603
const char * getStmtClassName() const
Definition Stmt.cpp:86
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isVoidType() const
Definition TypeBase.h:9200
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isMemberDataPointerType() const
Definition TypeBase.h:8907
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isRecordType() const
Definition TypeBase.h:8942
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2171
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Expr * getSizeExpr() const
Definition TypeBase.h:4078
mlir::ptr::MemorySpaceAttrInterface toCIRAddressSpaceAttr(mlir::MLIRContext &ctx, clang::LangAS langAS)
Convert an AST LangAS to the appropriate CIR address space attribute interface.
@ 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 ...
static bool previousOpIsNonYieldingCleanup(mlir::Block *block)
static std::string getVersionedTmpName(llvm::StringRef name, unsigned cnt)
static bool mayDropFunctionReturn(const ASTContext &astContext, QualType returnType)
static mlir::Value emitArgumentDemotion(CIRGenFunction &cgf, const VarDecl *var, mlir::Value value)
An argument came in as a promoted argument; demote it back to its declared type.
static bool functionMightHaveBypass(const Stmt *s)
Does the statement tree rooted at s contain a label, switch, or indirect goto that could bypass a loc...
static std::variant< LValue, RValue > emitPseudoObjectExpr(CIRGenFunction &cgf, const PseudoObjectExpr *e, bool forLValue, AggValueSlot slot)
bool canSkipVTablePointerInitialization(ASTContext &Ctx, const CXXDestructorDecl *Dtor)
Check whether we need to initialize any vtable pointers before calling this destructor.
bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, const LangOptions &LangOpts)
Decide whether we need to emit the lifetime markers.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
CXXCtorType
C++ constructor types.
Definition ABI.h:24
@ Ctor_Base
Base object ctor.
Definition ABI.h:26
@ Ctor_Complete
Complete object ctor.
Definition ABI.h:25
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
CXXDtorType
C++ destructor types.
Definition ABI.h:34
@ Dtor_VectorDeleting
Vector deleting dtor.
Definition ABI.h:40
@ Dtor_Comdat
The COMDAT used for dtors.
Definition ABI.h:38
@ Dtor_Unified
GCC-style unified dtor.
Definition ABI.h:39
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
@ Dtor_Deleting
Deleting dtor.
Definition ABI.h:35
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Other
Other implicit parameter.
Definition Decl.h:1787
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool fastMathFuncAttributes()
static bool constructABIArgDirectExtend()
static bool runCleanupsScope()
static bool emitTypeCheck()
static bool addressIsKnownNonNull()
static bool generateDebugInfo()
static bool incrementProfileCounter()
Represents a scope, including function bodies, compound statements, and the substatements of if/while...
llvm::ArrayRef< mlir::Block * > getRetBlocks()
LexicalScope(CIRGenFunction &cgf, mlir::Location loc, mlir::Block *eb)
mlir::Location getRetLoc(mlir::Block *b)
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669