clang 19.0.0git
CGDecl.cpp
Go to the documentation of this file.
1//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
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 LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGBlocks.h"
14#include "CGCXXABI.h"
15#include "CGCleanup.h"
16#include "CGDebugInfo.h"
17#include "CGOpenCLRuntime.h"
18#include "CGOpenMPRuntime.h"
19#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
21#include "ConstantEmitter.h"
22#include "PatternInit.h"
23#include "TargetInfo.h"
25#include "clang/AST/Attr.h"
26#include "clang/AST/CharUnits.h"
27#include "clang/AST/Decl.h"
28#include "clang/AST/DeclObjC.h"
34#include "clang/Sema/Sema.h"
35#include "llvm/Analysis/ValueTracking.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/Type.h"
40#include <optional>
41
42using namespace clang;
43using namespace CodeGen;
44
45static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
46 "Clang max alignment greater than what LLVM supports?");
47
48void CodeGenFunction::EmitDecl(const Decl &D) {
49 switch (D.getKind()) {
50 case Decl::BuiltinTemplate:
51 case Decl::TranslationUnit:
52 case Decl::ExternCContext:
53 case Decl::Namespace:
54 case Decl::UnresolvedUsingTypename:
55 case Decl::ClassTemplateSpecialization:
56 case Decl::ClassTemplatePartialSpecialization:
57 case Decl::VarTemplateSpecialization:
58 case Decl::VarTemplatePartialSpecialization:
59 case Decl::TemplateTypeParm:
60 case Decl::UnresolvedUsingValue:
61 case Decl::NonTypeTemplateParm:
62 case Decl::CXXDeductionGuide:
63 case Decl::CXXMethod:
64 case Decl::CXXConstructor:
65 case Decl::CXXDestructor:
66 case Decl::CXXConversion:
67 case Decl::Field:
68 case Decl::MSProperty:
69 case Decl::IndirectField:
70 case Decl::ObjCIvar:
71 case Decl::ObjCAtDefsField:
72 case Decl::ParmVar:
73 case Decl::ImplicitParam:
74 case Decl::ClassTemplate:
75 case Decl::VarTemplate:
76 case Decl::FunctionTemplate:
77 case Decl::TypeAliasTemplate:
78 case Decl::TemplateTemplateParm:
79 case Decl::ObjCMethod:
80 case Decl::ObjCCategory:
81 case Decl::ObjCProtocol:
82 case Decl::ObjCInterface:
83 case Decl::ObjCCategoryImpl:
84 case Decl::ObjCImplementation:
85 case Decl::ObjCProperty:
86 case Decl::ObjCCompatibleAlias:
87 case Decl::PragmaComment:
88 case Decl::PragmaDetectMismatch:
89 case Decl::AccessSpec:
90 case Decl::LinkageSpec:
91 case Decl::Export:
92 case Decl::ObjCPropertyImpl:
93 case Decl::FileScopeAsm:
94 case Decl::TopLevelStmt:
95 case Decl::Friend:
96 case Decl::FriendTemplate:
97 case Decl::Block:
98 case Decl::Captured:
99 case Decl::UsingShadow:
100 case Decl::ConstructorUsingShadow:
101 case Decl::ObjCTypeParam:
102 case Decl::Binding:
103 case Decl::UnresolvedUsingIfExists:
104 case Decl::HLSLBuffer:
105 llvm_unreachable("Declaration should not be in declstmts!");
106 case Decl::Record: // struct/union/class X;
107 case Decl::CXXRecord: // struct/union/class X; [C++]
108 if (CGDebugInfo *DI = getDebugInfo())
109 if (cast<RecordDecl>(D).getDefinition())
110 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
111 return;
112 case Decl::Enum: // enum X;
113 if (CGDebugInfo *DI = getDebugInfo())
114 if (cast<EnumDecl>(D).getDefinition())
115 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
116 return;
117 case Decl::Function: // void X();
118 case Decl::EnumConstant: // enum ? { X = ? }
119 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
120 case Decl::Label: // __label__ x;
121 case Decl::Import:
122 case Decl::MSGuid: // __declspec(uuid("..."))
123 case Decl::UnnamedGlobalConstant:
124 case Decl::TemplateParamObject:
125 case Decl::OMPThreadPrivate:
126 case Decl::OMPAllocate:
127 case Decl::OMPCapturedExpr:
128 case Decl::OMPRequires:
129 case Decl::Empty:
130 case Decl::Concept:
131 case Decl::ImplicitConceptSpecialization:
132 case Decl::LifetimeExtendedTemporary:
133 case Decl::RequiresExprBody:
134 // None of these decls require codegen support.
135 return;
136
137 case Decl::NamespaceAlias:
138 if (CGDebugInfo *DI = getDebugInfo())
139 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
140 return;
141 case Decl::Using: // using X; [C++]
142 if (CGDebugInfo *DI = getDebugInfo())
143 DI->EmitUsingDecl(cast<UsingDecl>(D));
144 return;
145 case Decl::UsingEnum: // using enum X; [C++]
146 if (CGDebugInfo *DI = getDebugInfo())
147 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
148 return;
149 case Decl::UsingPack:
150 for (auto *Using : cast<UsingPackDecl>(D).expansions())
151 EmitDecl(*Using);
152 return;
153 case Decl::UsingDirective: // using namespace X; [C++]
154 if (CGDebugInfo *DI = getDebugInfo())
155 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
156 return;
157 case Decl::Var:
158 case Decl::Decomposition: {
159 const VarDecl &VD = cast<VarDecl>(D);
160 assert(VD.isLocalVarDecl() &&
161 "Should not see file-scope variables inside a function!");
162 EmitVarDecl(VD);
163 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
164 for (auto *B : DD->bindings())
165 if (auto *HD = B->getHoldingVar())
166 EmitVarDecl(*HD);
167 return;
168 }
169
170 case Decl::OMPDeclareReduction:
171 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
172
173 case Decl::OMPDeclareMapper:
174 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
175
176 case Decl::Typedef: // typedef int X;
177 case Decl::TypeAlias: { // using X = int; [C++0x]
178 QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
179 if (CGDebugInfo *DI = getDebugInfo())
180 DI->EmitAndRetainType(Ty);
181 if (Ty->isVariablyModifiedType())
183 return;
184 }
185 }
186}
187
188/// EmitVarDecl - This method handles emission of any variable declaration
189/// inside a function, including static vars etc.
191 if (D.hasExternalStorage())
192 // Don't emit it now, allow it to be emitted lazily on its first use.
193 return;
194
195 // Some function-scope variable does not have static storage but still
196 // needs to be emitted like a static variable, e.g. a function-scope
197 // variable in constant address space in OpenCL.
198 if (D.getStorageDuration() != SD_Automatic) {
199 // Static sampler variables translated to function calls.
200 if (D.getType()->isSamplerT())
201 return;
202
203 llvm::GlobalValue::LinkageTypes Linkage =
205
206 // FIXME: We need to force the emission/use of a guard variable for
207 // some variables even if we can constant-evaluate them because
208 // we can't guarantee every translation unit will constant-evaluate them.
209
210 return EmitStaticVarDecl(D, Linkage);
211 }
212
215
216 assert(D.hasLocalStorage());
217 return EmitAutoVarDecl(D);
218}
219
220static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
221 if (CGM.getLangOpts().CPlusPlus)
222 return CGM.getMangledName(&D).str();
223
224 // If this isn't C++, we don't need a mangled name, just a pretty one.
225 assert(!D.isExternallyVisible() && "name shouldn't matter");
226 std::string ContextName;
227 const DeclContext *DC = D.getDeclContext();
228 if (auto *CD = dyn_cast<CapturedDecl>(DC))
229 DC = cast<DeclContext>(CD->getNonClosureContext());
230 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
231 ContextName = std::string(CGM.getMangledName(FD));
232 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
233 ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
234 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
235 ContextName = OMD->getSelector().getAsString();
236 else
237 llvm_unreachable("Unknown context for static var decl");
238
239 ContextName += "." + D.getNameAsString();
240 return ContextName;
241}
242
244 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
245 // In general, we don't always emit static var decls once before we reference
246 // them. It is possible to reference them before emitting the function that
247 // contains them, and it is possible to emit the containing function multiple
248 // times.
249 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
250 return ExistingGV;
251
252 QualType Ty = D.getType();
253 assert(Ty->isConstantSizeType() && "VLAs can't be static");
254
255 // Use the label if the variable is renamed with the asm-label extension.
256 std::string Name;
257 if (D.hasAttr<AsmLabelAttr>())
258 Name = std::string(getMangledName(&D));
259 else
260 Name = getStaticDeclName(*this, D);
261
262 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
264 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
265
266 // OpenCL variables in local address space and CUDA shared
267 // variables cannot have an initializer.
268 llvm::Constant *Init = nullptr;
270 D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
271 Init = llvm::UndefValue::get(LTy);
272 else
274
275 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
276 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
277 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
278 GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
279
280 if (supportsCOMDAT() && GV->isWeakForLinker())
281 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
282
283 if (D.getTLSKind())
284 setTLSMode(GV, D);
285
286 setGVProperties(GV, &D);
287 getTargetCodeGenInfo().setTargetAttributes(cast<Decl>(&D), GV, *this);
288
289 // Make sure the result is of the correct type.
290 LangAS ExpectedAS = Ty.getAddressSpace();
291 llvm::Constant *Addr = GV;
292 if (AS != ExpectedAS) {
294 *this, GV, AS, ExpectedAS,
295 llvm::PointerType::get(getLLVMContext(),
296 getContext().getTargetAddressSpace(ExpectedAS)));
297 }
298
300
301 // Ensure that the static local gets initialized by making sure the parent
302 // function gets emitted eventually.
303 const Decl *DC = cast<Decl>(D.getDeclContext());
304
305 // We can't name blocks or captured statements directly, so try to emit their
306 // parents.
307 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
308 DC = DC->getNonClosureContext();
309 // FIXME: Ensure that global blocks get emitted.
310 if (!DC)
311 return Addr;
312 }
313
314 GlobalDecl GD;
315 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
316 GD = GlobalDecl(CD, Ctor_Base);
317 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
318 GD = GlobalDecl(DD, Dtor_Base);
319 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
320 GD = GlobalDecl(FD);
321 else {
322 // Don't do anything for Obj-C method decls or global closures. We should
323 // never defer them.
324 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
325 }
326 if (GD.getDecl()) {
327 // Disable emission of the parent function for the OpenMP device codegen.
329 (void)GetAddrOfGlobal(GD);
330 }
331
332 return Addr;
333}
334
335/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
336/// global variable that has already been created for it. If the initializer
337/// has a different type than GV does, this may free GV and return a different
338/// one. Otherwise it just returns GV.
339llvm::GlobalVariable *
341 llvm::GlobalVariable *GV) {
342 ConstantEmitter emitter(*this);
343 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
344
345 // If constant emission failed, then this should be a C++ static
346 // initializer.
347 if (!Init) {
348 if (!getLangOpts().CPlusPlus)
349 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
350 else if (D.hasFlexibleArrayInit(getContext()))
351 CGM.ErrorUnsupported(D.getInit(), "flexible array initializer");
352 else if (HaveInsertPoint()) {
353 // Since we have a static initializer, this global variable can't
354 // be constant.
355 GV->setConstant(false);
356
357 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
358 }
359 return GV;
360 }
361
362#ifndef NDEBUG
366 CGM.getDataLayout().getTypeAllocSize(Init->getType()));
367 assert(VarSize == CstSize && "Emitted constant has unexpected size");
368#endif
369
370 // The initializer may differ in type from the global. Rewrite
371 // the global to match the initializer. (We have to do this
372 // because some types, like unions, can't be completely represented
373 // in the LLVM type system.)
374 if (GV->getValueType() != Init->getType()) {
375 llvm::GlobalVariable *OldGV = GV;
376
377 GV = new llvm::GlobalVariable(
378 CGM.getModule(), Init->getType(), OldGV->isConstant(),
379 OldGV->getLinkage(), Init, "",
380 /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
381 OldGV->getType()->getPointerAddressSpace());
382 GV->setVisibility(OldGV->getVisibility());
383 GV->setDSOLocal(OldGV->isDSOLocal());
384 GV->setComdat(OldGV->getComdat());
385
386 // Steal the name of the old global
387 GV->takeName(OldGV);
388
389 // Replace all uses of the old global with the new global
390 OldGV->replaceAllUsesWith(GV);
391
392 // Erase the old global, since it is no longer used.
393 OldGV->eraseFromParent();
394 }
395
396 bool NeedsDtor =
398
399 GV->setConstant(
400 D.getType().isConstantStorage(getContext(), true, !NeedsDtor));
401 GV->setInitializer(Init);
402
403 emitter.finalize(GV);
404
405 if (NeedsDtor && HaveInsertPoint()) {
406 // We have a constant initializer, but a nontrivial destructor. We still
407 // need to perform a guarded "initialization" in order to register the
408 // destructor.
409 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
410 }
411
412 return GV;
413}
414
416 llvm::GlobalValue::LinkageTypes Linkage) {
417 // Check to see if we already have a global variable for this
418 // declaration. This can happen when double-emitting function
419 // bodies, e.g. with complete and base constructors.
420 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
421 CharUnits alignment = getContext().getDeclAlign(&D);
422
423 // Store into LocalDeclMap before generating initializer to handle
424 // circular references.
425 llvm::Type *elemTy = ConvertTypeForMem(D.getType());
426 setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
427
428 // We can't have a VLA here, but we can have a pointer to a VLA,
429 // even though that doesn't really make any sense.
430 // Make sure to evaluate VLA bounds now so that we have them for later.
433
434 // Save the type in case adding the initializer forces a type change.
435 llvm::Type *expectedType = addr->getType();
436
437 llvm::GlobalVariable *var =
438 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
439
440 // CUDA's local and local static __shared__ variables should not
441 // have any non-empty initializers. This is ensured by Sema.
442 // Whatever initializer such variable may have when it gets here is
443 // a no-op and should not be emitted.
444 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
445 D.hasAttr<CUDASharedAttr>();
446 // If this value has an initializer, emit it.
447 if (D.getInit() && !isCudaSharedVar)
448 var = AddInitializerToStaticVarDecl(D, var);
449
450 var->setAlignment(alignment.getAsAlign());
451
452 if (D.hasAttr<AnnotateAttr>())
453 CGM.AddGlobalAnnotations(&D, var);
454
455 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
456 var->addAttribute("bss-section", SA->getName());
457 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
458 var->addAttribute("data-section", SA->getName());
459 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
460 var->addAttribute("rodata-section", SA->getName());
461 if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
462 var->addAttribute("relro-section", SA->getName());
463
464 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
465 var->setSection(SA->getName());
466
467 if (D.hasAttr<RetainAttr>())
468 CGM.addUsedGlobal(var);
469 else if (D.hasAttr<UsedAttr>())
471
472 if (CGM.getCodeGenOpts().KeepPersistentStorageVariables)
474
475 // We may have to cast the constant because of the initializer
476 // mismatch above.
477 //
478 // FIXME: It is really dangerous to store this in the map; if anyone
479 // RAUW's the GV uses of this constant will be invalid.
480 llvm::Constant *castedAddr =
481 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
482 LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
483 CGM.setStaticLocalDeclAddress(&D, castedAddr);
484
486
487 // Emit global variable debug descriptor for static vars.
489 if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
490 DI->setLocation(D.getLocation());
491 DI->EmitGlobalVariable(var, &D);
492 }
493}
494
495namespace {
496 struct DestroyObject final : EHScopeStack::Cleanup {
497 DestroyObject(Address addr, QualType type,
498 CodeGenFunction::Destroyer *destroyer,
499 bool useEHCleanupForArray)
500 : addr(addr), type(type), destroyer(destroyer),
501 useEHCleanupForArray(useEHCleanupForArray) {}
502
503 Address addr;
505 CodeGenFunction::Destroyer *destroyer;
506 bool useEHCleanupForArray;
507
508 void Emit(CodeGenFunction &CGF, Flags flags) override {
509 // Don't use an EH cleanup recursively from an EH cleanup.
510 bool useEHCleanupForArray =
511 flags.isForNormalCleanup() && this->useEHCleanupForArray;
512
513 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
514 }
515 };
516
517 template <class Derived>
518 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
519 DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
520 : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
521
522 llvm::Value *NRVOFlag;
523 Address Loc;
524 QualType Ty;
525
526 void Emit(CodeGenFunction &CGF, Flags flags) override {
527 // Along the exceptions path we always execute the dtor.
528 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
529
530 llvm::BasicBlock *SkipDtorBB = nullptr;
531 if (NRVO) {
532 // If we exited via NRVO, we skip the destructor call.
533 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
534 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
535 llvm::Value *DidNRVO =
536 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
537 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
538 CGF.EmitBlock(RunDtorBB);
539 }
540
541 static_cast<Derived *>(this)->emitDestructorCall(CGF);
542
543 if (NRVO) CGF.EmitBlock(SkipDtorBB);
544 }
545
546 virtual ~DestroyNRVOVariable() = default;
547 };
548
549 struct DestroyNRVOVariableCXX final
550 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
551 DestroyNRVOVariableCXX(Address addr, QualType type,
552 const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
553 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
554 Dtor(Dtor) {}
555
556 const CXXDestructorDecl *Dtor;
557
558 void emitDestructorCall(CodeGenFunction &CGF) {
560 /*ForVirtualBase=*/false,
561 /*Delegating=*/false, Loc, Ty);
562 }
563 };
564
565 struct DestroyNRVOVariableC final
566 : DestroyNRVOVariable<DestroyNRVOVariableC> {
567 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
568 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
569
570 void emitDestructorCall(CodeGenFunction &CGF) {
571 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
572 }
573 };
574
575 struct CallStackRestore final : EHScopeStack::Cleanup {
576 Address Stack;
577 CallStackRestore(Address Stack) : Stack(Stack) {}
578 bool isRedundantBeforeReturn() override { return true; }
579 void Emit(CodeGenFunction &CGF, Flags flags) override {
580 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
581 CGF.Builder.CreateStackRestore(V);
582 }
583 };
584
585 struct KmpcAllocFree final : EHScopeStack::Cleanup {
586 std::pair<llvm::Value *, llvm::Value *> AddrSizePair;
587 KmpcAllocFree(const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair)
588 : AddrSizePair(AddrSizePair) {}
589 void Emit(CodeGenFunction &CGF, Flags EmissionFlags) override {
590 auto &RT = CGF.CGM.getOpenMPRuntime();
591 RT.getKmpcFreeShared(CGF, AddrSizePair);
592 }
593 };
594
595 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
596 const VarDecl &Var;
597 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
598
599 void Emit(CodeGenFunction &CGF, Flags flags) override {
600 // Compute the address of the local variable, in case it's a
601 // byref or something.
602 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
604 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
606 CGF.EmitExtendGCLifetime(value);
607 }
608 };
609
610 struct CallCleanupFunction final : EHScopeStack::Cleanup {
611 llvm::Constant *CleanupFn;
612 const CGFunctionInfo &FnInfo;
613 const VarDecl &Var;
614
615 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
616 const VarDecl *Var)
617 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
618
619 void Emit(CodeGenFunction &CGF, Flags flags) override {
620 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
622 // Compute the address of the local variable, in case it's a byref
623 // or something.
624 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
625
626 // In some cases, the type of the function argument will be different from
627 // the type of the pointer. An example of this is
628 // void f(void* arg);
629 // __attribute__((cleanup(f))) void *g;
630 //
631 // To fix this we insert a bitcast here.
632 QualType ArgTy = FnInfo.arg_begin()->type;
633 llvm::Value *Arg =
634 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
635
636 CallArgList Args;
637 Args.add(RValue::get(Arg),
638 CGF.getContext().getPointerType(Var.getType()));
639 auto Callee = CGCallee::forDirect(CleanupFn);
640 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
641 }
642 };
643} // end anonymous namespace
644
645/// EmitAutoVarWithLifetime - Does the setup required for an automatic
646/// variable with lifetime.
648 Address addr,
649 Qualifiers::ObjCLifetime lifetime) {
650 switch (lifetime) {
652 llvm_unreachable("present but none");
653
655 // nothing to do
656 break;
657
659 CodeGenFunction::Destroyer *destroyer =
660 (var.hasAttr<ObjCPreciseLifetimeAttr>()
663
664 CleanupKind cleanupKind = CGF.getARCCleanupKind();
665 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
666 cleanupKind & EHCleanup);
667 break;
668 }
670 // nothing to do
671 break;
672
674 // __weak objects always get EH cleanups; otherwise, exceptions
675 // could cause really nasty crashes instead of mere leaks.
676 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
678 /*useEHCleanup*/ true);
679 break;
680 }
681}
682
683static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
684 if (const Expr *e = dyn_cast<Expr>(s)) {
685 // Skip the most common kinds of expressions that make
686 // hierarchy-walking expensive.
687 s = e = e->IgnoreParenCasts();
688
689 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
690 return (ref->getDecl() == &var);
691 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
692 const BlockDecl *block = be->getBlockDecl();
693 for (const auto &I : block->captures()) {
694 if (I.getVariable() == &var)
695 return true;
696 }
697 }
698 }
699
700 for (const Stmt *SubStmt : s->children())
701 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
702 if (SubStmt && isAccessedBy(var, SubStmt))
703 return true;
704
705 return false;
706}
707
708static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
709 if (!decl) return false;
710 if (!isa<VarDecl>(decl)) return false;
711 const VarDecl *var = cast<VarDecl>(decl);
712 return isAccessedBy(*var, e);
713}
714
716 const LValue &destLV, const Expr *init) {
717 bool needsCast = false;
718
719 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
720 switch (castExpr->getCastKind()) {
721 // Look through casts that don't require representation changes.
722 case CK_NoOp:
723 case CK_BitCast:
724 case CK_BlockPointerToObjCPointerCast:
725 needsCast = true;
726 break;
727
728 // If we find an l-value to r-value cast from a __weak variable,
729 // emit this operation as a copy or move.
730 case CK_LValueToRValue: {
731 const Expr *srcExpr = castExpr->getSubExpr();
732 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
733 return false;
734
735 // Emit the source l-value.
736 LValue srcLV = CGF.EmitLValue(srcExpr);
737
738 // Handle a formal type change to avoid asserting.
739 auto srcAddr = srcLV.getAddress(CGF);
740 if (needsCast) {
741 srcAddr =
742 srcAddr.withElementType(destLV.getAddress(CGF).getElementType());
743 }
744
745 // If it was an l-value, use objc_copyWeak.
746 if (srcExpr->isLValue()) {
747 CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
748 } else {
749 assert(srcExpr->isXValue());
750 CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
751 }
752 return true;
753 }
754
755 // Stop at anything else.
756 default:
757 return false;
758 }
759
760 init = castExpr->getSubExpr();
761 }
762 return false;
763}
764
766 LValue &lvalue,
767 const VarDecl *var) {
768 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
769}
770
771void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
772 SourceLocation Loc) {
773 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
774 return;
775
776 auto Nullability = LHS.getType()->getNullability();
777 if (!Nullability || *Nullability != NullabilityKind::NonNull)
778 return;
779
780 // Check if the right hand side of the assignment is nonnull, if the left
781 // hand side must be nonnull.
782 SanitizerScope SanScope(this);
783 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
784 llvm::Constant *StaticData[] = {
786 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
787 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
788 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
789 SanitizerHandler::TypeMismatch, StaticData, RHS);
790}
791
792void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
793 LValue lvalue, bool capturedByInit) {
794 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
795 if (!lifetime) {
796 llvm::Value *value = EmitScalarExpr(init);
797 if (capturedByInit)
798 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
799 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
800 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
801 return;
802 }
803
804 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
805 init = DIE->getExpr();
806
807 // If we're emitting a value with lifetime, we have to do the
808 // initialization *before* we leave the cleanup scopes.
809 if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
810 CodeGenFunction::RunCleanupsScope Scope(*this);
811 return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
812 }
813
814 // We have to maintain the illusion that the variable is
815 // zero-initialized. If the variable might be accessed in its
816 // initializer, zero-initialize before running the initializer, then
817 // actually perform the initialization with an assign.
818 bool accessedByInit = false;
819 if (lifetime != Qualifiers::OCL_ExplicitNone)
820 accessedByInit = (capturedByInit || isAccessedBy(D, init));
821 if (accessedByInit) {
822 LValue tempLV = lvalue;
823 // Drill down to the __block object if necessary.
824 if (capturedByInit) {
825 // We can use a simple GEP for this because it can't have been
826 // moved yet.
827 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
828 cast<VarDecl>(D),
829 /*follow*/ false));
830 }
831
832 auto ty =
833 cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
834 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
835
836 // If __weak, we want to use a barrier under certain conditions.
837 if (lifetime == Qualifiers::OCL_Weak)
838 EmitARCInitWeak(tempLV.getAddress(*this), zero);
839
840 // Otherwise just do a simple store.
841 else
842 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
843 }
844
845 // Emit the initializer.
846 llvm::Value *value = nullptr;
847
848 switch (lifetime) {
850 llvm_unreachable("present but none");
851
853 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
854 value = EmitARCRetainScalarExpr(init);
855 break;
856 }
857 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
858 // that we omit the retain, and causes non-autoreleased return values to be
859 // immediately released.
860 [[fallthrough]];
861 }
862
865 break;
866
868 // If it's not accessed by the initializer, try to emit the
869 // initialization with a copy or move.
870 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
871 return;
872 }
873
874 // No way to optimize a producing initializer into this. It's not
875 // worth optimizing for, because the value will immediately
876 // disappear in the common case.
877 value = EmitScalarExpr(init);
878
879 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
880 if (accessedByInit)
881 EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
882 else
883 EmitARCInitWeak(lvalue.getAddress(*this), value);
884 return;
885 }
886
889 break;
890 }
891
892 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
893
894 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
895
896 // If the variable might have been accessed by its initializer, we
897 // might have to initialize with a barrier. We have to do this for
898 // both __weak and __strong, but __weak got filtered out above.
899 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
900 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
901 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
903 return;
904 }
905
906 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
907}
908
909/// Decide whether we can emit the non-zero parts of the specified initializer
910/// with equal or fewer than NumStores scalar stores.
911static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
912 unsigned &NumStores) {
913 // Zero and Undef never requires any extra stores.
914 if (isa<llvm::ConstantAggregateZero>(Init) ||
915 isa<llvm::ConstantPointerNull>(Init) ||
916 isa<llvm::UndefValue>(Init))
917 return true;
918 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
919 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
920 isa<llvm::ConstantExpr>(Init))
921 return Init->isNullValue() || NumStores--;
922
923 // See if we can emit each element.
924 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
925 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
926 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
927 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
928 return false;
929 }
930 return true;
931 }
932
933 if (llvm::ConstantDataSequential *CDS =
934 dyn_cast<llvm::ConstantDataSequential>(Init)) {
935 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
936 llvm::Constant *Elt = CDS->getElementAsConstant(i);
937 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
938 return false;
939 }
940 return true;
941 }
942
943 // Anything else is hard and scary.
944 return false;
945}
946
947/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
948/// the scalar stores that would be required.
950 llvm::Constant *Init, Address Loc,
951 bool isVolatile, CGBuilderTy &Builder,
952 bool IsAutoInit) {
953 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
954 "called emitStoresForInitAfterBZero for zero or undef value.");
955
956 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
957 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
958 isa<llvm::ConstantExpr>(Init)) {
959 auto *I = Builder.CreateStore(Init, Loc, isVolatile);
960 if (IsAutoInit)
961 I->addAnnotationMetadata("auto-init");
962 return;
963 }
964
965 if (llvm::ConstantDataSequential *CDS =
966 dyn_cast<llvm::ConstantDataSequential>(Init)) {
967 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
968 llvm::Constant *Elt = CDS->getElementAsConstant(i);
969
970 // If necessary, get a pointer to the element and emit it.
971 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
973 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
974 Builder, IsAutoInit);
975 }
976 return;
977 }
978
979 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
980 "Unknown value type!");
981
982 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
983 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
984
985 // If necessary, get a pointer to the element and emit it.
986 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
988 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
989 isVolatile, Builder, IsAutoInit);
990 }
991}
992
993/// Decide whether we should use bzero plus some stores to initialize a local
994/// variable instead of using a memcpy from a constant global. It is beneficial
995/// to use bzero if the global is all zeros, or mostly zeros and large.
996static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
997 uint64_t GlobalSize) {
998 // If a global is all zeros, always use a bzero.
999 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
1000
1001 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
1002 // do it if it will require 6 or fewer scalar stores.
1003 // TODO: Should budget depends on the size? Avoiding a large global warrants
1004 // plopping in more stores.
1005 unsigned StoreBudget = 6;
1006 uint64_t SizeLimit = 32;
1007
1008 return GlobalSize > SizeLimit &&
1010}
1011
1012/// Decide whether we should use memset to initialize a local variable instead
1013/// of using a memcpy from a constant global. Assumes we've already decided to
1014/// not user bzero.
1015/// FIXME We could be more clever, as we are for bzero above, and generate
1016/// memset followed by stores. It's unclear that's worth the effort.
1017static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
1018 uint64_t GlobalSize,
1019 const llvm::DataLayout &DL) {
1020 uint64_t SizeLimit = 32;
1021 if (GlobalSize <= SizeLimit)
1022 return nullptr;
1023 return llvm::isBytewiseValue(Init, DL);
1024}
1025
1026/// Decide whether we want to split a constant structure or array store into a
1027/// sequence of its fields' stores. This may cost us code size and compilation
1028/// speed, but plays better with store optimizations.
1030 uint64_t GlobalByteSize) {
1031 // Don't break things that occupy more than one cacheline.
1032 uint64_t ByteSizeLimit = 64;
1033 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1034 return false;
1035 if (GlobalByteSize <= ByteSizeLimit)
1036 return true;
1037 return false;
1038}
1039
1040enum class IsPattern { No, Yes };
1041
1042/// Generate a constant filled with either a pattern or zeroes.
1043static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1044 llvm::Type *Ty) {
1045 if (isPattern == IsPattern::Yes)
1046 return initializationPatternFor(CGM, Ty);
1047 else
1048 return llvm::Constant::getNullValue(Ty);
1049}
1050
1051static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1052 llvm::Constant *constant);
1053
1054/// Helper function for constWithPadding() to deal with padding in structures.
1055static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1056 IsPattern isPattern,
1057 llvm::StructType *STy,
1058 llvm::Constant *constant) {
1059 const llvm::DataLayout &DL = CGM.getDataLayout();
1060 const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1061 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1062 unsigned SizeSoFar = 0;
1064 bool NestedIntact = true;
1065 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1066 unsigned CurOff = Layout->getElementOffset(i);
1067 if (SizeSoFar < CurOff) {
1068 assert(!STy->isPacked());
1069 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1070 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1071 }
1072 llvm::Constant *CurOp;
1073 if (constant->isZeroValue())
1074 CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1075 else
1076 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1077 auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1078 if (CurOp != NewOp)
1079 NestedIntact = false;
1080 Values.push_back(NewOp);
1081 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1082 }
1083 unsigned TotalSize = Layout->getSizeInBytes();
1084 if (SizeSoFar < TotalSize) {
1085 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1086 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1087 }
1088 if (NestedIntact && Values.size() == STy->getNumElements())
1089 return constant;
1090 return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1091}
1092
1093/// Replace all padding bytes in a given constant with either a pattern byte or
1094/// 0x00.
1095static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1096 llvm::Constant *constant) {
1097 llvm::Type *OrigTy = constant->getType();
1098 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1099 return constStructWithPadding(CGM, isPattern, STy, constant);
1100 if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
1102 uint64_t Size = ArrayTy->getNumElements();
1103 if (!Size)
1104 return constant;
1105 llvm::Type *ElemTy = ArrayTy->getElementType();
1106 bool ZeroInitializer = constant->isNullValue();
1107 llvm::Constant *OpValue, *PaddedOp;
1108 if (ZeroInitializer) {
1109 OpValue = llvm::Constant::getNullValue(ElemTy);
1110 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1111 }
1112 for (unsigned Op = 0; Op != Size; ++Op) {
1113 if (!ZeroInitializer) {
1114 OpValue = constant->getAggregateElement(Op);
1115 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1116 }
1117 Values.push_back(PaddedOp);
1118 }
1119 auto *NewElemTy = Values[0]->getType();
1120 if (NewElemTy == ElemTy)
1121 return constant;
1122 auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1123 return llvm::ConstantArray::get(NewArrayTy, Values);
1124 }
1125 // FIXME: Add handling for tail padding in vectors. Vectors don't
1126 // have padding between or inside elements, but the total amount of
1127 // data can be less than the allocated size.
1128 return constant;
1129}
1130
1132 llvm::Constant *Constant,
1133 CharUnits Align) {
1134 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1135 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1136 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1137 return CC->getNameAsString();
1138 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1139 return CD->getNameAsString();
1140 return std::string(getMangledName(FD));
1141 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1142 return OM->getNameAsString();
1143 } else if (isa<BlockDecl>(DC)) {
1144 return "<block>";
1145 } else if (isa<CapturedDecl>(DC)) {
1146 return "<captured>";
1147 } else {
1148 llvm_unreachable("expected a function or method");
1149 }
1150 };
1151
1152 // Form a simple per-variable cache of these values in case we find we
1153 // want to reuse them.
1154 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1155 if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1156 auto *Ty = Constant->getType();
1157 bool isConstant = true;
1158 llvm::GlobalVariable *InsertBefore = nullptr;
1159 unsigned AS =
1161 std::string Name;
1162 if (D.hasGlobalStorage())
1163 Name = getMangledName(&D).str() + ".const";
1164 else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1165 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1166 else
1167 llvm_unreachable("local variable has no parent function or method");
1168 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1169 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1170 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1171 GV->setAlignment(Align.getAsAlign());
1172 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1173 CacheEntry = GV;
1174 } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
1175 CacheEntry->setAlignment(Align.getAsAlign());
1176 }
1177
1178 return Address(CacheEntry, CacheEntry->getValueType(), Align);
1179}
1180
1182 const VarDecl &D,
1183 CGBuilderTy &Builder,
1184 llvm::Constant *Constant,
1185 CharUnits Align) {
1186 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1187 return SrcPtr.withElementType(CGM.Int8Ty);
1188}
1189
1191 Address Loc, bool isVolatile,
1192 CGBuilderTy &Builder,
1193 llvm::Constant *constant, bool IsAutoInit) {
1194 auto *Ty = constant->getType();
1195 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1196 if (!ConstantSize)
1197 return;
1198
1199 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1200 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1201 if (canDoSingleStore) {
1202 auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1203 if (IsAutoInit)
1204 I->addAnnotationMetadata("auto-init");
1205 return;
1206 }
1207
1208 auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1209
1210 // If the initializer is all or mostly the same, codegen with bzero / memset
1211 // then do a few stores afterward.
1212 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1213 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1214 SizeVal, isVolatile);
1215 if (IsAutoInit)
1216 I->addAnnotationMetadata("auto-init");
1217
1218 bool valueAlreadyCorrect =
1219 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1220 if (!valueAlreadyCorrect) {
1221 Loc = Loc.withElementType(Ty);
1222 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1223 IsAutoInit);
1224 }
1225 return;
1226 }
1227
1228 // If the initializer is a repeated byte pattern, use memset.
1229 llvm::Value *Pattern =
1230 shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1231 if (Pattern) {
1232 uint64_t Value = 0x00;
1233 if (!isa<llvm::UndefValue>(Pattern)) {
1234 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1235 assert(AP.getBitWidth() <= 8);
1236 Value = AP.getLimitedValue();
1237 }
1238 auto *I = Builder.CreateMemSet(
1239 Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1240 if (IsAutoInit)
1241 I->addAnnotationMetadata("auto-init");
1242 return;
1243 }
1244
1245 // If the initializer is small, use a handful of stores.
1246 if (shouldSplitConstantStore(CGM, ConstantSize)) {
1247 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1248 const llvm::StructLayout *Layout =
1249 CGM.getDataLayout().getStructLayout(STy);
1250 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1251 CharUnits CurOff = CharUnits::fromQuantity(Layout->getElementOffset(i));
1252 Address EltPtr = Builder.CreateConstInBoundsByteGEP(
1253 Loc.withElementType(CGM.Int8Ty), CurOff);
1254 emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
1255 constant->getAggregateElement(i), IsAutoInit);
1256 }
1257 return;
1258 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1259 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1260 Address EltPtr = Builder.CreateConstGEP(
1261 Loc.withElementType(ATy->getElementType()), i);
1262 emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
1263 constant->getAggregateElement(i), IsAutoInit);
1264 }
1265 return;
1266 }
1267 }
1268
1269 // Copy from a global.
1270 auto *I =
1271 Builder.CreateMemCpy(Loc,
1273 CGM, D, Builder, constant, Loc.getAlignment()),
1274 SizeVal, isVolatile);
1275 if (IsAutoInit)
1276 I->addAnnotationMetadata("auto-init");
1277}
1278
1280 Address Loc, bool isVolatile,
1281 CGBuilderTy &Builder) {
1282 llvm::Type *ElTy = Loc.getElementType();
1283 llvm::Constant *constant =
1284 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1285 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1286 /*IsAutoInit=*/true);
1287}
1288
1290 Address Loc, bool isVolatile,
1291 CGBuilderTy &Builder) {
1292 llvm::Type *ElTy = Loc.getElementType();
1293 llvm::Constant *constant = constWithPadding(
1294 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1295 assert(!isa<llvm::UndefValue>(constant));
1296 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1297 /*IsAutoInit=*/true);
1298}
1299
1300static bool containsUndef(llvm::Constant *constant) {
1301 auto *Ty = constant->getType();
1302 if (isa<llvm::UndefValue>(constant))
1303 return true;
1304 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1305 for (llvm::Use &Op : constant->operands())
1306 if (containsUndef(cast<llvm::Constant>(Op)))
1307 return true;
1308 return false;
1309}
1310
1311static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1312 llvm::Constant *constant) {
1313 auto *Ty = constant->getType();
1314 if (isa<llvm::UndefValue>(constant))
1315 return patternOrZeroFor(CGM, isPattern, Ty);
1316 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1317 return constant;
1318 if (!containsUndef(constant))
1319 return constant;
1320 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1321 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1322 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1323 Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1324 }
1325 if (Ty->isStructTy())
1326 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1327 if (Ty->isArrayTy())
1328 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1329 assert(Ty->isVectorTy());
1330 return llvm::ConstantVector::get(Values);
1331}
1332
1333/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1334/// variable declaration with auto, register, or no storage class specifier.
1335/// These turn into simple stack objects, or GlobalValues depending on target.
1337 AutoVarEmission emission = EmitAutoVarAlloca(D);
1338 EmitAutoVarInit(emission);
1339 EmitAutoVarCleanups(emission);
1340}
1341
1342/// Emit a lifetime.begin marker if some criteria are satisfied.
1343/// \return a pointer to the temporary size Value if a marker was emitted, null
1344/// otherwise
1345llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
1346 llvm::Value *Addr) {
1347 if (!ShouldEmitLifetimeMarkers)
1348 return nullptr;
1349
1350 assert(Addr->getType()->getPointerAddressSpace() ==
1351 CGM.getDataLayout().getAllocaAddrSpace() &&
1352 "Pointer should be in alloca address space");
1353 llvm::Value *SizeV = llvm::ConstantInt::get(
1354 Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
1355 llvm::CallInst *C =
1356 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1357 C->setDoesNotThrow();
1358 return SizeV;
1359}
1360
1361void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1362 assert(Addr->getType()->getPointerAddressSpace() ==
1363 CGM.getDataLayout().getAllocaAddrSpace() &&
1364 "Pointer should be in alloca address space");
1365 llvm::CallInst *C =
1366 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1367 C->setDoesNotThrow();
1368}
1369
1371 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1372 // For each dimension stores its QualType and corresponding
1373 // size-expression Value.
1376
1377 // Break down the array into individual dimensions.
1378 QualType Type1D = D.getType();
1379 while (getContext().getAsVariableArrayType(Type1D)) {
1380 auto VlaSize = getVLAElements1D(Type1D);
1381 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1382 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1383 else {
1384 // Generate a locally unique name for the size expression.
1385 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1386 SmallString<12> Buffer;
1387 StringRef NameRef = Name.toStringRef(Buffer);
1388 auto &Ident = getContext().Idents.getOwn(NameRef);
1389 VLAExprNames.push_back(&Ident);
1390 auto SizeExprAddr =
1391 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1392 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1393 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1394 Type1D.getUnqualifiedType());
1395 }
1396 Type1D = VlaSize.Type;
1397 }
1398
1399 if (!EmitDebugInfo)
1400 return;
1401
1402 // Register each dimension's size-expression with a DILocalVariable,
1403 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1404 // to describe this array.
1405 unsigned NameIdx = 0;
1406 for (auto &VlaSize : Dimensions) {
1407 llvm::Metadata *MD;
1408 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1409 MD = llvm::ConstantAsMetadata::get(C);
1410 else {
1411 // Create an artificial VarDecl to generate debug info for.
1412 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1414 SizeTy->getScalarSizeInBits(), false);
1415 auto *ArtificialDecl = VarDecl::Create(
1416 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1417 D.getLocation(), D.getLocation(), NameIdent, QT,
1418 getContext().CreateTypeSourceInfo(QT), SC_Auto);
1419 ArtificialDecl->setImplicit();
1420
1421 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1422 Builder);
1423 }
1424 assert(MD && "No Size expression debug node created");
1425 DI->registerVLASizeExpression(VlaSize.Type, MD);
1426 }
1427}
1428
1429/// EmitAutoVarAlloca - Emit the alloca and debug information for a
1430/// local variable. Does not emit initialization or destruction.
1431CodeGenFunction::AutoVarEmission
1433 QualType Ty = D.getType();
1434 assert(
1437
1438 AutoVarEmission emission(D);
1439
1440 bool isEscapingByRef = D.isEscapingByref();
1441 emission.IsEscapingByRef = isEscapingByRef;
1442
1443 CharUnits alignment = getContext().getDeclAlign(&D);
1444
1445 // If the type is variably-modified, emit all the VLA sizes for it.
1446 if (Ty->isVariablyModifiedType())
1448
1449 auto *DI = getDebugInfo();
1450 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1451
1452 Address address = Address::invalid();
1453 Address AllocaAddr = Address::invalid();
1454 Address OpenMPLocalAddr = Address::invalid();
1455 if (CGM.getLangOpts().OpenMPIRBuilder)
1456 OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1457 else
1458 OpenMPLocalAddr =
1459 getLangOpts().OpenMP
1461 : Address::invalid();
1462
1463 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1464
1465 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1466 address = OpenMPLocalAddr;
1467 AllocaAddr = OpenMPLocalAddr;
1468 } else if (Ty->isConstantSizeType()) {
1469 // If this value is an array or struct with a statically determinable
1470 // constant initializer, there are optimizations we can do.
1471 //
1472 // TODO: We should constant-evaluate the initializer of any variable,
1473 // as long as it is initialized by a constant expression. Currently,
1474 // isConstantInitializer produces wrong answers for structs with
1475 // reference or bitfield members, and a few other cases, and checking
1476 // for POD-ness protects us from some of these.
1477 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1478 (D.isConstexpr() ||
1479 ((Ty.isPODType(getContext()) ||
1480 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1481 D.getInit()->isConstantInitializer(getContext(), false)))) {
1482
1483 // If the variable's a const type, and it's neither an NRVO
1484 // candidate nor a __block variable and has no mutable members,
1485 // emit it as a global instead.
1486 // Exception is if a variable is located in non-constant address space
1487 // in OpenCL.
1488 bool NeedsDtor =
1490 if ((!getLangOpts().OpenCL ||
1492 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1493 !isEscapingByRef &&
1494 Ty.isConstantStorage(getContext(), true, !NeedsDtor))) {
1495 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1496
1497 // Signal this condition to later callbacks.
1498 emission.Addr = Address::invalid();
1499 assert(emission.wasEmittedAsGlobal());
1500 return emission;
1501 }
1502
1503 // Otherwise, tell the initialization code that we're in this case.
1504 emission.IsConstantAggregate = true;
1505 }
1506
1507 // A normal fixed sized variable becomes an alloca in the entry block,
1508 // unless:
1509 // - it's an NRVO variable.
1510 // - we are compiling OpenMP and it's an OpenMP local variable.
1511 if (NRVO) {
1512 // The named return value optimization: allocate this variable in the
1513 // return slot, so that we can elide the copy when returning this
1514 // variable (C++0x [class.copy]p34).
1515 address = ReturnValue;
1516 AllocaAddr = ReturnValue;
1517
1518 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1519 const auto *RD = RecordTy->getDecl();
1520 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1521 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1522 RD->isNonTrivialToPrimitiveDestroy()) {
1523 // Create a flag that is used to indicate when the NRVO was applied
1524 // to this variable. Set it to zero to indicate that NRVO was not
1525 // applied.
1526 llvm::Value *Zero = Builder.getFalse();
1527 Address NRVOFlag =
1528 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1530 Builder.CreateStore(Zero, NRVOFlag);
1531
1532 // Record the NRVO flag for this variable.
1533 NRVOFlags[&D] = NRVOFlag.getPointer();
1534 emission.NRVOFlag = NRVOFlag.getPointer();
1535 }
1536 }
1537 } else {
1538 CharUnits allocaAlignment;
1539 llvm::Type *allocaTy;
1540 if (isEscapingByRef) {
1541 auto &byrefInfo = getBlockByrefInfo(&D);
1542 allocaTy = byrefInfo.Type;
1543 allocaAlignment = byrefInfo.ByrefAlignment;
1544 } else {
1545 allocaTy = ConvertTypeForMem(Ty);
1546 allocaAlignment = alignment;
1547 }
1548
1549 // Create the alloca. Note that we set the name separately from
1550 // building the instruction so that it's there even in no-asserts
1551 // builds.
1552 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1553 /*ArraySize=*/nullptr, &AllocaAddr);
1554
1555 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1556 // the catch parameter starts in the catchpad instruction, and we can't
1557 // insert code in those basic blocks.
1558 bool IsMSCatchParam =
1560
1561 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1562 // if we don't have a valid insertion point (?).
1563 if (HaveInsertPoint() && !IsMSCatchParam) {
1564 // If there's a jump into the lifetime of this variable, its lifetime
1565 // gets broken up into several regions in IR, which requires more work
1566 // to handle correctly. For now, just omit the intrinsics; this is a
1567 // rare case, and it's better to just be conservatively correct.
1568 // PR28267.
1569 //
1570 // We have to do this in all language modes if there's a jump past the
1571 // declaration. We also have to do it in C if there's a jump to an
1572 // earlier point in the current block because non-VLA lifetimes begin as
1573 // soon as the containing block is entered, not when its variables
1574 // actually come into scope; suppressing the lifetime annotations
1575 // completely in this case is unnecessarily pessimistic, but again, this
1576 // is rare.
1577 if (!Bypasses.IsBypassed(&D) &&
1579 llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1580 emission.SizeForLifetimeMarkers =
1581 EmitLifetimeStart(Size, AllocaAddr.getPointer());
1582 }
1583 } else {
1584 assert(!emission.useLifetimeMarkers());
1585 }
1586 }
1587 } else {
1589
1590 // Delayed globalization for variable length declarations. This ensures that
1591 // the expression representing the length has been emitted and can be used
1592 // by the definition of the VLA. Since this is an escaped declaration, in
1593 // OpenMP we have to use a call to __kmpc_alloc_shared(). The matching
1594 // deallocation call to __kmpc_free_shared() is emitted later.
1595 bool VarAllocated = false;
1596 if (getLangOpts().OpenMPIsTargetDevice) {
1597 auto &RT = CGM.getOpenMPRuntime();
1598 if (RT.isDelayedVariableLengthDecl(*this, &D)) {
1599 // Emit call to __kmpc_alloc_shared() instead of the alloca.
1600 std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
1601 RT.getKmpcAllocShared(*this, &D);
1602
1603 // Save the address of the allocation:
1604 LValue Base = MakeAddrLValue(AddrSizePair.first, D.getType(),
1607 address = Base.getAddress(*this);
1608
1609 // Push a cleanup block to emit the call to __kmpc_free_shared in the
1610 // appropriate location at the end of the scope of the
1611 // __kmpc_alloc_shared functions:
1612 pushKmpcAllocFree(NormalCleanup, AddrSizePair);
1613
1614 // Mark variable as allocated:
1615 VarAllocated = true;
1616 }
1617 }
1618
1619 if (!VarAllocated) {
1620 if (!DidCallStackSave) {
1621 // Save the stack.
1622 Address Stack =
1624
1625 llvm::Value *V = Builder.CreateStackSave();
1626 assert(V->getType() == AllocaInt8PtrTy);
1627 Builder.CreateStore(V, Stack);
1628
1629 DidCallStackSave = true;
1630
1631 // Push a cleanup block and restore the stack there.
1632 // FIXME: in general circumstances, this should be an EH cleanup.
1634 }
1635
1636 auto VlaSize = getVLASize(Ty);
1637 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1638
1639 // Allocate memory for the array.
1640 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1641 &AllocaAddr);
1642 }
1643
1644 // If we have debug info enabled, properly describe the VLA dimensions for
1645 // this type by registering the vla size expression for each of the
1646 // dimensions.
1647 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1648 }
1649
1650 setAddrOfLocalVar(&D, address);
1651 emission.Addr = address;
1652 emission.AllocaAddr = AllocaAddr;
1653
1654 // Emit debug info for local var declaration.
1655 if (EmitDebugInfo && HaveInsertPoint()) {
1656 Address DebugAddr = address;
1657 bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1658 DI->setLocation(D.getLocation());
1659
1660 // If NRVO, use a pointer to the return address.
1661 if (UsePointerValue) {
1662 DebugAddr = ReturnValuePointer;
1663 AllocaAddr = ReturnValuePointer;
1664 }
1665 (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
1666 UsePointerValue);
1667 }
1668
1669 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1670 EmitVarAnnotations(&D, address.getPointer());
1671
1672 // Make sure we call @llvm.lifetime.end.
1673 if (emission.useLifetimeMarkers())
1674 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1675 emission.getOriginalAllocatedAddress(),
1676 emission.getSizeForLifetimeMarkers());
1677
1678 return emission;
1679}
1680
1681static bool isCapturedBy(const VarDecl &, const Expr *);
1682
1683/// Determines whether the given __block variable is potentially
1684/// captured by the given statement.
1685static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1686 if (const Expr *E = dyn_cast<Expr>(S))
1687 return isCapturedBy(Var, E);
1688 for (const Stmt *SubStmt : S->children())
1689 if (isCapturedBy(Var, SubStmt))
1690 return true;
1691 return false;
1692}
1693
1694/// Determines whether the given __block variable is potentially
1695/// captured by the given expression.
1696static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1697 // Skip the most common kinds of expressions that make
1698 // hierarchy-walking expensive.
1699 E = E->IgnoreParenCasts();
1700
1701 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1702 const BlockDecl *Block = BE->getBlockDecl();
1703 for (const auto &I : Block->captures()) {
1704 if (I.getVariable() == &Var)
1705 return true;
1706 }
1707
1708 // No need to walk into the subexpressions.
1709 return false;
1710 }
1711
1712 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1713 const CompoundStmt *CS = SE->getSubStmt();
1714 for (const auto *BI : CS->body())
1715 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1716 if (isCapturedBy(Var, BIE))
1717 return true;
1718 }
1719 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1720 // special case declarations
1721 for (const auto *I : DS->decls()) {
1722 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1723 const Expr *Init = VD->getInit();
1724 if (Init && isCapturedBy(Var, Init))
1725 return true;
1726 }
1727 }
1728 }
1729 else
1730 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1731 // Later, provide code to poke into statements for capture analysis.
1732 return true;
1733 return false;
1734 }
1735
1736 for (const Stmt *SubStmt : E->children())
1737 if (isCapturedBy(Var, SubStmt))
1738 return true;
1739
1740 return false;
1741}
1742
1743/// Determine whether the given initializer is trivial in the sense
1744/// that it requires no code to be generated.
1746 if (!Init)
1747 return true;
1748
1749 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1750 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1751 if (Constructor->isTrivial() &&
1752 Constructor->isDefaultConstructor() &&
1753 !Construct->requiresZeroInitialization())
1754 return true;
1755
1756 return false;
1757}
1758
1759void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1760 const VarDecl &D,
1761 Address Loc) {
1762 auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1763 auto trivialAutoVarInitMaxSize =
1764 getContext().getLangOpts().TrivialAutoVarInitMaxSize;
1766 bool isVolatile = type.isVolatileQualified();
1767 if (!Size.isZero()) {
1768 // We skip auto-init variables by their alloc size. Take this as an example:
1769 // "struct Foo {int x; char buff[1024];}" Assume the max-size flag is 1023.
1770 // All Foo type variables will be skipped. Ideally, we only skip the buff
1771 // array and still auto-init X in this example.
1772 // TODO: Improve the size filtering to by member size.
1773 auto allocSize = CGM.getDataLayout().getTypeAllocSize(Loc.getElementType());
1774 switch (trivialAutoVarInit) {
1776 llvm_unreachable("Uninitialized handled by caller");
1778 if (CGM.stopAutoInit())
1779 return;
1780 if (trivialAutoVarInitMaxSize > 0 &&
1781 allocSize > trivialAutoVarInitMaxSize)
1782 return;
1783 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1784 break;
1786 if (CGM.stopAutoInit())
1787 return;
1788 if (trivialAutoVarInitMaxSize > 0 &&
1789 allocSize > trivialAutoVarInitMaxSize)
1790 return;
1791 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1792 break;
1793 }
1794 return;
1795 }
1796
1797 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1798 // them, so emit a memcpy with the VLA size to initialize each element.
1799 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1800 // will catch that code, but there exists code which generates zero-sized
1801 // VLAs. Be nice and initialize whatever they requested.
1802 const auto *VlaType = getContext().getAsVariableArrayType(type);
1803 if (!VlaType)
1804 return;
1805 auto VlaSize = getVLASize(VlaType);
1806 auto SizeVal = VlaSize.NumElts;
1807 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1808 switch (trivialAutoVarInit) {
1810 llvm_unreachable("Uninitialized handled by caller");
1811
1813 if (CGM.stopAutoInit())
1814 return;
1815 if (!EltSize.isOne())
1816 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1817 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1818 SizeVal, isVolatile);
1819 I->addAnnotationMetadata("auto-init");
1820 break;
1821 }
1822
1824 if (CGM.stopAutoInit())
1825 return;
1826 llvm::Type *ElTy = Loc.getElementType();
1827 llvm::Constant *Constant = constWithPadding(
1828 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1829 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1830 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1831 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1832 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1833 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1834 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1835 "vla.iszerosized");
1836 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1837 EmitBlock(SetupBB);
1838 if (!EltSize.isOne())
1839 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1840 llvm::Value *BaseSizeInChars =
1841 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1843 llvm::Value *End = Builder.CreateInBoundsGEP(
1844 Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
1845 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1846 EmitBlock(LoopBB);
1847 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1848 Cur->addIncoming(Begin.getPointer(), OriginBB);
1849 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1850 auto *I =
1851 Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),
1853 CGM, D, Builder, Constant, ConstantAlign),
1854 BaseSizeInChars, isVolatile);
1855 I->addAnnotationMetadata("auto-init");
1856 llvm::Value *Next =
1857 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1858 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1859 Builder.CreateCondBr(Done, ContBB, LoopBB);
1860 Cur->addIncoming(Next, LoopBB);
1861 EmitBlock(ContBB);
1862 } break;
1863 }
1864}
1865
1866void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1867 assert(emission.Variable && "emission was not valid!");
1868
1869 // If this was emitted as a global constant, we're done.
1870 if (emission.wasEmittedAsGlobal()) return;
1871
1872 const VarDecl &D = *emission.Variable;
1874 QualType type = D.getType();
1875
1876 // If this local has an initializer, emit it now.
1877 const Expr *Init = D.getInit();
1878
1879 // If we are at an unreachable point, we don't need to emit the initializer
1880 // unless it contains a label.
1881 if (!HaveInsertPoint()) {
1882 if (!Init || !ContainsLabel(Init)) return;
1884 }
1885
1886 // Initialize the structure of a __block variable.
1887 if (emission.IsEscapingByRef)
1888 emitByrefStructureInit(emission);
1889
1890 // Initialize the variable here if it doesn't have a initializer and it is a
1891 // C struct that is non-trivial to initialize or an array containing such a
1892 // struct.
1893 if (!Init &&
1894 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1896 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1897 if (emission.IsEscapingByRef)
1898 drillIntoBlockVariable(*this, Dst, &D);
1900 return;
1901 }
1902
1903 // Check whether this is a byref variable that's potentially
1904 // captured and moved by its own initializer. If so, we'll need to
1905 // emit the initializer first, then copy into the variable.
1906 bool capturedByInit =
1907 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1908
1909 bool locIsByrefHeader = !capturedByInit;
1910 const Address Loc =
1911 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1912
1913 // Note: constexpr already initializes everything correctly.
1914 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1915 (D.isConstexpr()
1917 : (D.getAttr<UninitializedAttr>()
1919 : getContext().getLangOpts().getTrivialAutoVarInit()));
1920
1921 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1922 if (trivialAutoVarInit ==
1924 return;
1925
1926 // Only initialize a __block's storage: we always initialize the header.
1927 if (emission.IsEscapingByRef && !locIsByrefHeader)
1928 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1929
1930 return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1931 };
1932
1934 return initializeWhatIsTechnicallyUninitialized(Loc);
1935
1936 llvm::Constant *constant = nullptr;
1937 if (emission.IsConstantAggregate ||
1939 assert(!capturedByInit && "constant init contains a capturing block?");
1941 if (constant && !constant->isZeroValue() &&
1942 (trivialAutoVarInit !=
1944 IsPattern isPattern =
1945 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1946 ? IsPattern::Yes
1947 : IsPattern::No;
1948 // C guarantees that brace-init with fewer initializers than members in
1949 // the aggregate will initialize the rest of the aggregate as-if it were
1950 // static initialization. In turn static initialization guarantees that
1951 // padding is initialized to zero bits. We could instead pattern-init if D
1952 // has any ImplicitValueInitExpr, but that seems to be unintuitive
1953 // behavior.
1954 constant = constWithPadding(CGM, IsPattern::No,
1955 replaceUndef(CGM, isPattern, constant));
1956 }
1957 }
1958
1959 if (!constant) {
1960 initializeWhatIsTechnicallyUninitialized(Loc);
1961 LValue lv = MakeAddrLValue(Loc, type);
1962 lv.setNonGC(true);
1963 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1964 }
1965
1966 if (!emission.IsConstantAggregate) {
1967 // For simple scalar/complex initialization, store the value directly.
1968 LValue lv = MakeAddrLValue(Loc, type);
1969 lv.setNonGC(true);
1970 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1971 }
1972
1974 type.isVolatileQualified(), Builder, constant,
1975 /*IsAutoInit=*/false);
1976}
1977
1978/// Emit an expression as an initializer for an object (variable, field, etc.)
1979/// at the given location. The expression is not necessarily the normal
1980/// initializer for the object, and the address is not necessarily
1981/// its normal location.
1982///
1983/// \param init the initializing expression
1984/// \param D the object to act as if we're initializing
1985/// \param lvalue the lvalue to initialize
1986/// \param capturedByInit true if \p D is a __block variable
1987/// whose address is potentially changed by the initializer
1988void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1989 LValue lvalue, bool capturedByInit) {
1990 QualType type = D->getType();
1991
1992 if (type->isReferenceType()) {
1993 RValue rvalue = EmitReferenceBindingToExpr(init);
1994 if (capturedByInit)
1995 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1996 EmitStoreThroughLValue(rvalue, lvalue, true);
1997 return;
1998 }
1999 switch (getEvaluationKind(type)) {
2000 case TEK_Scalar:
2001 EmitScalarInit(init, D, lvalue, capturedByInit);
2002 return;
2003 case TEK_Complex: {
2004 ComplexPairTy complex = EmitComplexExpr(init);
2005 if (capturedByInit)
2006 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
2007 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
2008 return;
2009 }
2010 case TEK_Aggregate:
2011 if (type->isAtomicType()) {
2012 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
2013 } else {
2015 if (isa<VarDecl>(D))
2017 else if (auto *FD = dyn_cast<FieldDecl>(D))
2018 Overlap = getOverlapForFieldInit(FD);
2019 // TODO: how can we delay here if D is captured by its initializer?
2021 lvalue, *this, AggValueSlot::IsDestructed,
2023 AggValueSlot::IsNotAliased, Overlap));
2024 }
2025 return;
2026 }
2027 llvm_unreachable("bad evaluation kind");
2028}
2029
2030/// Enter a destroy cleanup for the given local variable.
2032 const CodeGenFunction::AutoVarEmission &emission,
2033 QualType::DestructionKind dtorKind) {
2034 assert(dtorKind != QualType::DK_none);
2035
2036 // Note that for __block variables, we want to destroy the
2037 // original stack object, not the possibly forwarded object.
2038 Address addr = emission.getObjectAddress(*this);
2039
2040 const VarDecl *var = emission.Variable;
2041 QualType type = var->getType();
2042
2043 CleanupKind cleanupKind = NormalAndEHCleanup;
2044 CodeGenFunction::Destroyer *destroyer = nullptr;
2045
2046 switch (dtorKind) {
2047 case QualType::DK_none:
2048 llvm_unreachable("no cleanup for trivially-destructible variable");
2049
2051 // If there's an NRVO flag on the emission, we need a different
2052 // cleanup.
2053 if (emission.NRVOFlag) {
2054 assert(!type->isArrayType());
2055 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
2056 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
2057 emission.NRVOFlag);
2058 return;
2059 }
2060 break;
2061
2063 // Suppress cleanups for pseudo-strong variables.
2064 if (var->isARCPseudoStrong()) return;
2065
2066 // Otherwise, consider whether to use an EH cleanup or not.
2067 cleanupKind = getARCCleanupKind();
2068
2069 // Use the imprecise destroyer by default.
2070 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2072 break;
2073
2075 break;
2076
2079 if (emission.NRVOFlag) {
2080 assert(!type->isArrayType());
2081 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2082 emission.NRVOFlag, type);
2083 return;
2084 }
2085 break;
2086 }
2087
2088 // If we haven't chosen a more specific destroyer, use the default.
2089 if (!destroyer) destroyer = getDestroyer(dtorKind);
2090
2091 // Use an EH cleanup in array destructors iff the destructor itself
2092 // is being pushed as an EH cleanup.
2093 bool useEHCleanup = (cleanupKind & EHCleanup);
2094 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2095 useEHCleanup);
2096}
2097
2098void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2099 assert(emission.Variable && "emission was not valid!");
2100
2101 // If this was emitted as a global constant, we're done.
2102 if (emission.wasEmittedAsGlobal()) return;
2103
2104 // If we don't have an insertion point, we're done. Sema prevents
2105 // us from jumping into any of these scopes anyway.
2106 if (!HaveInsertPoint()) return;
2107
2108 const VarDecl &D = *emission.Variable;
2109
2110 // Check the type for a cleanup.
2112 emitAutoVarTypeCleanup(emission, dtorKind);
2113
2114 // In GC mode, honor objc_precise_lifetime.
2115 if (getLangOpts().getGC() != LangOptions::NonGC &&
2116 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2117 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2118 }
2119
2120 // Handle the cleanup attribute.
2121 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2122 const FunctionDecl *FD = CA->getFunctionDecl();
2123
2124 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2125 assert(F && "Could not find function!");
2126
2128 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2129 }
2130
2131 // If this is a block variable, call _Block_object_destroy
2132 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2133 // mode.
2134 if (emission.IsEscapingByRef &&
2135 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2137 if (emission.Variable->getType().isObjCGCWeak())
2138 Flags |= BLOCK_FIELD_IS_WEAK;
2139 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2140 /*LoadBlockVarAddr*/ false,
2141 cxxDestructorCanThrow(emission.Variable->getType()));
2142 }
2143}
2144
2147 switch (kind) {
2148 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2150 return destroyCXXObject;
2154 return destroyARCWeak;
2157 }
2158 llvm_unreachable("Unknown DestructionKind");
2159}
2160
2161/// pushEHDestroy - Push the standard destructor for the given type as
2162/// an EH-only cleanup.
2164 Address addr, QualType type) {
2165 assert(dtorKind && "cannot push destructor for trivial type");
2166 assert(needsEHCleanup(dtorKind));
2167
2168 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2169}
2170
2171/// pushDestroy - Push the standard destructor for the given type as
2172/// at least a normal cleanup.
2174 Address addr, QualType type) {
2175 assert(dtorKind && "cannot push destructor for trivial type");
2176
2177 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2178 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2179 cleanupKind & EHCleanup);
2180}
2181
2182void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2183 QualType type, Destroyer *destroyer,
2184 bool useEHCleanupForArray) {
2185 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2186 destroyer, useEHCleanupForArray);
2187}
2188
2190 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2191}
2192
2194 CleanupKind Kind, std::pair<llvm::Value *, llvm::Value *> AddrSizePair) {
2195 EHStack.pushCleanup<KmpcAllocFree>(Kind, AddrSizePair);
2196}
2197
2199 Address addr, QualType type,
2200 Destroyer *destroyer,
2201 bool useEHCleanupForArray) {
2202 // If we're not in a conditional branch, we don't need to bother generating a
2203 // conditional cleanup.
2204 if (!isInConditionalBranch()) {
2205 // Push an EH-only cleanup for the object now.
2206 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2207 // around in case a temporary's destructor throws an exception.
2208 if (cleanupKind & EHCleanup)
2209 EHStack.pushCleanup<DestroyObject>(
2210 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2211 destroyer, useEHCleanupForArray);
2212
2213 return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2214 cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
2215 }
2216
2217 // Otherwise, we should only destroy the object if it's been initialized.
2218 // Re-use the active flag and saved address across both the EH and end of
2219 // scope cleanups.
2220
2221 using SavedType = typename DominatingValue<Address>::saved_type;
2222 using ConditionalCleanupType =
2224 Destroyer *, bool>;
2225
2226 Address ActiveFlag = createCleanupActiveFlag();
2227 SavedType SavedAddr = saveValueInCond(addr);
2228
2229 if (cleanupKind & EHCleanup) {
2230 EHStack.pushCleanup<ConditionalCleanupType>(
2231 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
2232 destroyer, useEHCleanupForArray);
2233 initFullExprCleanupWithFlag(ActiveFlag);
2234 }
2235
2236 pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2237 cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
2238 useEHCleanupForArray);
2239}
2240
2241/// emitDestroy - Immediately perform the destruction of the given
2242/// object.
2243///
2244/// \param addr - the address of the object; a type*
2245/// \param type - the type of the object; if an array type, all
2246/// objects are destroyed in reverse order
2247/// \param destroyer - the function to call to destroy individual
2248/// elements
2249/// \param useEHCleanupForArray - whether an EH cleanup should be
2250/// used when destroying array elements, in case one of the
2251/// destructions throws an exception
2253 Destroyer *destroyer,
2254 bool useEHCleanupForArray) {
2256 if (!arrayType)
2257 return destroyer(*this, addr, type);
2258
2259 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2260
2261 CharUnits elementAlign =
2262 addr.getAlignment()
2263 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2264
2265 // Normally we have to check whether the array is zero-length.
2266 bool checkZeroLength = true;
2267
2268 // But if the array length is constant, we can suppress that.
2269 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2270 // ...and if it's constant zero, we can just skip the entire thing.
2271 if (constLength->isZero()) return;
2272 checkZeroLength = false;
2273 }
2274
2275 llvm::Value *begin = addr.getPointer();
2276 llvm::Value *end =
2277 Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
2278 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2279 checkZeroLength, useEHCleanupForArray);
2280}
2281
2282/// emitArrayDestroy - Destroys all the elements of the given array,
2283/// beginning from last to first. The array cannot be zero-length.
2284///
2285/// \param begin - a type* denoting the first element of the array
2286/// \param end - a type* denoting one past the end of the array
2287/// \param elementType - the element type of the array
2288/// \param destroyer - the function to call to destroy elements
2289/// \param useEHCleanup - whether to push an EH cleanup to destroy
2290/// the remaining elements in case the destruction of a single
2291/// element throws
2292void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2293 llvm::Value *end,
2294 QualType elementType,
2295 CharUnits elementAlign,
2296 Destroyer *destroyer,
2297 bool checkZeroLength,
2298 bool useEHCleanup) {
2299 assert(!elementType->isArrayType());
2300
2301 // The basic structure here is a do-while loop, because we don't
2302 // need to check for the zero-element case.
2303 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2304 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2305
2306 if (checkZeroLength) {
2307 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2308 "arraydestroy.isempty");
2309 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2310 }
2311
2312 // Enter the loop body, making that address the current address.
2313 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2314 EmitBlock(bodyBB);
2315 llvm::PHINode *elementPast =
2316 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2317 elementPast->addIncoming(end, entryBB);
2318
2319 // Shift the address back by one element.
2320 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2321 llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
2322 llvm::Value *element = Builder.CreateInBoundsGEP(
2323 llvmElementType, elementPast, negativeOne, "arraydestroy.element");
2324
2325 if (useEHCleanup)
2326 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2327 destroyer);
2328
2329 // Perform the actual destruction there.
2330 destroyer(*this, Address(element, llvmElementType, elementAlign),
2331 elementType);
2332
2333 if (useEHCleanup)
2335
2336 // Check whether we've reached the end.
2337 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2338 Builder.CreateCondBr(done, doneBB, bodyBB);
2339 elementPast->addIncoming(element, Builder.GetInsertBlock());
2340
2341 // Done.
2342 EmitBlock(doneBB);
2343}
2344
2345/// Perform partial array destruction as if in an EH cleanup. Unlike
2346/// emitArrayDestroy, the element type here may still be an array type.
2348 llvm::Value *begin, llvm::Value *end,
2349 QualType type, CharUnits elementAlign,
2350 CodeGenFunction::Destroyer *destroyer) {
2351 llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
2352
2353 // If the element type is itself an array, drill down.
2354 unsigned arrayDepth = 0;
2355 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2356 // VLAs don't require a GEP index to walk into.
2357 if (!isa<VariableArrayType>(arrayType))
2358 arrayDepth++;
2359 type = arrayType->getElementType();
2360 }
2361
2362 if (arrayDepth) {
2363 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2364
2365 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2366 begin = CGF.Builder.CreateInBoundsGEP(
2367 elemTy, begin, gepIndices, "pad.arraybegin");
2368 end = CGF.Builder.CreateInBoundsGEP(
2369 elemTy, end, gepIndices, "pad.arrayend");
2370 }
2371
2372 // Destroy the array. We don't ever need an EH cleanup because we
2373 // assume that we're in an EH cleanup ourselves, so a throwing
2374 // destructor causes an immediate terminate.
2375 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2376 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2377}
2378
2379namespace {
2380 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2381 /// array destroy where the end pointer is regularly determined and
2382 /// does not need to be loaded from a local.
2383 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2384 llvm::Value *ArrayBegin;
2385 llvm::Value *ArrayEnd;
2386 QualType ElementType;
2387 CodeGenFunction::Destroyer *Destroyer;
2388 CharUnits ElementAlign;
2389 public:
2390 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2391 QualType elementType, CharUnits elementAlign,
2392 CodeGenFunction::Destroyer *destroyer)
2393 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2394 ElementType(elementType), Destroyer(destroyer),
2395 ElementAlign(elementAlign) {}
2396
2397 void Emit(CodeGenFunction &CGF, Flags flags) override {
2398 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2399 ElementType, ElementAlign, Destroyer);
2400 }
2401 };
2402
2403 /// IrregularPartialArrayDestroy - a cleanup which performs a
2404 /// partial array destroy where the end pointer is irregularly
2405 /// determined and must be loaded from a local.
2406 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2407 llvm::Value *ArrayBegin;
2408 Address ArrayEndPointer;
2409 QualType ElementType;
2410 CodeGenFunction::Destroyer *Destroyer;
2411 CharUnits ElementAlign;
2412 public:
2413 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2414 Address arrayEndPointer,
2415 QualType elementType,
2416 CharUnits elementAlign,
2417 CodeGenFunction::Destroyer *destroyer)
2418 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2419 ElementType(elementType), Destroyer(destroyer),
2420 ElementAlign(elementAlign) {}
2421
2422 void Emit(CodeGenFunction &CGF, Flags flags) override {
2423 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2424 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2425 ElementType, ElementAlign, Destroyer);
2426 }
2427 };
2428} // end anonymous namespace
2429
2430/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2431/// already-constructed elements of the given array. The cleanup
2432/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2433///
2434/// \param elementType - the immediate element type of the array;
2435/// possibly still an array type
2436void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2437 Address arrayEndPointer,
2438 QualType elementType,
2439 CharUnits elementAlign,
2440 Destroyer *destroyer) {
2441 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2442 arrayBegin, arrayEndPointer,
2443 elementType, elementAlign,
2444 destroyer);
2445}
2446
2447/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2448/// already-constructed elements of the given array. The cleanup
2449/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2450///
2451/// \param elementType - the immediate element type of the array;
2452/// possibly still an array type
2453void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2454 llvm::Value *arrayEnd,
2455 QualType elementType,
2456 CharUnits elementAlign,
2457 Destroyer *destroyer) {
2458 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2459 arrayBegin, arrayEnd,
2460 elementType, elementAlign,
2461 destroyer);
2462}
2463
2464/// Lazily declare the @llvm.lifetime.start intrinsic.
2466 if (LifetimeStartFn)
2467 return LifetimeStartFn;
2468 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2469 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2470 return LifetimeStartFn;
2471}
2472
2473/// Lazily declare the @llvm.lifetime.end intrinsic.
2475 if (LifetimeEndFn)
2476 return LifetimeEndFn;
2477 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2478 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2479 return LifetimeEndFn;
2480}
2481
2482namespace {
2483 /// A cleanup to perform a release of an object at the end of a
2484 /// function. This is used to balance out the incoming +1 of a
2485 /// ns_consumed argument when we can't reasonably do that just by
2486 /// not doing the initial retain for a __block argument.
2487 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2488 ConsumeARCParameter(llvm::Value *param,
2489 ARCPreciseLifetime_t precise)
2490 : Param(param), Precise(precise) {}
2491
2492 llvm::Value *Param;
2493 ARCPreciseLifetime_t Precise;
2494
2495 void Emit(CodeGenFunction &CGF, Flags flags) override {
2496 CGF.EmitARCRelease(Param, Precise);
2497 }
2498 };
2499} // end anonymous namespace
2500
2501/// Emit an alloca (or GlobalValue depending on target)
2502/// for the specified parameter and set up LocalDeclMap.
2503void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2504 unsigned ArgNo) {
2505 bool NoDebugInfo = false;
2506 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2507 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2508 "Invalid argument to EmitParmDecl");
2509
2510 // Set the name of the parameter's initial value to make IR easier to
2511 // read. Don't modify the names of globals.
2512 if (!isa<llvm::GlobalValue>(Arg.getAnyValue()))
2513 Arg.getAnyValue()->setName(D.getName());
2514
2515 QualType Ty = D.getType();
2516
2517 // Use better IR generation for certain implicit parameters.
2518 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2519 // The only implicit argument a block has is its literal.
2520 // This may be passed as an inalloca'ed value on Windows x86.
2521 if (BlockInfo) {
2522 llvm::Value *V = Arg.isIndirect()
2523 ? Builder.CreateLoad(Arg.getIndirectAddress())
2524 : Arg.getDirectValue();
2525 setBlockContextParameter(IPD, ArgNo, V);
2526 return;
2527 }
2528 // Suppressing debug info for ThreadPrivateVar parameters, else it hides
2529 // debug info of TLS variables.
2530 NoDebugInfo =
2531 (IPD->getParameterKind() == ImplicitParamKind::ThreadPrivateVar);
2532 }
2533
2534 Address DeclPtr = Address::invalid();
2535 Address AllocaPtr = Address::invalid();
2536 bool DoStore = false;
2537 bool IsScalar = hasScalarEvaluationKind(Ty);
2538 bool UseIndirectDebugAddress = false;
2539
2540 // If we already have a pointer to the argument, reuse the input pointer.
2541 if (Arg.isIndirect()) {
2542 DeclPtr = Arg.getIndirectAddress();
2543 DeclPtr = DeclPtr.withElementType(ConvertTypeForMem(Ty));
2544 // Indirect argument is in alloca address space, which may be different
2545 // from the default address space.
2546 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2547 auto *V = DeclPtr.getPointer();
2548 AllocaPtr = DeclPtr;
2549
2550 // For truly ABI indirect arguments -- those that are not `byval` -- store
2551 // the address of the argument on the stack to preserve debug information.
2552 ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
2553 if (ArgInfo.isIndirect())
2554 UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
2555 if (UseIndirectDebugAddress) {
2556 auto PtrTy = getContext().getPointerType(Ty);
2557 AllocaPtr = CreateMemTemp(PtrTy, getContext().getTypeAlignInChars(PtrTy),
2558 D.getName() + ".indirect_addr");
2559 EmitStoreOfScalar(V, AllocaPtr, /* Volatile */ false, PtrTy);
2560 }
2561
2562 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2563 auto DestLangAS =
2565 if (SrcLangAS != DestLangAS) {
2566 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2567 CGM.getDataLayout().getAllocaAddrSpace());
2568 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2569 auto *T = llvm::PointerType::get(getLLVMContext(), DestAS);
2570 DeclPtr =
2571 DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(
2572 *this, V, SrcLangAS, DestLangAS, T, true),
2573 DeclPtr.isKnownNonNull());
2574 }
2575
2576 // Push a destructor cleanup for this parameter if the ABI requires it.
2577 // Don't push a cleanup in a thunk for a method that will also emit a
2578 // cleanup.
2579 if (Ty->isRecordType() && !CurFuncIsThunk &&
2581 if (QualType::DestructionKind DtorKind =
2583 assert((DtorKind == QualType::DK_cxx_destructor ||
2584 DtorKind == QualType::DK_nontrivial_c_struct) &&
2585 "unexpected destructor type");
2586 pushDestroy(DtorKind, DeclPtr, Ty);
2587 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2589 }
2590 }
2591 } else {
2592 // Check if the parameter address is controlled by OpenMP runtime.
2593 Address OpenMPLocalAddr =
2594 getLangOpts().OpenMP
2596 : Address::invalid();
2597 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2598 DeclPtr = OpenMPLocalAddr;
2599 AllocaPtr = DeclPtr;
2600 } else {
2601 // Otherwise, create a temporary to hold the value.
2602 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2603 D.getName() + ".addr", &AllocaPtr);
2604 }
2605 DoStore = true;
2606 }
2607
2608 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2609
2610 LValue lv = MakeAddrLValue(DeclPtr, Ty);
2611 if (IsScalar) {
2612 Qualifiers qs = Ty.getQualifiers();
2614 // We honor __attribute__((ns_consumed)) for types with lifetime.
2615 // For __strong, it's handled by just skipping the initial retain;
2616 // otherwise we have to balance out the initial +1 with an extra
2617 // cleanup to do the release at the end of the function.
2618 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2619
2620 // If a parameter is pseudo-strong then we can omit the implicit retain.
2621 if (D.isARCPseudoStrong()) {
2622 assert(lt == Qualifiers::OCL_Strong &&
2623 "pseudo-strong variable isn't strong?");
2624 assert(qs.hasConst() && "pseudo-strong variable should be const!");
2626 }
2627
2628 // Load objects passed indirectly.
2629 if (Arg.isIndirect() && !ArgVal)
2630 ArgVal = Builder.CreateLoad(DeclPtr);
2631
2632 if (lt == Qualifiers::OCL_Strong) {
2633 if (!isConsumed) {
2634 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2635 // use objc_storeStrong(&dest, value) for retaining the
2636 // object. But first, store a null into 'dest' because
2637 // objc_storeStrong attempts to release its old value.
2638 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2639 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2640 EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
2641 DoStore = false;
2642 }
2643 else
2644 // Don't use objc_retainBlock for block pointers, because we
2645 // don't want to Block_copy something just because we got it
2646 // as a parameter.
2647 ArgVal = EmitARCRetainNonBlock(ArgVal);
2648 }
2649 } else {
2650 // Push the cleanup for a consumed parameter.
2651 if (isConsumed) {
2652 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2654 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2655 precise);
2656 }
2657
2658 if (lt == Qualifiers::OCL_Weak) {
2659 EmitARCInitWeak(DeclPtr, ArgVal);
2660 DoStore = false; // The weak init is a store, no need to do two.
2661 }
2662 }
2663
2664 // Enter the cleanup scope.
2665 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2666 }
2667 }
2668
2669 // Store the initial value into the alloca.
2670 if (DoStore)
2671 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2672
2673 setAddrOfLocalVar(&D, DeclPtr);
2674
2675 // Emit debug info for param declarations in non-thunk functions.
2676 if (CGDebugInfo *DI = getDebugInfo()) {
2678 !NoDebugInfo) {
2679 llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2680 &D, AllocaPtr.getPointer(), ArgNo, Builder, UseIndirectDebugAddress);
2681 if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
2682 DI->getParamDbgMappings().insert({Var, DILocalVar});
2683 }
2684 }
2685
2686 if (D.hasAttr<AnnotateAttr>())
2687 EmitVarAnnotations(&D, DeclPtr.getPointer());
2688
2689 // We can only check return value nullability if all arguments to the
2690 // function satisfy their nullability preconditions. This makes it necessary
2691 // to emit null checks for args in the function body itself.
2692 if (requiresReturnValueNullabilityCheck()) {
2693 auto Nullability = Ty->getNullability();
2694 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2695 SanitizerScope SanScope(this);
2696 RetValNullabilityPrecondition =
2697 Builder.CreateAnd(RetValNullabilityPrecondition,
2698 Builder.CreateIsNotNull(Arg.getAnyValue()));
2699 }
2700 }
2701}
2702
2704 CodeGenFunction *CGF) {
2705 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2706 return;
2708}
2709
2711 CodeGenFunction *CGF) {
2712 if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2713 (!LangOpts.EmitAllDecls && !D->isUsed()))
2714 return;
2716}
2717
2720}
2721
2723 for (const Expr *E : D->varlists()) {
2724 const auto *DE = cast<DeclRefExpr>(E);
2725 const auto *VD = cast<VarDecl>(DE->getDecl());
2726
2727 // Skip all but globals.
2728 if (!VD->hasGlobalStorage())
2729 continue;
2730
2731 // Check if the global has been materialized yet or not. If not, we are done
2732 // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2733 // we already emitted the global we might have done so before the
2734 // OMPAllocateDeclAttr was attached, leading to the wrong address space
2735 // (potentially). While not pretty, common practise is to remove the old IR
2736 // global and generate a new one, so we do that here too. Uses are replaced
2737 // properly.
2738 StringRef MangledName = getMangledName(VD);
2739 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2740 if (!Entry)
2741 continue;
2742
2743 // We can also keep the existing global if the address space is what we
2744 // expect it to be, if not, it is replaced.
2745 QualType ASTTy = VD->getType();
2747 auto TargetAS = getContext().getTargetAddressSpace(GVAS);
2748 if (Entry->getType()->getAddressSpace() == TargetAS)
2749 continue;
2750
2751 // Make a new global with the correct type / address space.
2752 llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
2753 llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
2754
2755 // Replace all uses of the old global with a cast. Since we mutate the type
2756 // in place we neeed an intermediate that takes the spot of the old entry
2757 // until we can create the cast.
2758 llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2759 getModule(), Entry->getValueType(), false,
2760 llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2761 llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2762 Entry->replaceAllUsesWith(DummyGV);
2763
2764 Entry->mutateType(PTy);
2765 llvm::Constant *NewPtrForOldDecl =
2766 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2767 Entry, DummyGV->getType());
2768
2769 // Now we have a casted version of the changed global, the dummy can be
2770 // replaced and deleted.
2771 DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
2772 DummyGV->eraseFromParent();
2773 }
2774}
2775
2776std::optional<CharUnits>
2778 if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
2779 if (Expr *Alignment = AA->getAlignment()) {
2780 unsigned UserAlign =
2781 Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
2782 CharUnits NaturalAlign =
2784
2785 // OpenMP5.1 pg 185 lines 7-10
2786 // Each item in the align modifier list must be aligned to the maximum
2787 // of the specified alignment and the type's natural alignment.
2789 std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));
2790 }
2791 }
2792 return std::nullopt;
2793}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3259
static void emitStoresForInitAfterBZero(CodeGenModule &CGM, llvm::Constant *Init, Address Loc, bool isVolatile, CGBuilderTy &Builder, bool IsAutoInit)
For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit the scalar stores that woul...
Definition: CGDecl.cpp:949
static bool isCapturedBy(const VarDecl &, const Expr *)
Determines whether the given __block variable is potentially captured by the given expression.
Definition: CGDecl.cpp:1696
static void emitPartialArrayDestroy(CodeGenFunction &CGF, llvm::Value *begin, llvm::Value *end, QualType type, CharUnits elementAlign, CodeGenFunction::Destroyer *destroyer)
Perform partial array destruction as if in an EH cleanup.
Definition: CGDecl.cpp:2347
static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D, Address Loc, bool isVolatile, CGBuilderTy &Builder)
Definition: CGDecl.cpp:1289
static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init, unsigned &NumStores)
Decide whether we can emit the non-zero parts of the specified initializer with equal or fewer than N...
Definition: CGDecl.cpp:911
static llvm::Constant * patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern, llvm::Type *Ty)
Generate a constant filled with either a pattern or zeroes.
Definition: CGDecl.cpp:1043
static llvm::Constant * constWithPadding(CodeGenModule &CGM, IsPattern isPattern, llvm::Constant *constant)
Replace all padding bytes in a given constant with either a pattern byte or 0x00.
Definition: CGDecl.cpp:1095
static llvm::Value * shouldUseMemSetToInitialize(llvm::Constant *Init, uint64_t GlobalSize, const llvm::DataLayout &DL)
Decide whether we should use memset to initialize a local variable instead of using a memcpy from a c...
Definition: CGDecl.cpp:1017
IsPattern
Definition: CGDecl.cpp:1040
static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D)
Definition: CGDecl.cpp:220
static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D, Address Loc, bool isVolatile, CGBuilderTy &Builder, llvm::Constant *constant, bool IsAutoInit)
Definition: CGDecl.cpp:1190
static bool shouldSplitConstantStore(CodeGenModule &CGM, uint64_t GlobalByteSize)
Decide whether we want to split a constant structure or array store into a sequence of its fields' st...
Definition: CGDecl.cpp:1029
static llvm::Constant * replaceUndef(CodeGenModule &CGM, IsPattern isPattern, llvm::Constant *constant)
Definition: CGDecl.cpp:1311
static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF, const LValue &destLV, const Expr *init)
Definition: CGDecl.cpp:715
static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init, uint64_t GlobalSize)
Decide whether we should use bzero plus some stores to initialize a local variable instead of using a...
Definition: CGDecl.cpp:996
static llvm::Constant * constStructWithPadding(CodeGenModule &CGM, IsPattern isPattern, llvm::StructType *STy, llvm::Constant *constant)
Helper function for constWithPadding() to deal with padding in structures.
Definition: CGDecl.cpp:1055
static bool containsUndef(llvm::Constant *constant)
Definition: CGDecl.cpp:1300
static bool isAccessedBy(const VarDecl &var, const Stmt *s)
Definition: CGDecl.cpp:683
static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, Address addr, Qualifiers::ObjCLifetime lifetime)
EmitAutoVarWithLifetime - Does the setup required for an automatic variable with lifetime.
Definition: CGDecl.cpp:647
static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM, const VarDecl &D, CGBuilderTy &Builder, llvm::Constant *Constant, CharUnits Align)
Definition: CGDecl.cpp:1181
static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D, Address Loc, bool isVolatile, CGBuilderTy &Builder)
Definition: CGDecl.cpp:1279
static void drillIntoBlockVariable(CodeGenFunction &CGF, LValue &lvalue, const VarDecl *var)
Definition: CGDecl.cpp:765
CodeGenFunction::ComplexPairTy ComplexPairTy
This file defines OpenMP nodes for declarative directives.
static const RecordType * getRecordType(QualType QT)
Checks that the passed in QualType either is of RecordType or points to RecordType.
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2985
Defines the SourceManager interface.
SourceLocation Begin
__device__ __2f16 float __ockl_bool s
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
IdentifierTable & Idents
Definition: ASTContext.h:639
const LangOptions & getLangOpts() const
Definition: ASTContext.h:770
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2745
unsigned getTargetAddressSpace(LangAS AS) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3147
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4459
ArrayRef< Capture > captures() const
Definition: Decl.h:4586
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6167
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1530
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2528
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1361
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2792
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
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
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
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
An aligned address.
Definition: Address.h:29
static Address invalid()
Definition: Address.h:46
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition: Address.h:78
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:62
Address withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Definition: Address.h:85
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:100
KnownNonNull_t isKnownNonNull() const
Whether the pointer is known not to be null.
Definition: Address.h:105
llvm::Value * getPointer() const
Definition: Address.h:51
bool isValid() const
Definition: Address.h:47
static AggValueSlot forLValue(const LValue &LV, CodeGenFunction &CGF, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition: CGValue.h:610
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:870
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:97
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:326
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:71
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:119
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:297
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:129
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:55
void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about a global variable.
Param2DILocTy & getParamDbgMappings()
Definition: CGDebugInfo.h:600
llvm::DILocalVariable * EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder, bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an argument variable declaration.
llvm::DILocalVariable * EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder, const bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an automatic variable declaration.
void setLocation(SourceLocation Loc)
Update the current source location.
void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr)
Register VLA size expression debug node with the qualified type.
Definition: CGDebugInfo.h:411
CGFunctionInfo - Class to encapsulate the information about a function definition.
const_arg_iterator arg_begin() const
MutableArrayRef< ArgInfo > arguments()
virtual void EmitWorkGroupLocalVarDecl(CodeGenFunction &CGF, const VarDecl &D)
Emit the IR required for a work-group-local variable declaration, and add an entry to CGF's LocalDecl...
Allows to disable automatic handling of functions used in target regions as those marked as omp decla...
virtual void getKmpcFreeShared(CodeGenFunction &CGF, const std::pair< llvm::Value *, llvm::Value * > &AddrSizePair)
Get call to __kmpc_free_shared.
void emitUserDefinedMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit the function for the user defined mapper construct.
virtual void processRequiresDirective(const OMPRequiresDecl *D)
Perform check on requires decl to ensure that target architecture supports unified addressing.
virtual std::pair< llvm::Value *, llvm::Value * > getKmpcAllocShared(CodeGenFunction &CGF, const VarDecl *VD)
Get call to __kmpc_alloc_shared.
virtual void emitUserDefinedReduction(CodeGenFunction *CGF, const OMPDeclareReductionDecl *D)
Emit code for the specified user defined reduction construct.
virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD)
Gets the OpenMP-specific address of the local variable.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:258
void add(RValue rvalue, QualType type)
Definition: CGCall.h:282
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void emitAutoVarTypeCleanup(const AutoVarEmission &emission, QualType::DestructionKind dtorKind)
void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags, bool LoadBlockVarAddr, bool CanThrow)
Enter a cleanup to destroy a __block variable.
llvm::Value * EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr)
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
static Destroyer destroyNonTrivialCStruct
static bool cxxDestructorCanThrow(QualType T)
Check if T is a C++ class that has a destructor that can throw.
SanitizerSet SanOpts
Sanitizers enabled for this function.
llvm::DenseMap< const VarDecl *, llvm::Value * > NRVOFlags
A mapping from NRVO variables to the flags used to indicate when the NRVO has been applied to this va...
void EmitARCMoveWeak(Address dst, Address src)
void EmitAutoVarDecl(const VarDecl &D)
EmitAutoVarDecl - Emit an auto variable declaration.
void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
static bool hasScalarEvaluationKind(QualType T)
const BlockByrefInfo & getBlockByrefInfo(const VarDecl *var)
void EmitDecl(const Decl &D)
EmitDecl - Emit a declaration.
void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, Address arrayEndPointer, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
void EmitExtendGCLifetime(llvm::Value *object)
EmitExtendGCLifetime - Given a pointer to an Objective-C object, make sure it survives garbage collec...
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
void pushEHDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, QualType elementType, CharUnits elementAlign, Destroyer *destroyer, bool checkZeroLength, bool useEHCleanup)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
const CodeGen::CGBlockInfo * BlockInfo
void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
EmitExprAsInit - Emits the code necessary to initialize a location in memory with the given initializ...
void emitByrefStructureInit(const AutoVarEmission &emission)
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
@ TCK_NonnullAssign
Checking the value assigned to a _Nonnull pointer. Must not be null.
llvm::Value * EmitARCStoreStrongCall(Address addr, llvm::Value *value, bool resultIgnored)
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **callOrInvoke, bool IsMustTail, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type,...
llvm::Type * ConvertTypeForMem(QualType T)
llvm::Value * EmitARCUnsafeUnretainedScalarExpr(const Expr *expr)
void EmitAutoVarInit(const AutoVarEmission &emission)
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
DominatingValue< T >::saved_type saveValueInCond(T value)
void EmitStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
void EmitAtomicInit(Expr *E, LValue lvalue)
const TargetInfo & getTarget() const
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit)
Emit code in this function to perform a guarded variable initialization.
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
void EmitARCCopyWeak(Address dst, Address src)
void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, llvm::Value *ptr)
void defaultInitNonTrivialCStructVar(LValue Dst)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, bool followForward=true)
BuildBlockByrefAddress - Computes the location of the data in a variable which is declared as __block...
LValue EmitDeclRefLValue(const DeclRefExpr *E)
AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD)
Determine whether a field initialization may overlap some other object.
Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
llvm::Value * EmitARCRetainAutoreleaseScalarExpr(const Expr *expr)
const TargetCodeGenInfo & getTargetHooks() const
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
void EmitVarDecl(const VarDecl &D)
EmitVarDecl - Emit a local variable declaration.
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
Address CreateMemTemp(QualType T, const Twine &Name="tmp", Address *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull.
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Address ReturnValuePointer
ReturnValuePointer - The temporary alloca to hold a pointer to sret.
void EmitAutoVarCleanups(const AutoVarEmission &emission)
llvm::GlobalVariable * AddInitializerToStaticVarDecl(const VarDecl &D, llvm::GlobalVariable *GV)
AddInitializerToStaticVarDecl - Add the initializer for 'D' to the global variable that has already b...
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
CleanupKind getCleanupKind(QualType::DestructionKind kind)
llvm::Type * ConvertType(QualType T)
void EmitARCInitWeak(Address addr, llvm::Value *value)
static Destroyer destroyARCStrongPrecise
void initFullExprCleanupWithFlag(Address ActiveFlag)
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
void pushStackRestore(CleanupKind kind, Address SPMem)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
const CGFunctionInfo * CurFnInfo
void pushKmpcAllocFree(CleanupKind Kind, std::pair< llvm::Value *, llvm::Value * > AddrSizePair)
void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
static Destroyer destroyARCStrongImprecise
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo)
Emits the alloca and debug information for the size expressions for each dimension of an array.
llvm::Value * EmitARCRetainScalarExpr(const Expr *expr)
void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, llvm::Value *arrayEnd, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
bool hasLabelBeenSeenInCurrentScope() const
Return true if a label was seen in the current scope.
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
llvm::Module & getModule() const
void setStaticLocalDeclAddress(const VarDecl *D, llvm::Constant *C)
llvm::Function * getLLVMLifetimeStartFn()
Lazily declare the @llvm.lifetime.start intrinsic.
Definition: CGDecl.cpp:2465
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant, CharUnits Align)
Definition: CGDecl.cpp:1131
llvm::Constant * getNullPointer(llvm::PointerType *T, QualType QT)
Get target specific null pointer.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
const LangOptions & getLangOpts() const
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
Definition: CGDecl.cpp:2722
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
const llvm::DataLayout & getDataLayout() const
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
SanitizerMetadata * getSanitizerMetadata()
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:243
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ASTContext & getContext() const
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
Definition: CGDecl.cpp:2710
llvm::Function * getLLVMLifetimeEndFn()
Lazily declare the @llvm.lifetime.end intrinsic.
Definition: CGDecl.cpp:2474
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
Definition: CGDecl.cpp:2718
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
Definition: CGDecl.cpp:2777
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
Definition: CGDecl.cpp:2703
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
const CGFunctionInfo & arrangeFunctionDeclaration(const FunctionDecl *FD)
Free functions are functions that are compatible with an ordinary C function pointer type.
Definition: CGCall.cpp:457
llvm::Type * ConvertTypeForMem(QualType T, bool ForBitField=false)
ConvertTypeForMem - Convert type T into a llvm::Type.
llvm::Constant * tryEmitAbstractForInitializer(const VarDecl &D)
Try to emit the initializer of the given declaration as an abstract constant.
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
ConditionalCleanup stores the saved form of its parameters, then restores them and performs the clean...
Definition: EHScopeStack.h:203
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:393
LValue - This represents an lvalue references.
Definition: CGValue.h:171
Address getAddress(CodeGenFunction &CGF) const
Definition: CGValue.h:350
llvm::Value * getPointer(CodeGenFunction &CGF) const
Definition: CGValue.h:346
QualType getType() const
Definition: CGValue.h:279
void setNonGC(bool Value)
Definition: CGValue.h:292
void setAddress(Address address)
Definition: CGValue.h:354
Qualifiers::ObjCLifetime getObjCLifetime() const
Definition: CGValue.h:281
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:39
static RValue get(llvm::Value *V)
Definition: CGValue.h:89
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:356
void reportGlobal(llvm::GlobalVariable *GV, const VarDecl &D, bool IsDynInit=false)
virtual llvm::Value * performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, llvm::Value *V, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Perform address space cast of an expression of pointer type.
Definition: TargetInfo.cpp:132
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition: TargetInfo.h:75
bool IsBypassed(const VarDecl *D) const
Returns true if the variable declaration was by bypassed by any goto or switch statement.
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1604
body_range body()
Definition: Stmt.h:1662
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
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:295
T * getAttr() const
Definition: DeclBase.h:578
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
Definition: DeclBase.cpp:1174
SourceLocation getLocation() const
Definition: DeclBase.h:444
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
DeclContext * getDeclContext()
Definition: DeclBase.h:453
bool hasAttr() const
Definition: DeclBase.h:582
Kind getKind() const
Definition: DeclBase.h:447
This represents one expression.
Definition: Expr.h:110
bool isXValue() const
Definition: Expr.h:279
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3050
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3041
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition: Expr.cpp:3273
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents a function declaration or definition.
Definition: Decl.h:1959
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
const Decl * getDecl() const
Definition: GlobalDecl.h:103
One of these records is kept for each identifier that is lexed.
IdentifierInfo & getOwn(StringRef Name)
Gets an IdentifierInfo for the given name without consulting external sources.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
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:292
bool isExternallyVisible() const
Definition: Decl.h:408
This represents '#pragma omp allocate ...' directive.
Definition: DeclOpenMP.h:473
varlist_range varlists()
Definition: DeclOpenMP.h:515
This represents '#pragma omp declare mapper ...' directive.
Definition: DeclOpenMP.h:287
This represents '#pragma omp declare reduction ...' directive.
Definition: DeclOpenMP.h:177
This represents '#pragma omp requires...' directive.
Definition: DeclOpenMP.h:416
A (possibly-)qualified type.
Definition: Type.h:737
@ DK_cxx_destructor
Definition: Type.h:1313
@ DK_nontrivial_c_struct
Definition: Type.h:1316
@ DK_objc_weak_lifetime
Definition: Type.h:1315
@ DK_objc_strong_lifetime
Definition: Type.h:1314
@ PDIK_Struct
The type is a struct containing a field whose type is not PCK_Trivial.
Definition: Type.h:1259
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7027
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:897
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6942
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1229
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7102
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition: Type.h:836
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2510
The collection of all-type qualifiers we support.
Definition: Type.h:147
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:164
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:181
bool hasConst() const
Definition: Type.h:264
ObjCLifetime getObjCLifetime() const
Definition: Type.h:352
bool isParamDestroyedInCallee() const
Definition: Decl.h:4275
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
static const uint64_t MaximumAlignment
Definition: Sema.h:970
Encodes a location in the source.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4377
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:287
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1291
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2289
bool isArrayType() const
Definition: Type.h:7220
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2438
bool isSamplerT() const
Definition: Type.h:7347
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
bool isRecordType() const
Definition: Type.h:7244
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4516
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1546
TLSKind getTLSKind() const
Definition: Decl.cpp:2165
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
Definition: Decl.cpp:2831
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1210
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2846
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:2463
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition: Decl.h:1489
bool isExceptionVariable() const
Determine whether this variable is the exception variable in a C++ catch statememt or an Objective-C ...
Definition: Decl.h:1471
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2820
const Expr * getInit() const
Definition: Decl.h:1352
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1201
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1524
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1168
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1237
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition: Decl.h:1213
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2675
Defines the clang::TargetInfo interface.
@ BLOCK_FIELD_IS_BYREF
Definition: CGBlocks.h:92
@ BLOCK_FIELD_IS_WEAK
Definition: CGBlocks.h:94
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
llvm::Constant * initializationPatternFor(CodeGenModule &, llvm::Type *)
Definition: PatternInit.cpp:15
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
ARCPreciseLifetime_t
Does an ARC strong l-value have precise lifetime?
Definition: CGValue.h:124
@ ARCPreciseLifetime
Definition: CGValue.h:125
@ ARCImpreciseLifetime
Definition: CGValue.h:125
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1809
bool Null(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1825
The JSON file list parser is used to communicate input to InstallAPI.
@ Ctor_Base
Base object ctor.
Definition: ABI.h:26
@ OpenCL
Definition: LangStandard.h:64
@ CPlusPlus
Definition: LangStandard.h:54
@ NonNull
Values of this type can never be null.
@ SC_Auto
Definition: Specifiers.h:253
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:325
@ Dtor_Base
Base object dtor.
Definition: ABI.h:36
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
@ ThreadPrivateVar
Parameter for Thread private variable.
float __ovld __cnfn length(float)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
static Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD)
Gets the OpenMP-specific address of the local variable /p VD.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::PointerType * AllocaInt8PtrTy
A metaprogramming class for ensuring that a value will dominate an arbitrary position in a function.
Definition: EHScopeStack.h:65
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:159