clang 23.0.0git
CIRGenDecl.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// This contains code to emit Decl nodes as CIR code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CIRGenCleanup.h"
15#include "CIRGenFunction.h"
16#include "mlir/IR/Location.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Attrs.inc"
19#include "clang/AST/Decl.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/Basic/Cuda.h"
27
28using namespace clang;
29using namespace clang::CIRGen;
30
33 mlir::OpBuilder::InsertPoint ip) {
34 QualType ty = d.getType();
35 assert(
38
39 mlir::Location loc = getLoc(d.getSourceRange());
40 bool nrvo =
41 getContext().getLangOpts().ElideConstructors && d.isNRVOVariable();
42
44 emission.isEscapingByRef = d.isEscapingByref();
45 if (emission.isEscapingByRef)
46 cgm.errorNYI(d.getSourceRange(),
47 "emitAutoVarAlloca: decl escaping by reference");
48
49 CharUnits alignment = getContext().getDeclAlign(&d);
50
51 // If the type is variably-modified, emit all the VLA sizes for it.
52 if (ty->isVariablyModifiedType())
54
56
57 Address address = Address::invalid();
58 if (ty->isConstantSizeType()) {
59 // If this value is an array, struct, or vector with a statically
60 // determinable constant initializer, there are optimizations we can do.
61 //
62 // TODO: We should constant-evaluate the initializer of any variable,
63 // as long as it is initialized by a constant expression. Currently,
64 // isConstantInitializer produces wrong answers for structs with
65 // reference or bitfield members, and a few other cases, and checking
66 // for POD-ness protects us from some of these.
67 if (d.getInit() &&
68 (ty->isArrayType() || ty->isRecordType() || ty->isVectorType()) &&
69 (d.isConstexpr() ||
70 ((ty.isPODType(getContext()) ||
71 getContext().getBaseElementType(ty)->isObjCObjectPointerType()) &&
73
74 // If the variable's a const type, and it's neither an NRVO
75 // candidate nor a __block variable and has no mutable members,
76 // emit it as a global instead.
77 // Exception is if a variable is located in non-constant address space
78 // in OpenCL.
79 // TODO(cir): perhaps we don't need this at all at CIR since this can
80 // be done as part of lowering down to LLVM.
81 bool needsDtor =
83 if ((!getContext().getLangOpts().OpenCL ||
85 (cgm.getCodeGenOpts().MergeAllConstants && !nrvo &&
86 !d.isEscapingByref() &&
87 ty.isConstantStorage(getContext(), true, !needsDtor))) {
88 cgm.errorNYI(d.getSourceRange(), "emitAutoVarAlloca: type constant");
89 }
90 // Otherwise, tell the initialization code that we're in this case.
91 emission.isConstantAggregate = true;
92 }
93
94 // A normal fixed sized variable becomes an alloca in the entry block,
95 // unless:
96 // - it's an NRVO variable.
97 // - we are compiling OpenMP and it's an OpenMP local variable.
98 if (nrvo) {
99 // The named return value optimization: allocate this variable in the
100 // return slot, so that we can elide the copy when returning this
101 // variable (C++0x [class.copy]p34).
102 address = returnValue;
103
104 if (const RecordDecl *rd = ty->getAsRecordDecl()) {
105 if (const auto *cxxrd = dyn_cast<CXXRecordDecl>(rd);
106 (cxxrd && !cxxrd->hasTrivialDestructor()) ||
107 rd->isNonTrivialToPrimitiveDestroy()) {
108 // In LLVM: Create a flag that is used to indicate when the NRVO was
109 // applied to this variable. Set it to zero to indicate that NRVO was
110 // not applied. For now, use the same approach for CIRGen until we can
111 // be sure it's worth doing something more aggressive.
112 cir::ConstantOp falseNVRO = builder.getFalse(loc);
113 Address nrvoFlag = createTempAlloca(falseNVRO.getType(),
114 CharUnits::One(), loc, "nrvo",
115 /*arraySize=*/nullptr);
116 assert(builder.getInsertionBlock());
117 builder.createStore(loc, falseNVRO, nrvoFlag);
118
119 // Record the NRVO flag for this variable.
120 nrvoFlags[&d] = nrvoFlag.getPointer();
121 emission.nrvoFlag = nrvoFlag.getPointer();
122 }
123 }
124 } else {
125 // A normal fixed sized variable becomes an alloca in the entry block,
126 mlir::Type allocaTy = convertTypeForMem(ty);
127 // Create the temp alloca and declare variable using it.
128 address = createTempAlloca(allocaTy, alignment, loc, d.getName(),
129 /*arraySize=*/nullptr, /*alloca=*/nullptr, ip);
130 declare(address.getPointer(), &d, ty, getLoc(d.getSourceRange()),
131 alignment);
132 }
133 } else {
134 // Non-constant size type
136 if (!didCallStackSave) {
137 // Save the stack.
138 cir::PointerType defaultTy = allocaInt8PtrTy;
140 cgm.getDataLayout().getAlignment(defaultTy, false));
141 Address stack = createTempAlloca(defaultTy, align, loc, "saved_stack");
142
143 mlir::Value v = builder.createStackSave(loc, defaultTy);
144 assert(v.getType() == allocaInt8PtrTy);
145 builder.createStore(loc, v, stack);
146
147 didCallStackSave = true;
148
149 // Push a cleanup block and restore the stack there.
150 // FIXME: in general circumstances, this should be an EH cleanup.
152 }
153
154 VlaSizePair vlaSize = getVLASize(ty);
155 mlir::Type memTy = convertTypeForMem(vlaSize.type);
156
157 // Allocate memory for the array.
158 address =
159 createTempAlloca(memTy, alignment, loc, d.getName(), vlaSize.numElts,
160 /*alloca=*/nullptr, builder.saveInsertionPoint());
161
162 // If we have debug info enabled, properly describe the VLA dimensions for
163 // this type by registering the vla size expression for each of the
164 // dimensions.
166 }
167
168 emission.addr = address;
169 setAddrOfLocalVar(&d, address);
170
171 return emission;
172}
173
174/// Determine whether the given initializer is trivial in the sense
175/// that it requires no code to be generated.
177 if (!init)
178 return true;
179
180 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(init))
181 if (CXXConstructorDecl *constructor = construct->getConstructor())
182 if (constructor->isTrivial() && constructor->isDefaultConstructor() &&
183 !construct->requiresZeroInitialization())
184 return true;
185
186 return false;
187}
188
189static void emitStoresForConstant(CIRGenModule &cgm, const VarDecl &d,
190 Address addr, bool isVolatile,
191 CIRGenBuilderTy &builder,
192 mlir::TypedAttr constant) {
193 mlir::Type ty = constant.getType();
194 cir::CIRDataLayout layout{cgm.getModule()};
195 uint64_t constantSize = layout.getTypeAllocSize(ty);
196 if (!constantSize)
197 return;
200
201 if (addr.getElementType() != ty)
202 addr = addr.withElementType(builder, ty);
203
204 // If the address is an alloca, set the init attribute.
205 // The address is usually and alloca, but there is at least one case where
206 // emitAutoVarInit is called from the OpenACC codegen with an address that
207 // is not an alloca.
208 cir::AllocaOp allocaOp = addr.getUnderlyingAllocaOp();
209 if (allocaOp)
210 allocaOp.setInitAttr(mlir::UnitAttr::get(&cgm.getMLIRContext()));
211
212 // There are cases where OpenACC codegen calls emitAutoVarInit with a
213 // temporary decl that doesn't have a source range set.
214 mlir::Location loc = builder.getUnknownLoc();
215 if (d.getSourceRange().isValid())
216 loc = cgm.getLoc(d.getSourceRange());
217
218 // Emit cir.const + cir.store, preserving source-level semantics. For
219 // aggregate types (arrays, records), LoweringPrepare implements the OG
220 // optimization tiers (shouldCreateMemCpyFromGlobal, shouldUseBZeroPlusStores,
221 // shouldUseMemSetToInitialize, shouldSplitConstantStore) by transforming
222 // into cir.global + cir.get_global + cir.copy when appropriate.
223 builder.createStore(loc, builder.getConstant(loc, constant), addr);
224}
225
227 const CIRGenFunction::AutoVarEmission &emission) {
228 assert(emission.variable && "emission was not valid!");
229
230 // If this was emitted as a global constant, we're done.
231 if (emission.wasEmittedAsGlobal())
232 return;
233
234 const VarDecl &d = *emission.variable;
235
236 QualType type = d.getType();
237
238 // If this local has an initializer, emit it now.
239 const Expr *init = d.getInit();
240
241 // Initialize the variable here if it doesn't have a initializer and it is a
242 // C struct that is non-trivial to initialize or an array containing such a
243 // struct.
244 if (!init && type.isNonTrivialToPrimitiveDefaultInitialize() ==
246 cgm.errorNYI(d.getSourceRange(),
247 "emitAutoVarInit: non-trivial to default initialize");
248 return;
249 }
250
251 const Address addr = emission.addr;
252
253 // Check whether this is a byref variable that's potentially
254 // captured and moved by its own initializer. If so, we'll need to
255 // emit the initializer first, then copy into the variable.
257
258 // Note: constexpr already initializes everything correctly.
259 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
260 (d.isConstexpr()
262 : (d.getAttr<UninitializedAttr>()
264 : getContext().getLangOpts().getTrivialAutoVarInit()));
265
266 auto initializeWhatIsTechnicallyUninitialized = [&](Address addr) {
267 if (trivialAutoVarInit ==
269 return;
270
271 cgm.errorNYI(d.getSourceRange(), "emitAutoVarInit: trivial initialization");
272 };
273
274 if (isTrivialInitializer(init)) {
275 initializeWhatIsTechnicallyUninitialized(addr);
276 return;
277 }
278
279 mlir::Attribute constant;
280 if (emission.isConstantAggregate ||
282 // FIXME: Differently from LLVM we try not to emit / lower too much
283 // here for CIR since we are interested in seeing the ctor in some
284 // analysis later on. So CIR's implementation of ConstantEmitter will
285 // frequently return an empty Attribute, to signal we want to codegen
286 // some trivial ctor calls and whatnots.
288 if (constant && !mlir::isa<cir::ZeroAttr>(constant) &&
289 (trivialAutoVarInit !=
291 cgm.errorNYI(d.getSourceRange(), "emitAutoVarInit: constant aggregate");
292 return;
293 }
294 }
295
296 // NOTE(cir): In case we have a constant initializer, we can just emit a
297 // store. But, in CIR, we wish to retain any ctor calls, so if it is a
298 // CXX temporary object creation, we ensure the ctor call is used deferring
299 // its removal/optimization to the CIR lowering.
300 if (!constant || isa<CXXTemporaryObjectExpr>(init)) {
301 initializeWhatIsTechnicallyUninitialized(addr);
303 emitExprAsInit(init, &d, lv);
304
305 if (!emission.wasEmittedAsOffloadClause()) {
306 // In case lv has uses it means we indeed initialized something
307 // out of it while trying to build the expression, mark it as such.
308 Address addr = lv.getAddress();
309 assert(addr.isValid() && "Should have an address");
310 cir::AllocaOp allocaOp = addr.getUnderlyingAllocaOp();
311 assert(allocaOp && "Address should come straight out of the alloca");
312
313 if (!allocaOp.use_empty())
314 allocaOp.setInitAttr(mlir::UnitAttr::get(&getMLIRContext()));
315 }
316
317 return;
318 }
319
320 // FIXME(cir): migrate most of this file to use mlir::TypedAttr directly.
321 auto typedConstant = mlir::dyn_cast<mlir::TypedAttr>(constant);
322 assert(typedConstant && "expected typed attribute");
323 if (!emission.isConstantAggregate) {
324 // For simple scalar/complex initialization, store the value directly.
325 LValue lv = makeAddrLValue(addr, type);
326 assert(init && "expected initializer");
327 mlir::Location initLoc = getLoc(init->getSourceRange());
328 // lv.setNonGC(true);
330 RValue::get(builder.getConstant(initLoc, typedConstant)), lv);
331 }
332
333 emitStoresForConstant(cgm, d, addr, type.isVolatileQualified(), builder,
334 typedConstant);
335}
336
338 const CIRGenFunction::AutoVarEmission &emission) {
339 const VarDecl &d = *emission.variable;
340
341 // Check the type for a cleanup.
343 emitAutoVarTypeCleanup(emission, dtorKind);
344
346
347 // Handle the cleanup attribute.
348 if (d.hasAttr<CleanupAttr>())
349 cgm.errorNYI(d.getSourceRange(), "emitAutoVarCleanups: CleanupAttr");
350}
351
352/// Emit code and set up symbol table for a variable declaration with auto,
353/// register, or no storage class specifier. These turn into simple stack
354/// objects, globals depending on target.
360
362 // If the declaration has external storage, don't emit it now, allow it to be
363 // emitted lazily on its first use.
364 if (d.hasExternalStorage())
365 return;
366
367 if (d.getStorageDuration() != SD_Automatic) {
368 // Static sampler variables translated to function calls.
369 if (d.getType()->isSamplerT()) {
370 // Nothing needs to be done here, but let's flag it as an error until we
371 // have a test. It requires OpenCL support.
372 cgm.errorNYI(d.getSourceRange(), "emitVarDecl: static sampler type");
373 return;
374 }
375
376 cir::GlobalLinkageKind linkage = cgm.getCIRLinkageVarDefinition(&d);
377
378 // FIXME: We need to force the emission/use of a guard variable for
379 // some variables even if we can constant-evaluate them because
380 // we can't guarantee every translation unit will constant-evaluate them.
381
382 return emitStaticVarDecl(d, linkage);
383 }
384
386 cgm.errorNYI(d.getSourceRange(), "emitVarDecl: openCL address space");
387
388 assert(d.hasLocalStorage());
389
390 CIRGenFunction::VarDeclContext varDeclCtx{*this, &d};
391 return emitAutoVarDecl(d);
392}
393
394static std::string getStaticDeclName(CIRGenModule &cgm, const VarDecl &d) {
395 if (cgm.getLangOpts().CPlusPlus)
396 return cgm.getMangledName(&d).str();
397
398 // If this isn't C++, we don't need a mangled name, just a pretty one.
399 assert(!d.isExternallyVisible() && "name shouldn't matter");
400 std::string contextName;
401 const DeclContext *dc = d.getDeclContext();
402 if (auto *cd = dyn_cast<CapturedDecl>(dc))
403 dc = cast<DeclContext>(cd->getNonClosureContext());
404 if (const auto *fd = dyn_cast<FunctionDecl>(dc))
405 contextName = std::string(cgm.getMangledName(fd));
406 else if (isa<BlockDecl>(dc))
407 cgm.errorNYI(d.getSourceRange(),
408 "getStaticDeclName: block decl context for static var");
409 else if (isa<ObjCMethodDecl>(dc))
410 cgm.errorNYI(d.getSourceRange(),
411 "getStaticDeclName: ObjC decl context for static var");
412 else
413 cgm.errorNYI(d.getSourceRange(),
414 "getStaticDeclName: Unknown context for static var decl");
415
416 contextName += "." + d.getNameAsString();
417 return contextName;
418}
419
420// TODO(cir): LLVM uses a Constant base class. Maybe CIR could leverage an
421// interface for all constants?
422cir::GlobalOp
424 cir::GlobalLinkageKind linkage) {
425 // In general, we don't always emit static var decls once before we reference
426 // them. It is possible to reference them before emitting the function that
427 // contains them, and it is possible to emit the containing function multiple
428 // times.
429 if (cir::GlobalOp existingGV = getStaticLocalDeclAddress(&d))
430 return existingGV;
431
432 QualType ty = d.getType();
433 assert(ty->isConstantSizeType() && "VLAs can't be static");
434
435 // Use the label if the variable is renamed with the asm-label extension.
436 if (d.hasAttr<AsmLabelAttr>())
437 errorNYI(d.getSourceRange(), "getOrCreateStaticVarDecl: asm label");
438
439 std::string name = getStaticDeclName(*this, d);
440
441 mlir::Type lty = getTypes().convertTypeForMem(ty);
443
444 // OpenCL variables in local address space and CUDA shared
445 // variables cannot have an initializer.
446 mlir::Attribute init = nullptr;
448 d.hasAttr<CUDASharedAttr>() || d.hasAttr<LoaderUninitializedAttr>())
449 init = cir::UndefAttr::get(lty);
450 else
451 init = builder.getZeroInitAttr(convertType(ty));
452
453 cir::GlobalOp gv = builder.createVersionedGlobal(
454 getModule(), getLoc(d.getLocation()), name, lty, false, linkage);
456 // TODO(cir): infer visibility from linkage in global op builder.
457 gv.setVisibility(getMLIRVisibilityFromCIRLinkage(linkage));
458 gv.setInitialValueAttr(init);
459 gv.setAlignment(getASTContext().getDeclAlign(&d).getAsAlign().value());
460
461 if (supportsCOMDAT() && gv.isWeakForLinker())
462 gv.setComdat(true);
463
464 if (d.getTLSKind())
465 setTLSMode(gv, d);
466
467 setGVProperties(gv, &d);
468
469 // OG checks if the expected address space, denoted by the type, is the
470 // same as the actual address space indicated by attributes. If they aren't
471 // the same, an addrspacecast is emitted when this variable is accessed.
472 // In CIR however, cir.get_global already carries that information in
473 // !cir.ptr type - if this global is in OpenCL local address space, then its
474 // type would be !cir.ptr<..., addrspace(offload_local)>. Therefore we don't
475 // need an explicit address space cast in CIR: they will get emitted when
476 // lowering to LLVM IR.
477
478 // Ensure that the static local gets initialized by making sure the parent
479 // function gets emitted eventually.
480 const Decl *dc = cast<Decl>(d.getDeclContext());
481
482 // We can't name blocks or captured statements directly, so try to emit their
483 // parents.
484 if (isa<BlockDecl>(dc) || isa<CapturedDecl>(dc)) {
485 dc = dc->getNonClosureContext();
486 // FIXME: Ensure that global blocks get emitted.
487 if (!dc)
488 errorNYI(d.getSourceRange(), "non-closure context");
489 }
490
491 GlobalDecl gd;
492 if (const auto *cd = dyn_cast<CXXConstructorDecl>(dc))
493 gd = GlobalDecl(cd, Ctor_Base);
494 else if (const auto *dd = dyn_cast<CXXDestructorDecl>(dc))
495 gd = GlobalDecl(dd, Dtor_Base);
496 else if (const auto *fd = dyn_cast<FunctionDecl>(dc))
497 gd = GlobalDecl(fd);
498 else {
499 // Don't do anything for Obj-C method decls or global closures. We should
500 // never defer them.
501 assert(isa<ObjCMethodDecl>(dc) && "unexpected parent code decl");
502 }
504 // Disable emission of the parent function for the OpenMP device codegen.
505 errorNYI(d.getSourceRange(), "OpenMP");
506 }
507
508 return gv;
509}
510
512 mlir::Attribute constAttr,
513 CharUnits align) {
514 auto functionName = [&](const DeclContext *dc) -> std::string {
515 if (const auto *fd = dyn_cast<FunctionDecl>(dc)) {
516 if (const auto *cc = dyn_cast<CXXConstructorDecl>(fd))
517 return cc->getNameAsString();
518 if (const auto *cd = dyn_cast<CXXDestructorDecl>(fd))
519 return cd->getNameAsString();
520 return std::string(getMangledName(fd));
521 } else if (const auto *om = dyn_cast<ObjCMethodDecl>(dc)) {
522 return om->getNameAsString();
523 } else if (isa<BlockDecl>(dc)) {
524 return "<block>";
525 } else if (isa<CapturedDecl>(dc)) {
526 return "<captured>";
527 } else {
528 llvm_unreachable("expected a function or method");
529 }
530 };
531
532 // Form a simple per-variable cache of these values in case we find we
533 // want to reuse them.
534 cir::GlobalOp &cacheEntry = initializerConstants[&d];
535 if (!cacheEntry || cacheEntry.getInitialValue() != constAttr) {
536 auto ty = mlir::cast<mlir::TypedAttr>(constAttr).getType();
537 bool isConstant = true;
538
539 std::string name;
540 if (d.hasGlobalStorage())
541 name = getMangledName(&d).str() + ".const";
542 else if (const DeclContext *dc = d.getParentFunctionOrMethod())
543 name = ("__const." + functionName(dc) + "." + d.getName()).str();
544 else
545 llvm_unreachable("local variable has no parent function or method");
546
548 cir::GlobalOp gv = builder.createVersionedGlobal(
549 getModule(), getLoc(d.getLocation()), name, ty, isConstant,
550 cir::GlobalLinkageKind::PrivateLinkage);
552 // TODO(cir): infer visibility from linkage in global op builder.
553 gv.setVisibility(getMLIRVisibilityFromCIRLinkage(
554 cir::GlobalLinkageKind::PrivateLinkage));
555 gv.setInitialValueAttr(constAttr);
556 gv.setAlignment(align.getAsAlign().value());
557 // TODO(cir): Set unnamed address attribute when available in CIR
558
559 cacheEntry = gv;
560 } else if (cacheEntry.getAlignment() < align.getQuantity()) {
561 cacheEntry.setAlignment(align.getAsAlign().value());
562 }
563
564 // Create a GetGlobalOp to get a pointer to the global
566 mlir::Type eltTy = mlir::cast<mlir::TypedAttr>(constAttr).getType();
567 auto ptrTy = builder.getPointerTo(cacheEntry.getSymType());
568 mlir::Value globalPtr = cir::GetGlobalOp::create(
569 builder, getLoc(d.getLocation()), ptrTy, cacheEntry.getSymName());
570 return Address(globalPtr, eltTy, align);
571}
572
573/// Add the initializer for 'd' to the global variable that has already been
574/// created for it. If the initializer has a different type than gv does, this
575/// may free gv and return a different one. Otherwise it just returns gv.
577 const VarDecl &d, cir::GlobalOp gv, cir::GetGlobalOp gvAddr) {
578 ConstantEmitter emitter(*this);
579 mlir::TypedAttr init = mlir::dyn_cast_if_present<mlir::TypedAttr>(
580 emitter.tryEmitForInitializer(d));
581
582 // If constant emission failed, then this should be a C++ static
583 // initializer.
584 if (!init) {
585 if (!getLangOpts().CPlusPlus) {
586 cgm.errorNYI(d.getInit()->getSourceRange(),
587 "constant l-value expression");
588 } else if (d.hasFlexibleArrayInit(getContext())) {
589 cgm.errorNYI(d.getInit()->getSourceRange(), "flexible array initializer");
590 } else {
591 // Since we have a static initializer, this global variable can't
592 // be constant.
593 gv.setConstant(false);
594 emitCXXGuardedInit(d, gv, /*performInit*/ true);
595 gvAddr.setStaticLocal(true);
596 }
597 return gv;
598 }
599
600 // TODO(cir): There should be debug code here to assert that the decl size
601 // matches the CIR data layout type alloc size, but the code for calculating
602 // the type alloc size is not implemented yet.
604
605 // The initializer may differ in type from the global. Rewrite
606 // the global to match the initializer. (We have to do this
607 // because some types, like unions, can't be completely represented
608 // in the LLVM type system.)
609 if (gv.getSymType() != init.getType()) {
610 gv.setSymType(init.getType());
611
612 // Normally this should be done with a call to cgm.replaceGlobal(oldGV, gv),
613 // but since at this point the current block hasn't been really attached,
614 // there's no visibility into the GetGlobalOp corresponding to this Global.
615 // Given those constraints, thread in the GetGlobalOp and update it
616 // directly.
618 gvAddr.getAddr().setType(builder.getPointerTo(init.getType()));
619 }
620
621 bool needsDtor =
623
624 gv.setConstant(d.getType().isConstantStorage(
625 getContext(), /*ExcludeCtor=*/true, !needsDtor));
626 gv.setInitialValueAttr(init);
627
628 emitter.finalize(gv);
629
630 if (needsDtor) {
631 // We have a constant initializer, but a nontrivial destructor. We still
632 // need to perform a guarded "initialization" in order to register the
633 // destructor.
634 emitCXXGuardedInit(d, gv, /*performInit=*/false);
635 gvAddr.setStaticLocal(true);
636 }
637
638 return gv;
639}
640
642 cir::GlobalLinkageKind linkage) {
643 // Check to see if we already have a global variable for this
644 // declaration. This can happen when double-emitting function
645 // bodies, e.g. with complete and base constructors.
646 cir::GlobalOp globalOp = cgm.getOrCreateStaticVarDecl(d, linkage);
647 // TODO(cir): we should have a way to represent global ops as values without
648 // having to emit a get global op. Sometimes these emissions are not used.
649 mlir::Value addr =
650 builder.createGetGlobal(globalOp, d.getTLSKind() != VarDecl::TLS_None);
651 auto getAddrOp = addr.getDefiningOp<cir::GetGlobalOp>();
652 assert(getAddrOp && "expected cir::GetGlobalOp");
653
654 CharUnits alignment = getContext().getDeclAlign(&d);
655
656 // Store into LocalDeclMap before generating initializer to handle
657 // circular references.
658 mlir::Type elemTy = convertTypeForMem(d.getType());
659 setAddrOfLocalVar(&d, Address(addr, elemTy, alignment));
660
661 // We can't have a VLA here, but we can have a pointer to a VLA,
662 // even though that doesn't really make any sense.
663 // Make sure to evaluate VLA bounds now so that we have them for later.
664 if (d.getType()->isVariablyModifiedType()) {
665 cgm.errorNYI(d.getSourceRange(),
666 "emitStaticVarDecl: variably modified type");
667 }
668
669 // Save the type in case adding the initializer forces a type change.
670 mlir::Type expectedType = addr.getType();
671
672 cir::GlobalOp var = globalOp;
673
675
676 // If this value has an initializer, emit it.
677 if (d.getInit())
678 var = addInitializerToStaticVarDecl(d, var, getAddrOp);
679
680 var.setAlignment(alignment.getAsAlign().value());
681
682 // There are a lot of attributes that need to be handled here. Until
683 // we start to support them, we just report an error if there are any.
684 if (d.hasAttr<AnnotateAttr>())
685 cgm.addGlobalAnnotations(&d, var);
686 if (d.getAttr<PragmaClangBSSSectionAttr>())
687 cgm.errorNYI(d.getSourceRange(),
688 "emitStaticVarDecl: CIR global BSS section attribute");
689 if (d.getAttr<PragmaClangDataSectionAttr>())
690 cgm.errorNYI(d.getSourceRange(),
691 "emitStaticVarDecl: CIR global Data section attribute");
692 if (d.getAttr<PragmaClangRodataSectionAttr>())
693 cgm.errorNYI(d.getSourceRange(),
694 "emitStaticVarDecl: CIR global Rodata section attribute");
695 if (d.getAttr<PragmaClangRelroSectionAttr>())
696 cgm.errorNYI(d.getSourceRange(),
697 "emitStaticVarDecl: CIR global Relro section attribute");
698
699 if (d.getAttr<SectionAttr>())
700 cgm.errorNYI(d.getSourceRange(),
701 "emitStaticVarDecl: CIR global object file section attribute");
702
703 if (cgm.getCodeGenOpts().KeepPersistentStorageVariables)
704 cgm.errorNYI(d.getSourceRange(), "static var keep persistent storage");
705
706 // From traditional codegen:
707 // We may have to cast the constant because of the initializer
708 // mismatch above.
709 //
710 // FIXME: It is really dangerous to store this in the map; if anyone
711 // RAUW's the GV uses of this constant will be invalid.
712 mlir::Value castedAddr =
713 builder.createBitcast(getAddrOp.getAddr(), expectedType);
714 localDeclMap.find(&d)->second = Address(castedAddr, elemTy, alignment);
715 cgm.setStaticLocalDeclAddress(&d, var);
716
719}
720
721void CIRGenFunction::emitScalarInit(const Expr *init, mlir::Location loc,
722 LValue lvalue, bool capturedByInit) {
724
725 SourceLocRAIIObject locRAII{*this, loc};
726 mlir::Value value = emitScalarExpr(init);
727 if (capturedByInit) {
728 cgm.errorNYI(init->getSourceRange(), "emitScalarInit: captured by init");
729 return;
730 }
732 emitStoreThroughLValue(RValue::get(value), lvalue, true);
733}
734
736 LValue lvalue, bool capturedByInit) {
737 SourceLocRAIIObject loc{*this, getLoc(init->getSourceRange())};
738 if (capturedByInit) {
739 cgm.errorNYI(init->getSourceRange(), "emitExprAsInit: captured by init");
740 return;
741 }
742
743 QualType type = d->getType();
744
745 if (type->isReferenceType()) {
746 RValue rvalue = emitReferenceBindingToExpr(init);
747 if (capturedByInit)
748 cgm.errorNYI(init->getSourceRange(), "emitExprAsInit: captured by init");
749 emitStoreThroughLValue(rvalue, lvalue);
750 return;
751 }
753 case cir::TEK_Scalar:
754 emitScalarInit(init, getLoc(d->getSourceRange()), lvalue);
755 return;
756 case cir::TEK_Complex: {
757 mlir::Value complex = emitComplexExpr(init);
758 if (capturedByInit)
759 cgm.errorNYI(init->getSourceRange(),
760 "emitExprAsInit: complex type captured by init");
761 mlir::Location loc = getLoc(init->getExprLoc());
762 emitStoreOfComplex(loc, complex, lvalue,
763 /*isInit*/ true);
764 return;
765 }
767 // The overlap flag here should be calculated.
769 emitAggExpr(init,
773 return;
774 }
775 llvm_unreachable("bad evaluation kind");
776}
777
778void CIRGenFunction::emitDecl(const Decl &d, bool evaluateConditionDecl) {
779 switch (d.getKind()) {
780 case Decl::BuiltinTemplate:
781 case Decl::TranslationUnit:
782 case Decl::ExternCContext:
783 case Decl::Namespace:
784 case Decl::UnresolvedUsingTypename:
785 case Decl::ClassTemplateSpecialization:
786 case Decl::ClassTemplatePartialSpecialization:
787 case Decl::VarTemplateSpecialization:
788 case Decl::VarTemplatePartialSpecialization:
789 case Decl::TemplateTypeParm:
790 case Decl::UnresolvedUsingValue:
791 case Decl::NonTypeTemplateParm:
792 case Decl::CXXDeductionGuide:
793 case Decl::CXXMethod:
794 case Decl::CXXConstructor:
795 case Decl::CXXDestructor:
796 case Decl::CXXConversion:
797 case Decl::Field:
798 case Decl::MSProperty:
799 case Decl::IndirectField:
800 case Decl::ObjCIvar:
801 case Decl::ObjCAtDefsField:
802 case Decl::ParmVar:
803 case Decl::ImplicitParam:
804 case Decl::ClassTemplate:
805 case Decl::VarTemplate:
806 case Decl::FunctionTemplate:
807 case Decl::TypeAliasTemplate:
808 case Decl::TemplateTemplateParm:
809 case Decl::ObjCMethod:
810 case Decl::ObjCCategory:
811 case Decl::ObjCProtocol:
812 case Decl::ObjCInterface:
813 case Decl::ObjCCategoryImpl:
814 case Decl::ObjCImplementation:
815 case Decl::ObjCProperty:
816 case Decl::ObjCCompatibleAlias:
817 case Decl::PragmaComment:
818 case Decl::PragmaDetectMismatch:
819 case Decl::AccessSpec:
820 case Decl::LinkageSpec:
821 case Decl::Export:
822 case Decl::ObjCPropertyImpl:
823 case Decl::FileScopeAsm:
824 case Decl::Friend:
825 case Decl::FriendTemplate:
826 case Decl::Block:
827 case Decl::OutlinedFunction:
828 case Decl::Captured:
829 case Decl::UsingShadow:
830 case Decl::ConstructorUsingShadow:
831 case Decl::ObjCTypeParam:
832 case Decl::Binding:
833 case Decl::UnresolvedUsingIfExists:
834 case Decl::HLSLBuffer:
835 case Decl::HLSLRootSignature:
836 llvm_unreachable("Declaration should not be in declstmts!");
837
838 case Decl::Function: // void X();
839 case Decl::EnumConstant: // enum ? { X = ? }
840 case Decl::ExplicitInstantiation:
841 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
842 case Decl::Label: // __label__ x;
843 case Decl::Import:
844 case Decl::MSGuid: // __declspec(uuid("..."))
845 case Decl::TemplateParamObject:
846 case Decl::Empty:
847 case Decl::Concept:
848 case Decl::LifetimeExtendedTemporary:
849 case Decl::RequiresExprBody:
850 case Decl::UnnamedGlobalConstant:
851 // None of these decls require codegen support.
852 return;
853
854 case Decl::Enum: // enum X;
855 case Decl::Record: // struct/union/class X;
856 case Decl::CXXRecord: // struct/union/class X; [C++]
857 case Decl::NamespaceAlias:
858 case Decl::Using: // using X; [C++]
859 case Decl::UsingEnum: // using enum X; [C++]
860 case Decl::UsingDirective: // using namespace X; [C++]
862 return;
863 case Decl::Var:
864 case Decl::Decomposition: {
865 const VarDecl &vd = cast<VarDecl>(d);
866 assert(vd.isLocalVarDecl() &&
867 "Should not see file-scope variables inside a function!");
868 emitVarDecl(vd);
869 if (evaluateConditionDecl)
871 return;
872 }
873 case Decl::OpenACCDeclare:
875 return;
876 case Decl::OpenACCRoutine:
878 return;
879 case Decl::OMPThreadPrivate:
881 return;
882 case Decl::OMPGroupPrivate:
884 return;
885 case Decl::OMPAllocate:
887 return;
888 case Decl::OMPCapturedExpr:
890 return;
891 case Decl::OMPRequires:
893 return;
894 case Decl::OMPDeclareMapper:
896 return;
897 case Decl::OMPDeclareReduction:
899 return;
900 case Decl::Typedef: // typedef int X;
901 case Decl::TypeAlias: { // using X = int; [C++0x]
902 QualType ty = cast<TypedefNameDecl>(d).getUnderlyingType();
904 if (ty->isVariablyModifiedType())
906 return;
907 }
908 case Decl::ImplicitConceptSpecialization:
909 case Decl::TopLevelStmt:
910 case Decl::UsingPack:
911 cgm.errorNYI(d.getSourceRange(),
912 std::string("emitDecl: unhandled decl type: ") +
913 d.getDeclKindName());
914 }
915}
916
918 SourceLocation loc) {
919 if (!sanOpts.has(SanitizerKind::NullabilityAssign))
920 return;
921
923}
924
925namespace {
926struct DestroyObject final : EHScopeStack::Cleanup {
927 DestroyObject(Address addr, QualType type,
928 CIRGenFunction::Destroyer *destroyer)
929 : addr(addr), type(type), destroyer(destroyer) {
931 }
932
933 Address addr;
935 CIRGenFunction::Destroyer *destroyer;
936
937 void emit(CIRGenFunction &cgf, Flags flags) override {
939 cgf.emitDestroy(addr, type, destroyer);
940 }
941};
942
943template <class Derived> struct DestroyNRVOVariable : EHScopeStack::Cleanup {
944 DestroyNRVOVariable(Address addr, QualType type, mlir::Value nrvoFlag)
945 : nrvoFlag(nrvoFlag), addr(addr), ty(type) {}
946
947 mlir::Value nrvoFlag;
948 Address addr;
949 QualType ty;
950
951 void emit(CIRGenFunction &cgf, Flags flags) override {
952 // Along the exceptions path we always execute the dtor.
953 bool nrvo = flags.isForNormalCleanup() && nrvoFlag;
954
955 CIRGenBuilderTy &builder = cgf.getBuilder();
956 mlir::OpBuilder::InsertionGuard guard(builder);
957 if (nrvo) {
958 // If we exited via NRVO, we skip the destructor call.
959 mlir::Location loc = addr.getPointer().getLoc();
960 mlir::Value didNRVO = builder.createFlagLoad(loc, nrvoFlag);
961 mlir::Value notNRVO = builder.createNot(didNRVO);
962 cir::IfOp::create(builder, loc, notNRVO, /*withElseRegion=*/false,
963 [&](mlir::OpBuilder &b, mlir::Location) {
964 static_cast<Derived *>(this)->emitDestructorCall(cgf);
965 builder.createYield(loc);
966 });
967 } else {
968 static_cast<Derived *>(this)->emitDestructorCall(cgf);
969 }
970 }
971
972 virtual ~DestroyNRVOVariable() = default;
973};
974
975struct DestroyNRVOVariableCXX final
976 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
977 DestroyNRVOVariableCXX(Address addr, QualType type,
978 const CXXDestructorDecl *dtor, mlir::Value nrvoFlag)
979 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, nrvoFlag),
980 dtor(dtor) {}
981
982 const CXXDestructorDecl *dtor;
983
984 void emitDestructorCall(CIRGenFunction &cgf) {
986 /*forVirtualBase=*/false,
987 /*delegating=*/false, addr, ty);
988 }
989};
990
991struct CallStackRestore final : EHScopeStack::Cleanup {
992 Address stack;
993 CallStackRestore(Address stack) : stack(stack) {}
994 void emit(CIRGenFunction &cgf, Flags flags) override {
995 mlir::Location loc = stack.getPointer().getLoc();
996 mlir::Value v = cgf.getBuilder().createLoad(loc, stack);
997 cgf.getBuilder().createStackRestore(loc, v);
998 }
999};
1000
1001/// A cleanup which performs a partial array destroy where the end pointer is
1002/// irregularly determined and must be loaded from a local.
1003struct IrregularPartialArrayDestroy final : EHScopeStack::Cleanup {
1004 mlir::Value arrayBegin;
1005 Address arrayEndPointer;
1006 QualType elementType;
1007 CharUnits elementAlign;
1008 CIRGenFunction::Destroyer *destroyer;
1009
1010 IrregularPartialArrayDestroy(mlir::Value arrayBegin, Address arrayEndPointer,
1011 QualType elementType, CharUnits elementAlign,
1012 CIRGenFunction::Destroyer *destroyer)
1013 : arrayBegin(arrayBegin), arrayEndPointer(arrayEndPointer),
1014 elementType(elementType), elementAlign(elementAlign),
1015 destroyer(destroyer) {}
1016
1017 void emit(CIRGenFunction &cgf, Flags flags) override {
1018 CIRGenBuilderTy &builder = cgf.getBuilder();
1019 mlir::Location loc = arrayBegin.getLoc();
1020
1021 mlir::Value arrayEnd = builder.createLoad(loc, arrayEndPointer);
1022
1023 // The cleanup is destroying elements in reverse from arrayEnd back to
1024 // arrayBegin, but only if arrayEnd != arrayBegin (i.e. something was
1025 // constructed).
1026 mlir::Type cirElementType = cgf.convertTypeForMem(elementType);
1027 cir::PointerType ptrToElmType = builder.getPointerTo(cirElementType);
1028
1029 mlir::Value ne = cir::CmpOp::create(builder, loc, cir::CmpOpKind::ne,
1030 arrayEnd, arrayBegin);
1031 cir::IfOp::create(
1032 builder, loc, ne, /*withElseRegion=*/false,
1033 [&](mlir::OpBuilder &b, mlir::Location loc) {
1034 Address iterAddr = cgf.createTempAlloca(
1035 ptrToElmType, cgf.getPointerAlign(), loc, "__array_idx");
1036 builder.createStore(loc, arrayEnd, iterAddr);
1037 builder.createDoWhile(
1038 loc,
1039 /*condBuilder=*/
1040 [&](mlir::OpBuilder &b, mlir::Location loc) {
1041 mlir::Value cur = builder.createLoad(loc, iterAddr);
1042 mlir::Value cmp = cir::CmpOp::create(
1043 builder, loc, cir::CmpOpKind::ne, cur, arrayBegin);
1044 builder.createCondition(cmp);
1045 },
1046 /*bodyBuilder=*/
1047 [&](mlir::OpBuilder &b, mlir::Location loc) {
1048 mlir::Value cur = builder.createLoad(loc, iterAddr);
1049 cir::ConstantOp negOne = builder.getConstInt(
1050 loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), -1);
1051 mlir::Value prev = cir::PtrStrideOp::create(
1052 builder, loc, ptrToElmType, cur, negOne);
1053 builder.createStore(loc, prev, iterAddr);
1054 Address elemAddr = Address(prev, cirElementType, elementAlign);
1055 destroyer(cgf, elemAddr, elementType);
1056 builder.createYield(loc);
1057 });
1058 builder.createYield(loc);
1059 });
1060 }
1061};
1062} // namespace
1063
1064/// Push an EH cleanup to destroy already-constructed elements of the given
1065/// array. The cleanup may be popped with deactivateCleanupBlock or
1066/// popCleanupBlock.
1067///
1068/// \param elementType - the immediate element type of the array;
1069/// possibly still an array type
1071 Address arrayEndPointer,
1072 QualType elementType,
1073 CharUnits elementAlign,
1074 Destroyer *destroyer) {
1075 ehStack.pushCleanup<IrregularPartialArrayDestroy>(
1076 EHCleanup, arrayBegin, arrayEndPointer, elementType, elementAlign,
1077 destroyer);
1078}
1079
1080/// pushEHDestroyIfNeeded - Push the standard destructor for the given type as
1081/// an EH-only cleanup. If EH cleanup is not needed, just return.
1083 Address addr, QualType type) {
1084 if (!needsEHCleanup(dtorKind))
1085 return;
1086
1088 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind));
1089}
1090
1091/// Push the standard destructor for the given type as
1092/// at least a normal cleanup.
1094 Address addr, QualType type) {
1095 assert(dtorKind && "cannot push destructor for trivial type");
1096
1097 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1098 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind));
1099}
1100
1102 QualType type, Destroyer *destroyer) {
1103 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1104}
1105
1108 assert(dtorKind && "cannot push destructor for trivial type");
1109
1110 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1112 cleanupKind, addr, type, getDestroyer(dtorKind), cleanupKind & EHCleanup);
1113}
1114
1116 CleanupKind cleanupKind, Address addr, QualType type, Destroyer *destroyer,
1117 bool useEHCleanupForArray) {
1120 destroyer);
1121}
1122
1124 Address addr, QualType type,
1125 Destroyer *destroyer,
1126 bool useEHCleanupForArray) {
1127 if (isInConditionalBranch()) {
1128 cgm.errorNYI("conditional lifetime-extended destroy");
1129 return;
1130 }
1131
1132 // Add the cleanup to the EHStack. After the full-expr, this would be
1133 // deactivated before being popped from the stack.
1134 pushDestroyAndDeferDeactivation(cleanupKind, addr, type, destroyer,
1135 useEHCleanupForArray);
1136
1138
1139 pushCleanupAfterFullExpr(cleanupKind, addr, type, destroyer);
1140}
1141
1143 const PendingCleanupEntry &entry) {
1144 ehStack.pushCleanup<DestroyObject>(entry.kind, entry.addr, entry.type,
1145 entry.destroyer);
1146
1147 if (entry.activeFlag.isValid()) {
1148 EHCleanupScope &scope = cast<EHCleanupScope>(*ehStack.begin());
1149 scope.setActiveFlag(entry.activeFlag);
1151 scope.setTestFlagInEHCleanup(scope.isEHCleanup());
1152 }
1153}
1154
1155/// Destroys all the elements of the given array, beginning from last to first.
1156///
1157/// \param begin - a type* denoting the first element of the array
1158/// \param numElements - the number of elements in the array
1159/// \param elementType - the element type of the array
1160/// \param destroyer - the function to call to destroy elements
1162 mlir::Value numElements,
1163 QualType elementType,
1164 CharUnits elementAlign,
1165 Destroyer *destroyer) {
1166 assert(!elementType->isArrayType());
1167
1168 // Differently from LLVM traditional codegen, use a higher level
1169 // representation instead of lowering directly to a loop.
1170 mlir::Type cirElementType = convertTypeForMem(elementType);
1171 cir::PointerType ptrToElmType = builder.getPointerTo(cirElementType);
1172
1173 auto regionBuilder = [&](mlir::OpBuilder &b, mlir::Location loc) {
1174 mlir::BlockArgument arg =
1175 b.getInsertionBlock()->addArgument(ptrToElmType, loc);
1176 Address curAddr = Address(arg, cirElementType, elementAlign);
1178
1179 // Perform the actual destruction there.
1180 destroyer(*this, curAddr, elementType);
1181
1182 cir::YieldOp::create(b, loc);
1183 };
1184
1185 // For a constant array size, use the static form of ArrayDtor.
1186 if (auto constantCount = numElements.getDefiningOp<cir::ConstantOp>()) {
1187 uint64_t size = 0;
1188 if (auto constIntAttr = constantCount.getValueAttr<cir::IntAttr>())
1189 size = constIntAttr.getUInt();
1190 auto arrayTy = cir::ArrayType::get(cirElementType, size);
1191 mlir::Value arrayOp = builder.createPtrBitcast(begin, arrayTy);
1192 cir::ArrayDtor::create(builder, *currSrcLoc, arrayOp, regionBuilder);
1193 return;
1194 }
1195
1196 // For a dynamic array size (VLA), use the dynamic form of ArrayDtor.
1197 mlir::Value elemBegin = builder.createPtrBitcast(begin, cirElementType);
1198 cir::ArrayDtor::create(builder, *currSrcLoc, elemBegin, numElements,
1199 regionBuilder);
1200}
1201
1202/// Immediately perform the destruction of the given object.
1203///
1204/// \param addr - the address of the object; a type*
1205/// \param type - the type of the object; if an array type, all
1206/// objects are destroyed in reverse order
1207/// \param destroyer - the function to call to destroy individual
1208/// elements
1210 Destroyer *destroyer) {
1212 if (!arrayType)
1213 return destroyer(*this, addr, type);
1214
1215 mlir::Value length = emitArrayLength(arrayType, type, addr);
1216
1217 CharUnits elementAlign = addr.getAlignment().alignmentOfArrayElement(
1218 getContext().getTypeSizeInChars(type));
1219
1220 // If the array length is constant, we can check for zero at compile time.
1221 auto constantCount = length.getDefiningOp<cir::ConstantOp>();
1222 if (constantCount) {
1223 auto constIntAttr = mlir::dyn_cast<cir::IntAttr>(constantCount.getValue());
1224 if (constIntAttr && constIntAttr.getUInt() == 0)
1225 return;
1226 }
1227
1228 mlir::Value begin = addr.getPointer();
1230 emitArrayDestroy(begin, length, type, elementAlign, destroyer);
1231
1232 // If the array destroy didn't use the length op, we can erase it.
1233 if (constantCount && constantCount.use_empty())
1234 constantCount.erase();
1235}
1236
1239 switch (kind) {
1240 case QualType::DK_none:
1241 llvm_unreachable("no destroyer for trivial dtor");
1243 return destroyCXXObject;
1247 cgm.errorNYI("getDestroyer: other destruction kind");
1248 return nullptr;
1249 }
1250 llvm_unreachable("Unknown DestructionKind");
1251}
1252
1254 ehStack.pushCleanup<CallStackRestore>(kind, spMem);
1255}
1256
1257/// Enter a destroy cleanup for the given local variable.
1259 const CIRGenFunction::AutoVarEmission &emission,
1260 QualType::DestructionKind dtorKind) {
1261 assert(dtorKind != QualType::DK_none);
1262
1263 // Note that for __block variables, we want to destroy the
1264 // original stack object, not the possibly forwarded object.
1265 Address addr = emission.getObjectAddress(*this);
1266
1267 const VarDecl *var = emission.variable;
1268 QualType type = var->getType();
1269
1270 CleanupKind cleanupKind = NormalAndEHCleanup;
1271 CIRGenFunction::Destroyer *destroyer = nullptr;
1272
1273 switch (dtorKind) {
1274 case QualType::DK_none:
1275 llvm_unreachable("no cleanup for trivially-destructible variable");
1276
1278 // If there's an NRVO flag on the emission, we need a different
1279 // cleanup.
1280 if (emission.nrvoFlag) {
1281 assert(!type->isArrayType());
1282 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1283 ehStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
1284 emission.nrvoFlag);
1285 return;
1286 }
1287 // Otherwise, this is handled below.
1288 break;
1289
1293 cgm.errorNYI(var->getSourceRange(),
1294 "emitAutoVarTypeCleanup: other dtor kind");
1295 return;
1296 }
1297
1298 // If we haven't chosen a more specific destroyer, use the default.
1299 if (!destroyer)
1300 destroyer = getDestroyer(dtorKind);
1301
1303 ehStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1304}
1305
1307 if (auto *dd = dyn_cast_if_present<DecompositionDecl>(vd)) {
1308 for (auto *b : dd->flat_bindings())
1309 if (auto *hd = b->getHoldingVar())
1310 emitVarDecl(*hd);
1311 }
1312}
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void emitStoresForConstant(CIRGenModule &cgm, const VarDecl &d, Address addr, bool isVolatile, CIRGenBuilderTy &builder, mlir::TypedAttr constant)
static std::string getStaticDeclName(CIRGenModule &cgm, const VarDecl &d)
This file defines OpenACC nodes for declarative directives.
Defines the clang::Expr interface and subclasses for C++ expressions.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
cir::ConditionOp createCondition(mlir::Value condition)
Create a loop condition.
cir::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr)
cir::PointerType getPointerTo(mlir::Type ty)
cir::DoWhileOp createDoWhile(mlir::Location loc, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> condBuilder, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> bodyBuilder)
Create a do-while operation.
mlir::Value createNot(mlir::Location loc, mlir::Value value)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
cir::LoadOp createFlagLoad(mlir::Location loc, mlir::Value addr)
Emit a load from an boolean flag variable.
llvm::TypeSize getTypeAllocSize(mlir::Type ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
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.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3784
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.
clang::CharUnits getAlignment() const
Definition Address.h:138
bool isValid() const
Definition Address.h:77
cir::AllocaOp getUnderlyingAllocaOp() const
Return the underlying alloca for this address, if any.
Definition Address.h:157
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed)
cir::StackRestoreOp createStackRestore(mlir::Location loc, mlir::Value v)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst, bool isVolatile=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false)
void emitOpenACCRoutine(const OpenACCRoutineDecl &d)
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.
static cir::TypeEvaluationKind getEvaluationKind(clang::QualType type)
Return the cir::TypeEvaluationKind of QualType type.
AutoVarEmission emitAutoVarAlloca(const clang::VarDecl &d, mlir::OpBuilder::InsertPoint ip={})
void emitAutoVarTypeCleanup(const AutoVarEmission &emission, clang::QualType::DestructionKind dtorKind)
Enter a destroy cleanup for the given local variable.
void emitVariablyModifiedType(QualType ty)
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 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,...
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.
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 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 pushCleanupAndDeferDeactivation(CleanupKind kind, As... a)
Push a cleanup and record it for deferred deactivation.
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
void emitOMPDeclareReduction(const OMPDeclareReductionDecl &d)
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::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...
RValue emitReferenceBindingToExpr(const Expr *e)
Emits a reference binding to the passed in expression.
void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind, Address addr, QualType type)
CleanupKind getCleanupKind(QualType::DestructionKind kind)
void emitOMPAllocateDecl(const OMPAllocateDecl &d)
void emitOMPDeclareMapper(const OMPDeclareMapperDecl &d)
EHScopeStack ehStack
Tracks function scope overall cleanup handling.
clang::SanitizerSet sanOpts
Sanitizers enabled for this function.
mlir::Type convertTypeForMem(QualType t)
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Push the standard destructor for the given type as at least a normal cleanup.
void emitVarDecl(const clang::VarDecl &d)
This method handles emission of any variable declaration inside a function, including static vars etc...
Address returnValue
The temporary alloca to hold the return value.
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.
void emitStoreOfComplex(mlir::Location loc, mlir::Value v, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
void emitScalarInit(const clang::Expr *init, mlir::Location loc, LValue lvalue, bool capturedByInit=false)
void emitAutoVarInit(const AutoVarEmission &emission)
Emit the initializer for an allocated variable.
void maybeEmitDeferredVarDeclInit(const VarDecl *vd)
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)
void emitAutoVarDecl(const clang::VarDecl &d)
Emit code and set up symbol table for a variable declaration with auto, register, or no storage class...
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
CIRGenBuilderTy & getBuilder()
bool didCallStackSave
Whether a cir.stacksave operation has been added.
void emitDecl(const clang::Decl &d, bool evaluateConditionDecl=false)
void emitDestroy(Address addr, QualType type, Destroyer *destroyer)
Immediately perform the destruction of the given object.
void pushPendingCleanupToEHStack(const PendingCleanupEntry &entry)
Promote a single pending cleanup entry onto the EH scope stack.
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...
mlir::MLIRContext & getMLIRContext()
Destroyer * getDestroyer(clang::QualType::DestructionKind kind)
void Destroyer(CIRGenFunction &cgf, Address addr, QualType ty)
DeclMapTy localDeclMap
This keeps track of the CIR allocas or globals for local C declarations.
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)
void emitOMPGroupPrivateDecl(const OMPGroupPrivateDecl &d)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
void emitCXXDestructorCall(const CXXDestructorDecl *dd, CXXDtorType type, bool forVirtualBase, bool delegating, Address thisAddr, QualType thisTy)
void pushFullExprCleanup(CleanupKind kind, As... a)
Push a cleanup to be run at the end of the current full-expression.
std::optional< mlir::Location > currSrcLoc
Use to track source locations across nested visitor traversals.
clang::ASTContext & getContext() const
void setAddrOfLocalVar(const clang::VarDecl *vd, Address addr)
Set the address of a local variable.
void pushCleanupAfterFullExpr(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer)
Queue a cleanup to be pushed after finishing the current full-expression.
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...
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 ...
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
void emitAggExpr(const clang::Expr *e, AggValueSlot slot)
void emitAutoVarCleanups(const AutoVarEmission &emission)
This class organizes the cross-function state that is used while generating CIR code.
llvm::StringRef getMangledName(clang::GlobalDecl gd)
cir::GlobalOp getOrCreateStaticVarDecl(const VarDecl &d, cir::GlobalLinkageKind linkage)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
clang::ASTContext & getASTContext() const
void insertGlobalSymbol(mlir::Operation *op)
mlir::Type convertType(clang::QualType type)
llvm::DenseMap< const VarDecl *, cir::GlobalOp > initializerConstants
void setGVProperties(mlir::Operation *op, const NamedDecl *d) const
Set visibility, dllimport/dllexport and dso_local.
static mlir::SymbolTable::Visibility getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK)
void setTLSMode(mlir::Operation *op, const VarDecl &d, bool isExtendingDecl=false)
Set TLS mode for the given operation based on the given variable declaration.
const clang::LangOptions & getLangOpts() const
mlir::Location getLoc(clang::SourceLocation cLoc)
Helpers to convert the presumed location of Clang's SourceLocation to an MLIR Location.
mlir::ModuleOp getModule() const
mlir::MLIRContext & getMLIRContext()
cir::GlobalOp getStaticLocalDeclAddress(const VarDecl *d)
Address createUnnamedGlobalFrom(const VarDecl &d, mlir::Attribute constAttr, CharUnits align)
mlir::Type convertTypeForMem(clang::QualType, bool forBitField=false)
Convert type T into an mlir::Type.
mlir::Attribute tryEmitForInitializer(const VarDecl &d)
Try to emit the initializer of the given declaration as an abstract constant.
mlir::Attribute tryEmitAbstractForInitializer(const VarDecl &d)
Try to emit the initializer of the given declaration as an abstract constant.
A cleanup scope which generates the cleanup blocks lazily.
void setTestFlagInEHCleanup(bool value)
void setTestFlagInNormalCleanup(bool value)
void setActiveFlag(Address var)
Information for lazily generating a cleanup.
Address getAddress() const
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
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a C++ constructor within a class.
Definition DeclCXX.h:2620
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
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
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:214
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:341
T * getAttr() const
Definition DeclBase.h:581
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
SourceLocation getLocation() const
Definition DeclBase.h:447
const char * getDeclKindName() const
Definition DeclBase.cpp:169
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
Kind getKind() const
Definition DeclBase.h:450
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
This represents one expression.
Definition Expr.h:112
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3355
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
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
const Decl * getDecl() const
Definition GlobalDecl.h:106
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:317
bool isExternallyVisible() const
Definition Decl.h:433
A (possibly-)qualified type.
Definition TypeBase.h:937
@ PDIK_Struct
The type is a struct containing a field whose type is not PCK_Trivial.
Definition TypeBase.h:1493
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8566
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1036
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2789
Represents a struct/union/class.
Definition Decl.h:4331
Encodes a location in the source.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2518
bool isArrayType() const
Definition TypeBase.h:8776
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2862
bool isVectorType() const
Definition TypeBase.h:8816
bool isSamplerT() const
Definition TypeBase.h:8921
bool isRecordType() const
Definition TypeBase.h:8804
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1582
TLSKind getTLSKind() const
Definition Decl.cpp:2148
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2170
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
Definition Decl.cpp:2821
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2466
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition Decl.h:1525
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2810
const Expr * getInit() const
Definition Decl.h:1381
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1230
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
@ TLS_None
Not a TLS variable.
Definition Decl.h:944
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1266
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1242
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition Decl.cpp:2670
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
The JSON file list parser is used to communicate input to InstallAPI.
@ Ctor_Base
Base object ctor.
Definition ABI.h:26
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:345
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
U cast(CodeGen::Address addr)
Definition Address.h:327
float __ovld __cnfn length(float)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
static bool objCLifetime()
static bool addAutoInitAnnotation()
static bool addressSpace()
static bool emitNullabilityCheck()
static bool useEHCleanupForArray()
static bool vectorConstants()
static bool aggValueSlotMayOverlap()
static bool dtorCleanups()
static bool dataLayoutTypeAllocSize()
static bool opAllocaCaptureByInit()
static bool opAllocaPreciseLifetime()
static bool cudaSupport()
static bool generateDebugInfo()
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 isConstantAggregate
True if the variable is of aggregate type and has a constant initializer.
Address getObjectAddress(CIRGenFunction &cgf) const
Returns the address of the object within this declaration.
A cleanup entry that will be promoted onto the EH scope stack at a later point.
clang::CharUnits getPointerAlign() const
cir::PointerType allocaInt8PtrTy
void* in alloca address space