| 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 "CIRGenConstantEmitter.h" |
| 14 |
#include "CIRGenFunction.h" |
| 15 |
#include "mlir/IR/Location.h" |
| 16 |
#include "clang/AST/Attr.h" |
| 17 |
#include "clang/AST/Decl.h" |
| 18 |
#include "clang/AST/DeclOpenACC.h" |
| 19 |
#include "clang/AST/Expr.h" |
| 20 |
#include "clang/AST/ExprCXX.h" |
| 21 |
#include "clang/CIR/MissingFeatures.h" |
| 22 |
|
| 23 |
using namespace clang; |
| 24 |
using namespace clang::CIRGen; |
| 25 |
|
| 26 |
CIRGenFunction::AutoVarEmission |
| 27 |
CIRGenFunction::emitAutoVarAlloca(const VarDecl &d, |
| 28 |
mlir::OpBuilder::InsertPoint ip) { |
| 29 |
QualType ty = d.getType(); |
| 30 |
if (ty.getAddressSpace() != LangAS::Default) |
| 31 |
cgm.errorNYI(d.getSourceRange(), "emitAutoVarAlloca: address space"); |
| 32 |
|
| 33 |
mlir::Location loc = getLoc(d.getSourceRange()); |
| 34 |
bool nrvo = |
| 35 |
getContext().getLangOpts().ElideConstructors && d.isNRVOVariable(); |
| 36 |
|
| 37 |
CIRGenFunction::AutoVarEmission emission(d); |
| 38 |
emission.isEscapingByRef = d.isEscapingByref(); |
| 39 |
if (emission.isEscapingByRef) |
| 40 |
cgm.errorNYI(d.getSourceRange(), |
| 41 |
"emitAutoVarDecl: decl escaping by reference"); |
| 42 |
|
| 43 |
CharUnits alignment = getContext().getDeclAlign(&d); |
| 44 |
|
| 45 |
// If the type is variably-modified, emit all the VLA sizes for it. |
| 46 |
if (ty->isVariablyModifiedType()) |
| 47 |
emitVariablyModifiedType(ty); |
| 48 |
|
| 49 |
assert(!cir::MissingFeatures::openMP()); |
| 50 |
|
| 51 |
Address address = Address::invalid(); |
| 52 |
if (ty->isConstantSizeType()) { |
| 53 |
// If this value is an array, struct, or vector with a statically |
| 54 |
// determinable constant initializer, there are optimizations we can do. |
| 55 |
// |
| 56 |
// TODO: We should constant-evaluate the initializer of any variable, |
| 57 |
// as long as it is initialized by a constant expression. Currently, |
| 58 |
// isConstantInitializer produces wrong answers for structs with |
| 59 |
// reference or bitfield members, and a few other cases, and checking |
| 60 |
// for POD-ness protects us from some of these. |
| 61 |
if (d.getInit() && |
| 62 |
(ty->isArrayType() || ty->isRecordType() || ty->isVectorType()) && |
| 63 |
(d.isConstexpr() || |
| 64 |
((ty.isPODType(getContext()) || |
| 65 |
getContext().getBaseElementType(ty)->isObjCObjectPointerType()) && |
| 66 |
d.getInit()->isConstantInitializer(getContext(), false)))) { |
| 67 |
|
| 68 |
// If the variable's a const type, and it's neither an NRVO |
| 69 |
// candidate nor a __block variable and has no mutable members, |
| 70 |
// emit it as a global instead. |
| 71 |
// Exception is if a variable is located in non-constant address space |
| 72 |
// in OpenCL. |
| 73 |
// TODO(cir): perhaps we don't need this at all at CIR since this can |
| 74 |
// be done as part of lowering down to LLVM. |
| 75 |
bool needsDtor = |
| 76 |
d.needsDestruction(getContext()) == QualType::DK_cxx_destructor; |
| 77 |
if ((!getContext().getLangOpts().OpenCL || |
| 78 |
ty.getAddressSpace() == LangAS::opencl_constant) && |
| 79 |
(cgm.getCodeGenOpts().MergeAllConstants && !nrvo && |
| 80 |
!d.isEscapingByref() && |
| 81 |
ty.isConstantStorage(getContext(), true, !needsDtor))) { |
| 82 |
cgm.errorNYI(d.getSourceRange(), "emitAutoVarAlloca: type constant"); |
| 83 |
} |
| 84 |
// Otherwise, tell the initialization code that we're in this case. |
| 85 |
emission.isConstantAggregate = true; |
| 86 |
} |
| 87 |
|
| 88 |
// A normal fixed sized variable becomes an alloca in the entry block, |
| 89 |
// unless: |
| 90 |
// - it's an NRVO variable. |
| 91 |
// - we are compiling OpenMP and it's an OpenMP local variable. |
| 92 |
if (nrvo) { |
| 93 |
// The named return value optimization: allocate this variable in the |
| 94 |
// return slot, so that we can elide the copy when returning this |
| 95 |
// variable (C++0x [class.copy]p34). |
| 96 |
address = returnValue; |
| 97 |
|
| 98 |
if (const RecordDecl *rd = ty->getAsRecordDecl()) { |
| 99 |
if (const auto *cxxrd = dyn_cast<CXXRecordDecl>(rd); |
| 100 |
(cxxrd && !cxxrd->hasTrivialDestructor()) || |
| 101 |
rd->isNonTrivialToPrimitiveDestroy()) { |
| 102 |
// In LLVM: Create a flag that is used to indicate when the NRVO was |
| 103 |
// applied to this variable. Set it to zero to indicate that NRVO was |
| 104 |
// not applied. For now, use the same approach for CIRGen until we can |
| 105 |
// be sure it's worth doing something more aggressive. |
| 106 |
cir::ConstantOp falseNVRO = builder.getFalse(loc); |
| 107 |
Address nrvoFlag = createTempAlloca(falseNVRO.getType(), |
| 108 |
CharUnits::One(), loc, "nrvo", |
| 109 |
/*arraySize=*/nullptr); |
| 110 |
assert(builder.getInsertionBlock()); |
| 111 |
builder.createStore(loc, falseNVRO, nrvoFlag); |
| 112 |
|
| 113 |
// Record the NRVO flag for this variable. |
| 114 |
nrvoFlags[&d] = nrvoFlag.getPointer(); |
| 115 |
emission.nrvoFlag = nrvoFlag.getPointer(); |
| 116 |
} |
| 117 |
} |
| 118 |
} else { |
| 119 |
// A normal fixed sized variable becomes an alloca in the entry block, |
| 120 |
mlir::Type allocaTy = convertTypeForMem(ty); |
| 121 |
// Create the temp alloca and declare variable using it. |
| 122 |
address = createTempAlloca(allocaTy, alignment, loc, d.getName(), |
| 123 |
/*arraySize=*/nullptr, /*alloca=*/nullptr, ip); |
| 124 |
declare(address.getPointer(), &d, ty, getLoc(d.getSourceRange()), |
| 125 |
alignment); |
| 126 |
} |
| 127 |
} else { |
| 128 |
// Non-constant size type |
| 129 |
assert(!cir::MissingFeatures::openMP()); |
| 130 |
if (!didCallStackSave) { |
| 131 |
// Save the stack. |
| 132 |
cir::PointerType defaultTy = allocaInt8PtrTy; |
| 133 |
CharUnits align = CharUnits::fromQuantity( |
| 134 |
cgm.getDataLayout().getAlignment(defaultTy, false)); |
| 135 |
Address stack = createTempAlloca(defaultTy, align, loc, "saved_stack"); |
| 136 |
|
| 137 |
mlir::Value v = builder.createStackSave(loc, defaultTy); |
| 138 |
assert(v.getType() == allocaInt8PtrTy); |
| 139 |
builder.createStore(loc, v, stack); |
| 140 |
|
| 141 |
didCallStackSave = true; |
| 142 |
|
| 143 |
// Push a cleanup block and restore the stack there. |
| 144 |
// FIXME: in general circumstances, this should be an EH cleanup. |
| 145 |
pushStackRestore(NormalCleanup, stack); |
| 146 |
} |
| 147 |
|
| 148 |
VlaSizePair vlaSize = getVLASize(ty); |
| 149 |
mlir::Type memTy = convertTypeForMem(vlaSize.type); |
| 150 |
|
| 151 |
// Allocate memory for the array. |
| 152 |
address = |
| 153 |
createTempAlloca(memTy, alignment, loc, d.getName(), vlaSize.numElts, |
| 154 |
/*alloca=*/nullptr, builder.saveInsertionPoint()); |
| 155 |
|
| 156 |
// If we have debug info enabled, properly describe the VLA dimensions for |
| 157 |
// this type by registering the vla size expression for each of the |
| 158 |
// dimensions. |
| 159 |
assert(!cir::MissingFeatures::generateDebugInfo()); |
| 160 |
} |
| 161 |
|
| 162 |
emission.addr = address; |
| 163 |
setAddrOfLocalVar(&d, address); |
| 164 |
|
| 165 |
return emission; |
| 166 |
} |
| 167 |
|
| 168 |
/// Determine whether the given initializer is trivial in the sense |
| 169 |
/// that it requires no code to be generated. |
| 170 |
bool CIRGenFunction::isTrivialInitializer(const Expr *init) { |
| 171 |
if (!init) |
| 172 |
return true; |
| 173 |
|
| 174 |
if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(init)) |
| 175 |
if (CXXConstructorDecl *constructor = construct->getConstructor()) |
| 176 |
if (constructor->isTrivial() && constructor->isDefaultConstructor() && |
| 177 |
!construct->requiresZeroInitialization()) |
| 178 |
return true; |
| 179 |
|
| 180 |
return false; |
| 181 |
} |
| 182 |
|
| 183 |
static void emitStoresForConstant(CIRGenModule &cgm, const VarDecl &d, |
| 184 |
Address addr, bool isVolatile, |
| 185 |
CIRGenBuilderTy &builder, |
| 186 |
mlir::TypedAttr constant) { |
| 187 |
mlir::Type ty = constant.getType(); |
| 188 |
cir::CIRDataLayout layout{cgm.getModule()}; |
| 189 |
uint64_t constantSize = layout.getTypeAllocSize(ty); |
| 190 |
if (!constantSize) |
| 191 |
return; |
| 192 |
assert(!cir::MissingFeatures::addAutoInitAnnotation()); |
| 193 |
assert(!cir::MissingFeatures::vectorConstants()); |
| 194 |
assert(!cir::MissingFeatures::shouldUseBZeroPlusStoresToInitialize()); |
| 195 |
assert(!cir::MissingFeatures::shouldUseMemSetToInitialize()); |
| 196 |
assert(!cir::MissingFeatures::shouldSplitConstantStore()); |
| 197 |
assert(!cir::MissingFeatures::shouldCreateMemCpyFromGlobal()); |
| 198 |
// In CIR we want to emit a store for the whole thing, later lowering |
| 199 |
// prepare to LLVM should unwrap this into the best policy (see asserts |
| 200 |
// above). |
| 201 |
// |
| 202 |
// FIXME(cir): This is closer to memcpy behavior but less optimal, instead of |
| 203 |
// copy from a global, we just create a cir.const out of it. |
| 204 |
|
| 205 |
if (addr.getElementType() != ty) |
| 206 |
addr = addr.withElementType(builder, ty); |
| 207 |
|
| 208 |
// If the address is an alloca, set the init attribute. |
| 209 |
// The address is usually and alloca, but there is at least one case where |
| 210 |
// emitAutoVarInit is called from the OpenACC codegen with an address that |
| 211 |
// is not an alloca. |
| 212 |
auto allocaOp = addr.getDefiningOp<cir::AllocaOp>(); |
| 213 |
if (allocaOp) |
| 214 |
allocaOp.setInitAttr(mlir::UnitAttr::get(&cgm.getMLIRContext())); |
| 215 |
|
| 216 |
// There are cases where OpenACC codegen calls emitAutoVarInit with a |
| 217 |
// temporary decl that doesn't have a source range set. |
| 218 |
mlir::Location loc = builder.getUnknownLoc(); |
| 219 |
if (d.getSourceRange().isValid()) |
| 220 |
loc = cgm.getLoc(d.getSourceRange()); |
| 221 |
builder.createStore(loc, builder.getConstant(loc, constant), addr); |
| 222 |
} |
| 223 |
|
| 224 |
void CIRGenFunction::emitAutoVarInit( |
| 225 |
const CIRGenFunction::AutoVarEmission &emission) { |
| 226 |
assert(emission.variable && "emission was not valid!"); |
| 227 |
|
| 228 |
// If this was emitted as a global constant, we're done. |
| 229 |
if (emission.wasEmittedAsGlobal()) |
| 230 |
return; |
| 231 |
|
| 232 |
const VarDecl &d = *emission.variable; |
| 233 |
|
| 234 |
QualType type = d.getType(); |
| 235 |
|
| 236 |
// If this local has an initializer, emit it now. |
| 237 |
const Expr *init = d.getInit(); |
| 238 |
|
| 239 |
// Initialize the variable here if it doesn't have a initializer and it is a |
| 240 |
// C struct that is non-trivial to initialize or an array containing such a |
| 241 |
// struct. |
| 242 |
if (!init && type.isNonTrivialToPrimitiveDefaultInitialize() == |
| 243 |
QualType::PDIK_Struct) { |
| 244 |
cgm.errorNYI(d.getSourceRange(), |
| 245 |
"emitAutoVarInit: non-trivial to default initialize"); |
| 246 |
return; |
| 247 |
} |
| 248 |
|
| 249 |
const Address addr = emission.addr; |
| 250 |
|
| 251 |
// Check whether this is a byref variable that's potentially |
| 252 |
// captured and moved by its own initializer. If so, we'll need to |
| 253 |
// emit the initializer first, then copy into the variable. |
| 254 |
assert(!cir::MissingFeatures::opAllocaCaptureByInit()); |
| 255 |
|
| 256 |
// Note: constexpr already initializes everything correctly. |
| 257 |
LangOptions::TrivialAutoVarInitKind trivialAutoVarInit = |
| 258 |
(d.isConstexpr() |
| 259 |
? LangOptions::TrivialAutoVarInitKind::Uninitialized |
| 260 |
: (d.getAttr<UninitializedAttr>() |
| 261 |
? LangOptions::TrivialAutoVarInitKind::Uninitialized |
| 262 |
: getContext().getLangOpts().getTrivialAutoVarInit())); |
| 263 |
|
| 264 |
auto initializeWhatIsTechnicallyUninitialized = [&](Address addr) { |
| 265 |
if (trivialAutoVarInit == |
| 266 |
LangOptions::TrivialAutoVarInitKind::Uninitialized) |
| 267 |
return; |
| 268 |
|
| 269 |
cgm.errorNYI(d.getSourceRange(), "emitAutoVarInit: trivial initialization"); |
| 270 |
}; |
| 271 |
|
| 272 |
if (isTrivialInitializer(init)) { |
| 273 |
initializeWhatIsTechnicallyUninitialized(addr); |
| 274 |
return; |
| 275 |
} |
| 276 |
|
| 277 |
mlir::Attribute constant; |
| 278 |
if (emission.isConstantAggregate || |
| 279 |
d.mightBeUsableInConstantExpressions(getContext())) { |
| 280 |
// FIXME: Differently from LLVM we try not to emit / lower too much |
| 281 |
// here for CIR since we are interested in seeing the ctor in some |
| 282 |
// analysis later on. So CIR's implementation of ConstantEmitter will |
| 283 |
// frequently return an empty Attribute, to signal we want to codegen |
| 284 |
// some trivial ctor calls and whatnots. |
| 285 |
constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(d); |
| 286 |
if (constant && !mlir::isa<cir::ZeroAttr>(constant) && |
| 287 |
(trivialAutoVarInit != |
| 288 |
LangOptions::TrivialAutoVarInitKind::Uninitialized)) { |
| 289 |
cgm.errorNYI(d.getSourceRange(), "emitAutoVarInit: constant aggregate"); |
| 290 |
return; |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
// NOTE(cir): In case we have a constant initializer, we can just emit a |
| 295 |
// store. But, in CIR, we wish to retain any ctor calls, so if it is a |
| 296 |
// CXX temporary object creation, we ensure the ctor call is used deferring |
| 297 |
// its removal/optimization to the CIR lowering. |
| 298 |
if (!constant || isa<CXXTemporaryObjectExpr>(init)) { |
| 299 |
initializeWhatIsTechnicallyUninitialized(addr); |
| 300 |
LValue lv = makeAddrLValue(addr, type, AlignmentSource::Decl); |
| 301 |
emitExprAsInit(init, &d, lv); |
| 302 |
|
| 303 |
if (!emission.wasEmittedAsOffloadClause()) { |
| 304 |
// In case lv has uses it means we indeed initialized something |
| 305 |
// out of it while trying to build the expression, mark it as such. |
| 306 |
mlir::Value val = lv.getAddress().getPointer(); |
| 307 |
assert(val && "Should have an address"); |
| 308 |
auto allocaOp = val.getDefiningOp<cir::AllocaOp>(); |
| 309 |
assert(allocaOp && "Address should come straight out of the alloca"); |
| 310 |
|
| 311 |
if (!allocaOp.use_empty()) |
| 312 |
allocaOp.setInitAttr(mlir::UnitAttr::get(&getMLIRContext())); |
| 313 |
} |
| 314 |
|
| 315 |
return; |
| 316 |
} |
| 317 |
|
| 318 |
// FIXME(cir): migrate most of this file to use mlir::TypedAttr directly. |
| 319 |
auto typedConstant = mlir::dyn_cast<mlir::TypedAttr>(constant); |
| 320 |
assert(typedConstant && "expected typed attribute"); |
| 321 |
if (!emission.isConstantAggregate) { |
| 322 |
// For simple scalar/complex initialization, store the value directly. |
| 323 |
LValue lv = makeAddrLValue(addr, type); |
| 324 |
assert(init && "expected initializer"); |
| 325 |
mlir::Location initLoc = getLoc(init->getSourceRange()); |
| 326 |
// lv.setNonGC(true); |
| 327 |
return emitStoreThroughLValue( |
| 328 |
RValue::get(builder.getConstant(initLoc, typedConstant)), lv); |
| 329 |
} |
| 330 |
|
| 331 |
emitStoresForConstant(cgm, d, addr, type.isVolatileQualified(), builder, |
| 332 |
typedConstant); |
| 333 |
} |
| 334 |
|
| 335 |
void CIRGenFunction::emitAutoVarCleanups( |
| 336 |
const CIRGenFunction::AutoVarEmission &emission) { |
| 337 |
const VarDecl &d = *emission.variable; |
| 338 |
|
| 339 |
// Check the type for a cleanup. |
| 340 |
if (QualType::DestructionKind dtorKind = d.needsDestruction(getContext())) |
| 341 |
emitAutoVarTypeCleanup(emission, dtorKind); |
| 342 |
|
| 343 |
assert(!cir::MissingFeatures::opAllocaPreciseLifetime()); |
| 344 |
|
| 345 |
// Handle the cleanup attribute. |
| 346 |
if (d.hasAttr<CleanupAttr>()) |
| 347 |
cgm.errorNYI(d.getSourceRange(), "emitAutoVarCleanups: CleanupAttr"); |
| 348 |
} |
| 349 |
|
| 350 |
/// Emit code and set up symbol table for a variable declaration with auto, |
| 351 |
/// register, or no storage class specifier. These turn into simple stack |
| 352 |
/// objects, globals depending on target. |
| 353 |
void CIRGenFunction::emitAutoVarDecl(const VarDecl &d) { |
| 354 |
CIRGenFunction::AutoVarEmission emission = emitAutoVarAlloca(d); |
| 355 |
emitAutoVarInit(emission); |
| 356 |
emitAutoVarCleanups(emission); |
| 357 |
} |
| 358 |
|
| 359 |
void CIRGenFunction::emitVarDecl(const VarDecl &d) { |
| 360 |
// If the declaration has external storage, don't emit it now, allow it to be |
| 361 |
// emitted lazily on its first use. |
| 362 |
if (d.hasExternalStorage()) |
| 363 |
return; |
| 364 |
|
| 365 |
if (d.getStorageDuration() != SD_Automatic) { |
| 366 |
// Static sampler variables translated to function calls. |
| 367 |
if (d.getType()->isSamplerT()) { |
| 368 |
// Nothing needs to be done here, but let's flag it as an error until we |
| 369 |
// have a test. It requires OpenCL support. |
| 370 |
cgm.errorNYI(d.getSourceRange(), "emitVarDecl static sampler type"); |
| 371 |
return; |
| 372 |
} |
| 373 |
|
| 374 |
cir::GlobalLinkageKind linkage = |
| 375 |
cgm.getCIRLinkageVarDefinition(&d, /*IsConstant=*/false); |
| 376 |
|
| 377 |
// FIXME: We need to force the emission/use of a guard variable for |
| 378 |
// some variables even if we can constant-evaluate them because |
| 379 |
// we can't guarantee every translation unit will constant-evaluate them. |
| 380 |
|
| 381 |
return emitStaticVarDecl(d, linkage); |
| 382 |
} |
| 383 |
|
| 384 |
if (d.getType().getAddressSpace() == LangAS::opencl_local) |
| 385 |
cgm.errorNYI(d.getSourceRange(), "emitVarDecl openCL address space"); |
| 386 |
|
| 387 |
assert(d.hasLocalStorage()); |
| 388 |
|
| 389 |
CIRGenFunction::VarDeclContext varDeclCtx{*this, &d}; |
| 390 |
return emitAutoVarDecl(d); |
| 391 |
} |
| 392 |
|
| 393 |
static std::string getStaticDeclName(CIRGenModule &cgm, const VarDecl &d) { |
| 394 |
if (cgm.getLangOpts().CPlusPlus) |
| 395 |
return cgm.getMangledName(&d).str(); |
| 396 |
|
| 397 |
// If this isn't C++, we don't need a mangled name, just a pretty one. |
| 398 |
assert(!d.isExternallyVisible() && "name shouldn't matter"); |
| 399 |
std::string contextName; |
| 400 |
const DeclContext *dc = d.getDeclContext(); |
| 401 |
if (auto *cd = dyn_cast<CapturedDecl>(dc)) |
| 402 |
dc = cast<DeclContext>(cd->getNonClosureContext()); |
| 403 |
if (const auto *fd = dyn_cast<FunctionDecl>(dc)) |
| 404 |
contextName = std::string(cgm.getMangledName(fd)); |
| 405 |
else if (isa<BlockDecl>(dc)) |
| 406 |
cgm.errorNYI(d.getSourceRange(), "block decl context for static var"); |
| 407 |
else if (isa<ObjCMethodDecl>(dc)) |
| 408 |
cgm.errorNYI(d.getSourceRange(), "ObjC decl context for static var"); |
| 409 |
else |
| 410 |
cgm.errorNYI(d.getSourceRange(), "Unknown context for static var decl"); |
| 411 |
|
| 412 |
contextName += "." + d.getNameAsString(); |
| 413 |
return contextName; |
| 414 |
} |
| 415 |
|
| 416 |
// TODO(cir): LLVM uses a Constant base class. Maybe CIR could leverage an |
| 417 |
// interface for all constants? |
| 418 |
cir::GlobalOp |
| 419 |
CIRGenModule::getOrCreateStaticVarDecl(const VarDecl &d, |
| 420 |
cir::GlobalLinkageKind linkage) { |
| 421 |
// In general, we don't always emit static var decls once before we reference |
| 422 |
// them. It is possible to reference them before emitting the function that |
| 423 |
// contains them, and it is possible to emit the containing function multiple |
| 424 |
// times. |
| 425 |
if (cir::GlobalOp existingGV = getStaticLocalDeclAddress(&d)) |
| 426 |
return existingGV; |
| 427 |
|
| 428 |
QualType ty = d.getType(); |
| 429 |
assert(ty->isConstantSizeType() && "VLAs can't be static"); |
| 430 |
|
| 431 |
// Use the label if the variable is renamed with the asm-label extension. |
| 432 |
if (d.hasAttr<AsmLabelAttr>()) |
| 433 |
errorNYI(d.getSourceRange(), "getOrCreateStaticVarDecl: asm label"); |
| 434 |
|
| 435 |
std::string name = getStaticDeclName(*this, d); |
| 436 |
|
| 437 |
mlir::Type lty = getTypes().convertTypeForMem(ty); |
| 438 |
assert(!cir::MissingFeatures::addressSpace()); |
| 439 |
|
| 440 |
if (d.hasAttr<LoaderUninitializedAttr>() || d.hasAttr<CUDASharedAttr>()) |
| 441 |
errorNYI(d.getSourceRange(), |
| 442 |
"getOrCreateStaticVarDecl: LoaderUninitializedAttr"); |
| 443 |
assert(!cir::MissingFeatures::addressSpace()); |
| 444 |
|
| 445 |
mlir::Attribute init = builder.getZeroInitAttr(convertType(ty)); |
| 446 |
|
| 447 |
cir::GlobalOp gv = builder.createVersionedGlobal( |
| 448 |
getModule(), getLoc(d.getLocation()), name, lty, false, linkage); |
| 449 |
// TODO(cir): infer visibility from linkage in global op builder. |
| 450 |
gv.setVisibility(getMLIRVisibilityFromCIRLinkage(linkage)); |
| 451 |
gv.setInitialValueAttr(init); |
| 452 |
gv.setAlignment(getASTContext().getDeclAlign(&d).getAsAlign().value()); |
| 453 |
|
| 454 |
if (supportsCOMDAT() && gv.isWeakForLinker()) |
| 455 |
gv.setComdat(true); |
| 456 |
|
| 457 |
if (d.getTLSKind()) |
| 458 |
errorNYI(d.getSourceRange(), "getOrCreateStaticVarDecl: TLS"); |
| 459 |
|
| 460 |
setGVProperties(gv, &d); |
| 461 |
|
| 462 |
// OG checks if the expected address space, denoted by the type, is the |
| 463 |
// same as the actual address space indicated by attributes. If they aren't |
| 464 |
// the same, an addrspacecast is emitted when this variable is accessed. |
| 465 |
// In CIR however, cir.get_global already carries that information in |
| 466 |
// !cir.ptr type - if this global is in OpenCL local address space, then its |
| 467 |
// type would be !cir.ptr<..., addrspace(offload_local)>. Therefore we don't |
| 468 |
// need an explicit address space cast in CIR: they will get emitted when |
| 469 |
// lowering to LLVM IR. |
| 470 |
|
| 471 |
// Ensure that the static local gets initialized by making sure the parent |
| 472 |
// function gets emitted eventually. |
| 473 |
const Decl *dc = cast<Decl>(d.getDeclContext()); |
| 474 |
|
| 475 |
// We can't name blocks or captured statements directly, so try to emit their |
| 476 |
// parents. |
| 477 |
if (isa<BlockDecl>(dc) || isa<CapturedDecl>(dc)) { |
| 478 |
dc = dc->getNonClosureContext(); |
| 479 |
// FIXME: Ensure that global blocks get emitted. |
| 480 |
if (!dc) |
| 481 |
errorNYI(d.getSourceRange(), "non-closure context"); |
| 482 |
} |
| 483 |
|
| 484 |
GlobalDecl gd; |
| 485 |
if (isa<CXXConstructorDecl>(dc)) |
| 486 |
errorNYI(d.getSourceRange(), "C++ constructors static var context"); |
| 487 |
else if (isa<CXXDestructorDecl>(dc)) |
| 488 |
errorNYI(d.getSourceRange(), "C++ destructors static var context"); |
| 489 |
else if (const auto *fd = dyn_cast<FunctionDecl>(dc)) |
| 490 |
gd = GlobalDecl(fd); |
| 491 |
else { |
| 492 |
// Don't do anything for Obj-C method decls or global closures. We should |
| 493 |
// never defer them. |
| 494 |
assert(isa<ObjCMethodDecl>(dc) && "unexpected parent code decl"); |
| 495 |
} |
| 496 |
if (gd.getDecl() && cir::MissingFeatures::openMP()) { |
| 497 |
// Disable emission of the parent function for the OpenMP device codegen. |
| 498 |
errorNYI(d.getSourceRange(), "OpenMP"); |
| 499 |
} |
| 500 |
|
| 501 |
return gv; |
| 502 |
} |
| 503 |
|
| 504 |
/// Add the initializer for 'd' to the global variable that has already been |
| 505 |
/// created for it. If the initializer has a different type than gv does, this |
| 506 |
/// may free gv and return a different one. Otherwise it just returns gv. |
| 507 |
cir::GlobalOp CIRGenFunction::addInitializerToStaticVarDecl( |
| 508 |
const VarDecl &d, cir::GlobalOp gv, cir::GetGlobalOp gvAddr) { |
| 509 |
ConstantEmitter emitter(*this); |
| 510 |
mlir::TypedAttr init = |
| 511 |
mlir::cast<mlir::TypedAttr>(emitter.tryEmitForInitializer(d)); |
| 512 |
|
| 513 |
// If constant emission failed, then this should be a C++ static |
| 514 |
// initializer. |
| 515 |
if (!init) { |
| 516 |
cgm.errorNYI(d.getSourceRange(), "static var without initializer"); |
| 517 |
return gv; |
| 518 |
} |
| 519 |
|
| 520 |
// TODO(cir): There should be debug code here to assert that the decl size |
| 521 |
// matches the CIR data layout type alloc size, but the code for calculating |
| 522 |
// the type alloc size is not implemented yet. |
| 523 |
assert(!cir::MissingFeatures::dataLayoutTypeAllocSize()); |
| 524 |
|
| 525 |
// The initializer may differ in type from the global. Rewrite |
| 526 |
// the global to match the initializer. (We have to do this |
| 527 |
// because some types, like unions, can't be completely represented |
| 528 |
// in the LLVM type system.) |
| 529 |
if (gv.getSymType() != init.getType()) { |
| 530 |
gv.setSymType(init.getType()); |
| 531 |
|
| 532 |
// Normally this should be done with a call to cgm.replaceGlobal(oldGV, gv), |
| 533 |
// but since at this point the current block hasn't been really attached, |
| 534 |
// there's no visibility into the GetGlobalOp corresponding to this Global. |
| 535 |
// Given those constraints, thread in the GetGlobalOp and update it |
| 536 |
// directly. |
| 537 |
assert(!cir::MissingFeatures::addressSpace()); |
| 538 |
gvAddr.getAddr().setType(builder.getPointerTo(init.getType())); |
| 539 |
} |
| 540 |
|
| 541 |
bool needsDtor = |
| 542 |
d.needsDestruction(getContext()) == QualType::DK_cxx_destructor; |
| 543 |
|
| 544 |
gv.setConstant(d.getType().isConstantStorage( |
| 545 |
getContext(), /*ExcludeCtor=*/true, !needsDtor)); |
| 546 |
gv.setInitialValueAttr(init); |
| 547 |
|
| 548 |
emitter.finalize(gv); |
| 549 |
|
| 550 |
if (needsDtor) { |
| 551 |
// We have a constant initializer, but a nontrivial destructor. We still |
| 552 |
// need to perform a guarded "initialization" in order to register the |
| 553 |
// destructor. |
| 554 |
cgm.errorNYI(d.getSourceRange(), "C++ guarded init"); |
| 555 |
} |
| 556 |
|
| 557 |
return gv; |
| 558 |
} |
| 559 |
|
| 560 |
void CIRGenFunction::emitStaticVarDecl(const VarDecl &d, |
| 561 |
cir::GlobalLinkageKind linkage) { |
| 562 |
// Check to see if we already have a global variable for this |
| 563 |
// declaration. This can happen when double-emitting function |
| 564 |
// bodies, e.g. with complete and base constructors. |
| 565 |
cir::GlobalOp globalOp = cgm.getOrCreateStaticVarDecl(d, linkage); |
| 566 |
// TODO(cir): we should have a way to represent global ops as values without |
| 567 |
// having to emit a get global op. Sometimes these emissions are not used. |
| 568 |
mlir::Value addr = builder.createGetGlobal(globalOp); |
| 569 |
auto getAddrOp = addr.getDefiningOp<cir::GetGlobalOp>(); |
| 570 |
assert(getAddrOp && "expected cir::GetGlobalOp"); |
| 571 |
|
| 572 |
CharUnits alignment = getContext().getDeclAlign(&d); |
| 573 |
|
| 574 |
// Store into LocalDeclMap before generating initializer to handle |
| 575 |
// circular references. |
| 576 |
mlir::Type elemTy = convertTypeForMem(d.getType()); |
| 577 |
setAddrOfLocalVar(&d, Address(addr, elemTy, alignment)); |
| 578 |
|
| 579 |
// We can't have a VLA here, but we can have a pointer to a VLA, |
| 580 |
// even though that doesn't really make any sense. |
| 581 |
// Make sure to evaluate VLA bounds now so that we have them for later. |
| 582 |
if (d.getType()->isVariablyModifiedType()) { |
| 583 |
cgm.errorNYI(d.getSourceRange(), |
| 584 |
"emitStaticVarDecl: variably modified type"); |
| 585 |
} |
| 586 |
|
| 587 |
// Save the type in case adding the initializer forces a type change. |
| 588 |
mlir::Type expectedType = addr.getType(); |
| 589 |
|
| 590 |
cir::GlobalOp var = globalOp; |
| 591 |
|
| 592 |
assert(!cir::MissingFeatures::cudaSupport()); |
| 593 |
|
| 594 |
// If this value has an initializer, emit it. |
| 595 |
if (d.getInit()) |
| 596 |
var = addInitializerToStaticVarDecl(d, var, getAddrOp); |
| 597 |
|
| 598 |
var.setAlignment(alignment.getAsAlign().value()); |
| 599 |
|
| 600 |
// There are a lot of attributes that need to be handled here. Until |
| 601 |
// we start to support them, we just report an error if there are any. |
| 602 |
if (d.hasAttrs()) |
| 603 |
cgm.errorNYI(d.getSourceRange(), "static var with attrs"); |
| 604 |
|
| 605 |
if (cgm.getCodeGenOpts().KeepPersistentStorageVariables) |
| 606 |
cgm.errorNYI(d.getSourceRange(), "static var keep persistent storage"); |
| 607 |
|
| 608 |
// From traditional codegen: |
| 609 |
// We may have to cast the constant because of the initializer |
| 610 |
// mismatch above. |
| 611 |
// |
| 612 |
// FIXME: It is really dangerous to store this in the map; if anyone |
| 613 |
// RAUW's the GV uses of this constant will be invalid. |
| 614 |
mlir::Value castedAddr = |
| 615 |
builder.createBitcast(getAddrOp.getAddr(), expectedType); |
| 616 |
localDeclMap.find(&d)->second = Address(castedAddr, elemTy, alignment); |
| 617 |
cgm.setStaticLocalDeclAddress(&d, var); |
| 618 |
|
| 619 |
assert(!cir::MissingFeatures::sanitizers()); |
| 620 |
assert(!cir::MissingFeatures::generateDebugInfo()); |
| 621 |
} |
| 622 |
|
| 623 |
void CIRGenFunction::emitScalarInit(const Expr *init, mlir::Location loc, |
| 624 |
LValue lvalue, bool capturedByInit) { |
| 625 |
assert(!cir::MissingFeatures::objCLifetime()); |
| 626 |
|
| 627 |
SourceLocRAIIObject locRAII{*this, loc}; |
| 628 |
mlir::Value value = emitScalarExpr(init); |
| 629 |
if (capturedByInit) { |
| 630 |
cgm.errorNYI(init->getSourceRange(), "emitScalarInit: captured by init"); |
| 631 |
return; |
| 632 |
} |
| 633 |
assert(!cir::MissingFeatures::emitNullabilityCheck()); |
| 634 |
emitStoreThroughLValue(RValue::get(value), lvalue, true); |
| 635 |
} |
| 636 |
|
| 637 |
void CIRGenFunction::emitExprAsInit(const Expr *init, const ValueDecl *d, |
| 638 |
LValue lvalue, bool capturedByInit) { |
| 639 |
SourceLocRAIIObject loc{*this, getLoc(init->getSourceRange())}; |
| 640 |
if (capturedByInit) { |
| 641 |
cgm.errorNYI(init->getSourceRange(), "emitExprAsInit: captured by init"); |
| 642 |
return; |
| 643 |
} |
| 644 |
|
| 645 |
QualType type = d->getType(); |
| 646 |
|
| 647 |
if (type->isReferenceType()) { |
| 648 |
RValue rvalue = emitReferenceBindingToExpr(init); |
| 649 |
if (capturedByInit) |
| 650 |
cgm.errorNYI(init->getSourceRange(), "emitExprAsInit: captured by init"); |
| 651 |
emitStoreThroughLValue(rvalue, lvalue); |
| 652 |
return; |
| 653 |
} |
| 654 |
switch (CIRGenFunction::getEvaluationKind(type)) { |
| 655 |
case cir::TEK_Scalar: |
| 656 |
emitScalarInit(init, getLoc(d->getSourceRange()), lvalue); |
| 657 |
return; |
| 658 |
case cir::TEK_Complex: { |
| 659 |
mlir::Value complex = emitComplexExpr(init); |
| 660 |
if (capturedByInit) |
| 661 |
cgm.errorNYI(init->getSourceRange(), |
| 662 |
"emitExprAsInit: complex type captured by init"); |
| 663 |
mlir::Location loc = getLoc(init->getExprLoc()); |
| 664 |
emitStoreOfComplex(loc, complex, lvalue, |
| 665 |
/*isInit*/ true); |
| 666 |
return; |
| 667 |
} |
| 668 |
case cir::TEK_Aggregate: |
| 669 |
// The overlap flag here should be calculated. |
| 670 |
assert(!cir::MissingFeatures::aggValueSlotMayOverlap()); |
| 671 |
emitAggExpr(init, |
| 672 |
AggValueSlot::forLValue(lvalue, AggValueSlot::IsDestructed, |
| 673 |
AggValueSlot::IsNotAliased, |
| 674 |
AggValueSlot::MayOverlap)); |
| 675 |
return; |
| 676 |
} |
| 677 |
llvm_unreachable("bad evaluation kind"); |
| 678 |
} |
| 679 |
|
| 680 |
void CIRGenFunction::emitDecl(const Decl &d, bool evaluateConditionDecl) { |
| 681 |
switch (d.getKind()) { |
| 682 |
case Decl::BuiltinTemplate: |
| 683 |
case Decl::TranslationUnit: |
| 684 |
case Decl::ExternCContext: |
| 685 |
case Decl::Namespace: |
| 686 |
case Decl::UnresolvedUsingTypename: |
| 687 |
case Decl::ClassTemplateSpecialization: |
| 688 |
case Decl::ClassTemplatePartialSpecialization: |
| 689 |
case Decl::VarTemplateSpecialization: |
| 690 |
case Decl::VarTemplatePartialSpecialization: |
| 691 |
case Decl::TemplateTypeParm: |
| 692 |
case Decl::UnresolvedUsingValue: |
| 693 |
case Decl::NonTypeTemplateParm: |
| 694 |
case Decl::CXXDeductionGuide: |
| 695 |
case Decl::CXXMethod: |
| 696 |
case Decl::CXXConstructor: |
| 697 |
case Decl::CXXDestructor: |
| 698 |
case Decl::CXXConversion: |
| 699 |
case Decl::Field: |
| 700 |
case Decl::MSProperty: |
| 701 |
case Decl::IndirectField: |
| 702 |
case Decl::ObjCIvar: |
| 703 |
case Decl::ObjCAtDefsField: |
| 704 |
case Decl::ParmVar: |
| 705 |
case Decl::ImplicitParam: |
| 706 |
case Decl::ClassTemplate: |
| 707 |
case Decl::VarTemplate: |
| 708 |
case Decl::FunctionTemplate: |
| 709 |
case Decl::TypeAliasTemplate: |
| 710 |
case Decl::TemplateTemplateParm: |
| 711 |
case Decl::ObjCMethod: |
| 712 |
case Decl::ObjCCategory: |
| 713 |
case Decl::ObjCProtocol: |
| 714 |
case Decl::ObjCInterface: |
| 715 |
case Decl::ObjCCategoryImpl: |
| 716 |
case Decl::ObjCImplementation: |
| 717 |
case Decl::ObjCProperty: |
| 718 |
case Decl::ObjCCompatibleAlias: |
| 719 |
case Decl::PragmaComment: |
| 720 |
case Decl::PragmaDetectMismatch: |
| 721 |
case Decl::AccessSpec: |
| 722 |
case Decl::LinkageSpec: |
| 723 |
case Decl::Export: |
| 724 |
case Decl::ObjCPropertyImpl: |
| 725 |
case Decl::FileScopeAsm: |
| 726 |
case Decl::Friend: |
| 727 |
case Decl::FriendTemplate: |
| 728 |
case Decl::Block: |
| 729 |
case Decl::OutlinedFunction: |
| 730 |
case Decl::Captured: |
| 731 |
case Decl::UsingShadow: |
| 732 |
case Decl::ConstructorUsingShadow: |
| 733 |
case Decl::ObjCTypeParam: |
| 734 |
case Decl::Binding: |
| 735 |
case Decl::UnresolvedUsingIfExists: |
| 736 |
case Decl::HLSLBuffer: |
| 737 |
case Decl::HLSLRootSignature: |
| 738 |
llvm_unreachable("Declaration should not be in declstmts!"); |
| 739 |
|
| 740 |
case Decl::Function: // void X(); |
| 741 |
case Decl::EnumConstant: // enum ? { X = ? } |
| 742 |
case Decl::StaticAssert: // static_assert(X, ""); [C++0x] |
| 743 |
case Decl::Label: // __label__ x; |
| 744 |
case Decl::Import: |
| 745 |
case Decl::MSGuid: // __declspec(uuid("...")) |
| 746 |
case Decl::TemplateParamObject: |
| 747 |
case Decl::Empty: |
| 748 |
case Decl::Concept: |
| 749 |
case Decl::LifetimeExtendedTemporary: |
| 750 |
case Decl::RequiresExprBody: |
| 751 |
case Decl::UnnamedGlobalConstant: |
| 752 |
// None of these decls require codegen support. |
| 753 |
return; |
| 754 |
|
| 755 |
case Decl::Enum: // enum X; |
| 756 |
case Decl::Record: // struct/union/class X; |
| 757 |
case Decl::CXXRecord: // struct/union/class X; [C++] |
| 758 |
case Decl::NamespaceAlias: |
| 759 |
case Decl::Using: // using X; [C++] |
| 760 |
case Decl::UsingEnum: // using enum X; [C++] |
| 761 |
case Decl::UsingDirective: // using namespace X; [C++] |
| 762 |
assert(!cir::MissingFeatures::generateDebugInfo()); |
| 763 |
return; |
| 764 |
case Decl::Var: |
| 765 |
case Decl::Decomposition: { |
| 766 |
const VarDecl &vd = cast<VarDecl>(d); |
| 767 |
assert(vd.isLocalVarDecl() && |
| 768 |
"Should not see file-scope variables inside a function!"); |
| 769 |
emitVarDecl(vd); |
| 770 |
if (evaluateConditionDecl) |
| 771 |
maybeEmitDeferredVarDeclInit(&vd); |
| 772 |
return; |
| 773 |
} |
| 774 |
case Decl::OpenACCDeclare: |
| 775 |
emitOpenACCDeclare(cast<OpenACCDeclareDecl>(d)); |
| 776 |
return; |
| 777 |
case Decl::OpenACCRoutine: |
| 778 |
emitOpenACCRoutine(cast<OpenACCRoutineDecl>(d)); |
| 779 |
return; |
| 780 |
case Decl::OMPThreadPrivate: |
| 781 |
emitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(d)); |
| 782 |
return; |
| 783 |
case Decl::OMPGroupPrivate: |
| 784 |
emitOMPGroupPrivateDecl(cast<OMPGroupPrivateDecl>(d)); |
| 785 |
return; |
| 786 |
case Decl::OMPAllocate: |
| 787 |
emitOMPAllocateDecl(cast<OMPAllocateDecl>(d)); |
| 788 |
return; |
| 789 |
case Decl::OMPCapturedExpr: |
| 790 |
emitOMPCapturedExpr(cast<OMPCapturedExprDecl>(d)); |
| 791 |
return; |
| 792 |
case Decl::OMPRequires: |
| 793 |
emitOMPRequiresDecl(cast<OMPRequiresDecl>(d)); |
| 794 |
return; |
| 795 |
case Decl::OMPDeclareMapper: |
| 796 |
emitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(d)); |
| 797 |
return; |
| 798 |
case Decl::OMPDeclareReduction: |
| 799 |
emitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(d)); |
| 800 |
return; |
| 801 |
case Decl::Typedef: // typedef int X; |
| 802 |
case Decl::TypeAlias: { // using X = int; [C++0x] |
| 803 |
QualType ty = cast<TypedefNameDecl>(d).getUnderlyingType(); |
| 804 |
assert(!cir::MissingFeatures::generateDebugInfo()); |
| 805 |
if (ty->isVariablyModifiedType()) |
| 806 |
cgm.errorNYI(d.getSourceRange(), "emitDecl: variably modified type"); |
| 807 |
return; |
| 808 |
} |
| 809 |
case Decl::ImplicitConceptSpecialization: |
| 810 |
case Decl::TopLevelStmt: |
| 811 |
case Decl::UsingPack: |
| 812 |
cgm.errorNYI(d.getSourceRange(), |
| 813 |
std::string("emitDecl: unhandled decl type: ") + |
| 814 |
d.getDeclKindName()); |
| 815 |
} |
| 816 |
} |
| 817 |
|
| 818 |
void CIRGenFunction::emitNullabilityCheck(LValue lhs, mlir::Value rhs, |
| 819 |
SourceLocation loc) { |
| 820 |
if (!sanOpts.has(SanitizerKind::NullabilityAssign)) |
| 821 |
return; |
| 822 |
|
| 823 |
assert(!cir::MissingFeatures::sanitizers()); |
| 824 |
} |
| 825 |
|
| 826 |
namespace { |
| 827 |
struct DestroyObject final : EHScopeStack::Cleanup { |
| 828 |
DestroyObject(Address addr, QualType type, |
| 829 |
CIRGenFunction::Destroyer *destroyer) |
| 830 |
: addr(addr), type(type), destroyer(destroyer) { |
| 831 |
assert(!cir::MissingFeatures::useEHCleanupForArray()); |
| 832 |
} |
| 833 |
|
| 834 |
Address addr; |
| 835 |
QualType type; |
| 836 |
CIRGenFunction::Destroyer *destroyer; |
| 837 |
|
| 838 |
void emit(CIRGenFunction &cgf, Flags flags) override { |
| 839 |
assert(!cir::MissingFeatures::useEHCleanupForArray()); |
| 840 |
cgf.emitDestroy(addr, type, destroyer); |
| 841 |
} |
| 842 |
}; |
| 843 |
|
| 844 |
template <class Derived> struct DestroyNRVOVariable : EHScopeStack::Cleanup { |
| 845 |
DestroyNRVOVariable(Address addr, QualType type, mlir::Value nrvoFlag) |
| 846 |
: nrvoFlag(nrvoFlag), addr(addr), ty(type) {} |
| 847 |
|
| 848 |
mlir::Value nrvoFlag; |
| 849 |
Address addr; |
| 850 |
QualType ty; |
| 851 |
|
| 852 |
void emit(CIRGenFunction &cgf, Flags flags) override { |
| 853 |
// Along the exceptions path we always execute the dtor. |
| 854 |
bool nrvo = flags.isForNormalCleanup() && nrvoFlag; |
| 855 |
|
| 856 |
CIRGenBuilderTy &builder = cgf.getBuilder(); |
| 857 |
mlir::OpBuilder::InsertionGuard guard(builder); |
| 858 |
if (nrvo) { |
| 859 |
// If we exited via NRVO, we skip the destructor call. |
| 860 |
mlir::Location loc = addr.getPointer().getLoc(); |
| 861 |
mlir::Value didNRVO = builder.createFlagLoad(loc, nrvoFlag); |
| 862 |
mlir::Value notNRVO = builder.createNot(didNRVO); |
| 863 |
cir::IfOp::create(builder, loc, notNRVO, /*withElseRegion=*/false, |
| 864 |
[&](mlir::OpBuilder &b, mlir::Location) { |
| 865 |
static_cast<Derived *>(this)->emitDestructorCall(cgf); |
| 866 |
builder.createYield(loc); |
| 867 |
}); |
| 868 |
} else { |
| 869 |
static_cast<Derived *>(this)->emitDestructorCall(cgf); |
| 870 |
} |
| 871 |
} |
| 872 |
|
| 873 |
virtual ~DestroyNRVOVariable() = default; |
| 874 |
}; |
| 875 |
|
| 876 |
struct DestroyNRVOVariableCXX final |
| 877 |
: DestroyNRVOVariable<DestroyNRVOVariableCXX> { |
| 878 |
DestroyNRVOVariableCXX(Address addr, QualType type, |
| 879 |
const CXXDestructorDecl *dtor, mlir::Value nrvoFlag) |
| 880 |
: DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, nrvoFlag), |
| 881 |
dtor(dtor) {} |
| 882 |
|
| 883 |
const CXXDestructorDecl *dtor; |
| 884 |
|
| 885 |
void emitDestructorCall(CIRGenFunction &cgf) { |
| 886 |
cgf.emitCXXDestructorCall(dtor, Dtor_Complete, |
| 887 |
/*forVirtualBase=*/false, |
| 888 |
/*delegating=*/false, addr, ty); |
| 889 |
} |
| 890 |
}; |
| 891 |
|
| 892 |
struct CallStackRestore final : EHScopeStack::Cleanup { |
| 893 |
Address stack; |
| 894 |
CallStackRestore(Address stack) : stack(stack) {} |
| 895 |
void emit(CIRGenFunction &cgf, Flags flags) override { |
| 896 |
mlir::Location loc = stack.getPointer().getLoc(); |
| 897 |
mlir::Value v = cgf.getBuilder().createLoad(loc, stack); |
| 898 |
cgf.getBuilder().createStackRestore(loc, v); |
| 899 |
} |
| 900 |
}; |
| 901 |
} // namespace |
| 902 |
|
| 903 |
/// Push the standard destructor for the given type as |
| 904 |
/// at least a normal cleanup. |
| 905 |
void CIRGenFunction::pushDestroy(QualType::DestructionKind dtorKind, |
| 906 |
Address addr, QualType type) { |
| 907 |
assert(dtorKind && "cannot push destructor for trivial type"); |
| 908 |
|
| 909 |
CleanupKind cleanupKind = getCleanupKind(dtorKind); |
| 910 |
pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind)); |
| 911 |
} |
| 912 |
|
| 913 |
void CIRGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr, |
| 914 |
QualType type, Destroyer *destroyer) { |
| 915 |
pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, destroyer); |
| 916 |
} |
| 917 |
|
| 918 |
/// Destroys all the elements of the given array, beginning from last to first. |
| 919 |
/// The array cannot be zero-length. |
| 920 |
/// |
| 921 |
/// \param begin - a type* denoting the first element of the array |
| 922 |
/// \param numElements - the number of elements in the array |
| 923 |
/// \param elementType - the element type of the array |
| 924 |
/// \param destroyer - the function to call to destroy elements |
| 925 |
void CIRGenFunction::emitArrayDestroy(mlir::Value begin, |
| 926 |
mlir::Value numElements, |
| 927 |
QualType elementType, |
| 928 |
CharUnits elementAlign, |
| 929 |
Destroyer *destroyer) { |
| 930 |
assert(!elementType->isArrayType()); |
| 931 |
|
| 932 |
// Differently from LLVM traditional codegen, use a higher level |
| 933 |
// representation instead of lowering directly to a loop. |
| 934 |
mlir::Type cirElementType = convertTypeForMem(elementType); |
| 935 |
cir::PointerType ptrToElmType = builder.getPointerTo(cirElementType); |
| 936 |
|
| 937 |
uint64_t size = 0; |
| 938 |
|
| 939 |
// Optimize for a constant array size. |
| 940 |
if (auto constantCount = numElements.getDefiningOp<cir::ConstantOp>()) { |
| 941 |
if (auto constIntAttr = constantCount.getValueAttr<cir::IntAttr>()) |
| 942 |
size = constIntAttr.getUInt(); |
| 943 |
} else { |
| 944 |
cgm.errorNYI(begin.getDefiningOp()->getLoc(), |
| 945 |
"dynamic-length array expression"); |
| 946 |
} |
| 947 |
|
| 948 |
auto arrayTy = cir::ArrayType::get(cirElementType, size); |
| 949 |
mlir::Value arrayOp = builder.createPtrBitcast(begin, arrayTy); |
| 950 |
|
| 951 |
// Emit the dtor call that will execute for every array element. |
| 952 |
cir::ArrayDtor::create( |
| 953 |
builder, *currSrcLoc, arrayOp, |
| 954 |
[&](mlir::OpBuilder &b, mlir::Location loc) { |
| 955 |
auto arg = b.getInsertionBlock()->addArgument(ptrToElmType, loc); |
| 956 |
Address curAddr = Address(arg, cirElementType, elementAlign); |
| 957 |
assert(!cir::MissingFeatures::dtorCleanups()); |
| 958 |
|
| 959 |
// Perform the actual destruction there. |
| 960 |
destroyer(*this, curAddr, elementType); |
| 961 |
|
| 962 |
cir::YieldOp::create(builder, loc); |
| 963 |
}); |
| 964 |
} |
| 965 |
|
| 966 |
/// Immediately perform the destruction of the given object. |
| 967 |
/// |
| 968 |
/// \param addr - the address of the object; a type* |
| 969 |
/// \param type - the type of the object; if an array type, all |
| 970 |
/// objects are destroyed in reverse order |
| 971 |
/// \param destroyer - the function to call to destroy individual |
| 972 |
/// elements |
| 973 |
void CIRGenFunction::emitDestroy(Address addr, QualType type, |
| 974 |
Destroyer *destroyer) { |
| 975 |
const ArrayType *arrayType = getContext().getAsArrayType(type); |
| 976 |
if (!arrayType) |
| 977 |
return destroyer(*this, addr, type); |
| 978 |
|
| 979 |
mlir::Value length = emitArrayLength(arrayType, type, addr); |
| 980 |
|
| 981 |
CharUnits elementAlign = addr.getAlignment().alignmentOfArrayElement( |
| 982 |
getContext().getTypeSizeInChars(type)); |
| 983 |
|
| 984 |
auto constantCount = length.getDefiningOp<cir::ConstantOp>(); |
| 985 |
if (!constantCount) { |
| 986 |
assert(!cir::MissingFeatures::vlas()); |
| 987 |
cgm.errorNYI("emitDestroy: variable length array"); |
| 988 |
return; |
| 989 |
} |
| 990 |
|
| 991 |
auto constIntAttr = mlir::dyn_cast<cir::IntAttr>(constantCount.getValue()); |
| 992 |
// If it's constant zero, we can just skip the entire thing. |
| 993 |
if (constIntAttr && constIntAttr.getUInt() == 0) |
| 994 |
return; |
| 995 |
|
| 996 |
mlir::Value begin = addr.getPointer(); |
| 997 |
assert(!cir::MissingFeatures::useEHCleanupForArray()); |
| 998 |
emitArrayDestroy(begin, length, type, elementAlign, destroyer); |
| 999 |
|
| 1000 |
// If the array destroy didn't use the length op, we can erase it. |
| 1001 |
if (constantCount.use_empty()) |
| 1002 |
constantCount.erase(); |
| 1003 |
} |
| 1004 |
|
| 1005 |
CIRGenFunction::Destroyer * |
| 1006 |
CIRGenFunction::getDestroyer(QualType::DestructionKind kind) { |
| 1007 |
switch (kind) { |
| 1008 |
case QualType::DK_none: |
| 1009 |
llvm_unreachable("no destroyer for trivial dtor"); |
| 1010 |
case QualType::DK_cxx_destructor: |
| 1011 |
return destroyCXXObject; |
| 1012 |
case QualType::DK_objc_strong_lifetime: |
| 1013 |
case QualType::DK_objc_weak_lifetime: |
| 1014 |
case QualType::DK_nontrivial_c_struct: |
| 1015 |
cgm.errorNYI("getDestroyer: other destruction kind"); |
| 1016 |
return nullptr; |
| 1017 |
} |
| 1018 |
llvm_unreachable("Unknown DestructionKind"); |
| 1019 |
} |
| 1020 |
|
| 1021 |
void CIRGenFunction::pushStackRestore(CleanupKind kind, Address spMem) { |
| 1022 |
ehStack.pushCleanup<CallStackRestore>(kind, spMem); |
| 1023 |
} |
| 1024 |
|
| 1025 |
/// Enter a destroy cleanup for the given local variable. |
| 1026 |
void CIRGenFunction::emitAutoVarTypeCleanup( |
| 1027 |
const CIRGenFunction::AutoVarEmission &emission, |
| 1028 |
QualType::DestructionKind dtorKind) { |
| 1029 |
assert(dtorKind != QualType::DK_none); |
| 1030 |
|
| 1031 |
// Note that for __block variables, we want to destroy the |
| 1032 |
// original stack object, not the possibly forwarded object. |
| 1033 |
Address addr = emission.getObjectAddress(*this); |
| 1034 |
|
| 1035 |
const VarDecl *var = emission.variable; |
| 1036 |
QualType type = var->getType(); |
| 1037 |
|
| 1038 |
CleanupKind cleanupKind = NormalAndEHCleanup; |
| 1039 |
CIRGenFunction::Destroyer *destroyer = nullptr; |
| 1040 |
|
| 1041 |
switch (dtorKind) { |
| 1042 |
case QualType::DK_none: |
| 1043 |
llvm_unreachable("no cleanup for trivially-destructible variable"); |
| 1044 |
|
| 1045 |
case QualType::DK_cxx_destructor: |
| 1046 |
// If there's an NRVO flag on the emission, we need a different |
| 1047 |
// cleanup. |
| 1048 |
if (emission.nrvoFlag) { |
| 1049 |
assert(!type->isArrayType()); |
| 1050 |
CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor(); |
| 1051 |
ehStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor, |
| 1052 |
emission.nrvoFlag); |
| 1053 |
return; |
| 1054 |
} |
| 1055 |
// Otherwise, this is handled below. |
| 1056 |
break; |
| 1057 |
|
| 1058 |
case QualType::DK_objc_strong_lifetime: |
| 1059 |
case QualType::DK_objc_weak_lifetime: |
| 1060 |
case QualType::DK_nontrivial_c_struct: |
| 1061 |
cgm.errorNYI(var->getSourceRange(), |
| 1062 |
"emitAutoVarTypeCleanup: other dtor kind"); |
| 1063 |
return; |
| 1064 |
} |
| 1065 |
|
| 1066 |
// If we haven't chosen a more specific destroyer, use the default. |
| 1067 |
if (!destroyer) |
| 1068 |
destroyer = getDestroyer(dtorKind); |
| 1069 |
|
| 1070 |
assert(!cir::MissingFeatures::useEHCleanupForArray()); |
| 1071 |
ehStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer); |
| 1072 |
} |
| 1073 |
|
| 1074 |
void CIRGenFunction::maybeEmitDeferredVarDeclInit(const VarDecl *vd) { |
| 1075 |
if (auto *dd = dyn_cast_if_present<DecompositionDecl>(vd)) { |
| 1076 |
for (auto *b : dd->flat_bindings()) |
| 1077 |
if (auto *hd = b->getHoldingVar()) |
| 1078 |
emitVarDecl(*hd); |
| 1079 |
} |
| 1080 |
} |