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