1 //===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with code generation of C++ declarations
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/Frontend/CodeGenOptions.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/Support/Path.h"
21 
22 using namespace clang;
23 using namespace CodeGen;
24 
25 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
26                          llvm::Constant *DeclPtr) {
27   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
28   assert(!D.getType()->isReferenceType() &&
29          "Should not call EmitDeclInit on a reference!");
30 
31   ASTContext &Context = CGF.getContext();
32 
33   CharUnits alignment = Context.getDeclAlign(&D);
34   QualType type = D.getType();
35   LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
36 
37   const Expr *Init = D.getInit();
38   switch (CGF.getEvaluationKind(type)) {
39   case TEK_Scalar: {
40     CodeGenModule &CGM = CGF.CGM;
41     if (lv.isObjCStrong())
42       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
43                                                 DeclPtr, D.getTLSKind());
44     else if (lv.isObjCWeak())
45       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
46                                               DeclPtr);
47     else
48       CGF.EmitScalarInit(Init, &D, lv, false);
49     return;
50   }
51   case TEK_Complex:
52     CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
53     return;
54   case TEK_Aggregate:
55     CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
56                                           AggValueSlot::DoesNotNeedGCBarriers,
57                                                   AggValueSlot::IsNotAliased));
58     return;
59   }
60   llvm_unreachable("bad evaluation kind");
61 }
62 
63 /// Emit code to cause the destruction of the given variable with
64 /// static storage duration.
65 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
66                             llvm::Constant *addr) {
67   CodeGenModule &CGM = CGF.CGM;
68 
69   // FIXME:  __attribute__((cleanup)) ?
70 
71   QualType type = D.getType();
72   QualType::DestructionKind dtorKind = type.isDestructedType();
73 
74   switch (dtorKind) {
75   case QualType::DK_none:
76     return;
77 
78   case QualType::DK_cxx_destructor:
79     break;
80 
81   case QualType::DK_objc_strong_lifetime:
82   case QualType::DK_objc_weak_lifetime:
83     // We don't care about releasing objects during process teardown.
84     assert(!D.getTLSKind() && "should have rejected this");
85     return;
86   }
87 
88   llvm::Constant *function;
89   llvm::Constant *argument;
90 
91   // Special-case non-array C++ destructors, where there's a function
92   // with the right signature that we can just call.
93   const CXXRecordDecl *record = nullptr;
94   if (dtorKind == QualType::DK_cxx_destructor &&
95       (record = type->getAsCXXRecordDecl())) {
96     assert(!record->hasTrivialDestructor());
97     CXXDestructorDecl *dtor = record->getDestructor();
98 
99     function = CGM.getAddrOfCXXStructor(dtor, StructorType::Complete);
100     argument = llvm::ConstantExpr::getBitCast(
101         addr, CGF.getTypes().ConvertType(type)->getPointerTo());
102 
103   // Otherwise, the standard logic requires a helper function.
104   } else {
105     function = CodeGenFunction(CGM)
106         .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind),
107                                CGF.needsEHCleanup(dtorKind), &D);
108     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
109   }
110 
111   CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
112 }
113 
114 /// Emit code to cause the variable at the given address to be considered as
115 /// constant from this point onwards.
116 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
117                               llvm::Constant *Addr) {
118   // Don't emit the intrinsic if we're not optimizing.
119   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
120     return;
121 
122   // Grab the llvm.invariant.start intrinsic.
123   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
124   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
125 
126   // Emit a call with the size in bytes of the object.
127   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
128   uint64_t Width = WidthChars.getQuantity();
129   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
130                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
131   CGF.Builder.CreateCall(InvariantStart, Args);
132 }
133 
134 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
135                                                llvm::Constant *DeclPtr,
136                                                bool PerformInit) {
137 
138   const Expr *Init = D.getInit();
139   QualType T = D.getType();
140 
141   if (!T->isReferenceType()) {
142     if (PerformInit)
143       EmitDeclInit(*this, D, DeclPtr);
144     if (CGM.isTypeConstant(D.getType(), true))
145       EmitDeclInvariant(*this, D, DeclPtr);
146     else
147       EmitDeclDestroy(*this, D, DeclPtr);
148     return;
149   }
150 
151   assert(PerformInit && "cannot have constant initializer which needs "
152          "destruction for reference");
153   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
154   RValue RV = EmitReferenceBindingToExpr(Init);
155   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
156 }
157 
158 /// Create a stub function, suitable for being passed to atexit,
159 /// which passes the given address to the given destructor function.
160 llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD,
161                                                   llvm::Constant *dtor,
162                                                   llvm::Constant *addr) {
163   // Get the destructor function type, void(*)(void).
164   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
165   SmallString<256> FnName;
166   {
167     llvm::raw_svector_ostream Out(FnName);
168     CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
169   }
170   llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
171                                                               VD.getLocation());
172 
173   CodeGenFunction CGF(CGM);
174 
175   CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn,
176                     CGM.getTypes().arrangeNullaryFunction(), FunctionArgList());
177 
178   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
179 
180  // Make sure the call and the callee agree on calling convention.
181   if (llvm::Function *dtorFn =
182         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
183     call->setCallingConv(dtorFn->getCallingConv());
184 
185   CGF.FinishFunction();
186 
187   return fn;
188 }
189 
190 /// Register a global destructor using the C atexit runtime function.
191 void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
192                                                    llvm::Constant *dtor,
193                                                    llvm::Constant *addr) {
194   // Create a function which calls the destructor.
195   llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
196 
197   // extern "C" int atexit(void (*f)(void));
198   llvm::FunctionType *atexitTy =
199     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
200 
201   llvm::Constant *atexit =
202     CGM.CreateRuntimeFunction(atexitTy, "atexit");
203   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
204     atexitFn->setDoesNotThrow();
205 
206   EmitNounwindRuntimeCall(atexit, dtorStub);
207 }
208 
209 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
210                                          llvm::GlobalVariable *DeclPtr,
211                                          bool PerformInit) {
212   // If we've been asked to forbid guard variables, emit an error now.
213   // This diagnostic is hard-coded for Darwin's use case;  we can find
214   // better phrasing if someone else needs it.
215   if (CGM.getCodeGenOpts().ForbidGuardVariables)
216     CGM.Error(D.getLocation(),
217               "this initialization requires a guard variable, which "
218               "the kernel does not support");
219 
220   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
221 }
222 
223 llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
224     llvm::FunctionType *FTy, const Twine &Name, SourceLocation Loc, bool TLS) {
225   llvm::Function *Fn =
226     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
227                            Name, &getModule());
228   if (!getLangOpts().AppleKext && !TLS) {
229     // Set the section if needed.
230     if (const char *Section = getTarget().getStaticInitSectionSpecifier())
231       Fn->setSection(Section);
232   }
233 
234   Fn->setCallingConv(getRuntimeCC());
235 
236   if (!getLangOpts().Exceptions)
237     Fn->setDoesNotThrow();
238 
239   if (!isInSanitizerBlacklist(Fn, Loc)) {
240     if (getLangOpts().Sanitize.Address)
241       Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
242     if (getLangOpts().Sanitize.Thread)
243       Fn->addFnAttr(llvm::Attribute::SanitizeThread);
244     if (getLangOpts().Sanitize.Memory)
245       Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
246   }
247 
248   return Fn;
249 }
250 
251 /// Create a global pointer to a function that will initialize a global
252 /// variable.  The user has requested that this pointer be emitted in a specific
253 /// section.
254 void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
255                                           llvm::GlobalVariable *GV,
256                                           llvm::Function *InitFunc,
257                                           InitSegAttr *ISA) {
258   llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
259       TheModule, InitFunc->getType(), /*isConstant=*/true,
260       llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
261   PtrArray->setSection(ISA->getSection());
262   addUsedGlobal(PtrArray);
263 
264   // If the GV is already in a comdat group, then we have to join it.
265   llvm::Comdat *C = GV->getComdat();
266 
267   // LinkOnce and Weak linkage are lowered down to a single-member comdat group.
268   // Make an explicit group so we can join it.
269   if (!C && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())) {
270     C = TheModule.getOrInsertComdat(GV->getName());
271     GV->setComdat(C);
272   }
273   if (C)
274     PtrArray->setComdat(C);
275 }
276 
277 void
278 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
279                                             llvm::GlobalVariable *Addr,
280                                             bool PerformInit) {
281   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
282   SmallString<256> FnName;
283   {
284     llvm::raw_svector_ostream Out(FnName);
285     getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
286   }
287 
288   // Create a variable initialization function.
289   llvm::Function *Fn =
290       CreateGlobalInitOrDestructFunction(FTy, FnName.str(), D->getLocation());
291 
292   auto *ISA = D->getAttr<InitSegAttr>();
293   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
294                                                           PerformInit);
295 
296   llvm::GlobalVariable *COMDATKey =
297       supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
298 
299   if (D->getTLSKind()) {
300     // FIXME: Should we support init_priority for thread_local?
301     // FIXME: Ideally, initialization of instantiated thread_local static data
302     // members of class templates should not trigger initialization of other
303     // entities in the TU.
304     // FIXME: We only need to register one __cxa_thread_atexit function for the
305     // entire TU.
306     CXXThreadLocalInits.push_back(Fn);
307     CXXThreadLocalInitVars.push_back(Addr);
308   } else if (PerformInit && ISA) {
309     EmitPointerToInitFunc(D, Addr, Fn, ISA);
310     DelayedCXXInitPosition.erase(D);
311   } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
312     OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
313     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
314     DelayedCXXInitPosition.erase(D);
315   } else if (isTemplateInstantiation(D->getTemplateSpecializationKind())) {
316     // C++ [basic.start.init]p2:
317     //   Definitions of explicitly specialized class template static data
318     //   members have ordered initialization. Other class template static data
319     //   members (i.e., implicitly or explicitly instantiated specializations)
320     //   have unordered initialization.
321     //
322     // As a consequence, we can put them into their own llvm.global_ctors entry.
323     //
324     // If the global is externally visible, put the initializer into a COMDAT
325     // group with the global being initialized.  On most platforms, this is a
326     // minor startup time optimization.  In the MS C++ ABI, there are no guard
327     // variables, so this COMDAT key is required for correctness.
328     AddGlobalCtor(Fn, 65535, COMDATKey);
329     DelayedCXXInitPosition.erase(D);
330   } else if (D->hasAttr<SelectAnyAttr>()) {
331     // SelectAny globals will be comdat-folded. Put the initializer into a COMDAT
332     // group associated with the global, so the initializers get folded too.
333     AddGlobalCtor(Fn, 65535, COMDATKey);
334     DelayedCXXInitPosition.erase(D);
335   } else {
336     llvm::DenseMap<const Decl *, unsigned>::iterator I =
337       DelayedCXXInitPosition.find(D);
338     if (I == DelayedCXXInitPosition.end()) {
339       CXXGlobalInits.push_back(Fn);
340     } else {
341       assert(CXXGlobalInits[I->second] == nullptr);
342       CXXGlobalInits[I->second] = Fn;
343       DelayedCXXInitPosition.erase(I);
344     }
345   }
346 }
347 
348 void CodeGenModule::EmitCXXThreadLocalInitFunc() {
349   getCXXABI().EmitThreadLocalInitFuncs(
350       *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
351 
352   CXXThreadLocalInits.clear();
353   CXXThreadLocalInitVars.clear();
354   CXXThreadLocals.clear();
355 }
356 
357 void
358 CodeGenModule::EmitCXXGlobalInitFunc() {
359   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
360     CXXGlobalInits.pop_back();
361 
362   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
363     return;
364 
365   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
366 
367 
368   // Create our global initialization function.
369   if (!PrioritizedCXXGlobalInits.empty()) {
370     SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
371     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
372                          PrioritizedCXXGlobalInits.end());
373     // Iterate over "chunks" of ctors with same priority and emit each chunk
374     // into separate function. Note - everything is sorted first by priority,
375     // second - by lex order, so we emit ctor functions in proper order.
376     for (SmallVectorImpl<GlobalInitData >::iterator
377            I = PrioritizedCXXGlobalInits.begin(),
378            E = PrioritizedCXXGlobalInits.end(); I != E; ) {
379       SmallVectorImpl<GlobalInitData >::iterator
380         PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
381 
382       LocalCXXGlobalInits.clear();
383       unsigned Priority = I->first.priority;
384       // Compute the function suffix from priority. Prepend with zeroes to make
385       // sure the function names are also ordered as priorities.
386       std::string PrioritySuffix = llvm::utostr(Priority);
387       // Priority is always <= 65535 (enforced by sema).
388       PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
389       llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
390           FTy, "_GLOBAL__I_" + PrioritySuffix);
391 
392       for (; I < PrioE; ++I)
393         LocalCXXGlobalInits.push_back(I->second);
394 
395       CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
396       AddGlobalCtor(Fn, Priority);
397     }
398   }
399 
400   SmallString<128> FileName;
401   SourceManager &SM = Context.getSourceManager();
402   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
403     // Include the filename in the symbol name. Including "sub_" matches gcc and
404     // makes sure these symbols appear lexicographically behind the symbols with
405     // priority emitted above.
406     FileName = llvm::sys::path::filename(MainFile->getName());
407   } else {
408     FileName = SmallString<128>("<null>");
409   }
410 
411   for (size_t i = 0; i < FileName.size(); ++i) {
412     // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
413     // to be the set of C preprocessing numbers.
414     if (!isPreprocessingNumberBody(FileName[i]))
415       FileName[i] = '_';
416   }
417 
418   llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
419       FTy, llvm::Twine("_GLOBAL__sub_I_", FileName));
420 
421   CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
422   AddGlobalCtor(Fn);
423 
424   CXXGlobalInits.clear();
425   PrioritizedCXXGlobalInits.clear();
426 }
427 
428 void CodeGenModule::EmitCXXGlobalDtorFunc() {
429   if (CXXGlobalDtors.empty())
430     return;
431 
432   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
433 
434   // Create our global destructor function.
435   llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a");
436 
437   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
438   AddGlobalDtor(Fn);
439 }
440 
441 /// Emit the code necessary to initialize the given global variable.
442 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
443                                                        const VarDecl *D,
444                                                  llvm::GlobalVariable *Addr,
445                                                        bool PerformInit) {
446   // Check if we need to emit debug info for variable initializer.
447   if (D->hasAttr<NoDebugAttr>())
448     DebugInfo = nullptr; // disable debug info indefinitely for this function
449 
450   StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
451                 getTypes().arrangeNullaryFunction(),
452                 FunctionArgList(), D->getLocation(),
453                 D->getInit()->getExprLoc());
454 
455   // Use guarded initialization if the global variable is weak. This
456   // occurs for, e.g., instantiated static data members and
457   // definitions explicitly marked weak.
458   if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
459     EmitCXXGuardedInit(*D, Addr, PerformInit);
460   } else {
461     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
462   }
463 
464   FinishFunction();
465 }
466 
467 void
468 CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
469                                            ArrayRef<llvm::Function *> Decls,
470                                            llvm::GlobalVariable *Guard) {
471   {
472     ArtificialLocation AL(*this, Builder);
473     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
474                   getTypes().arrangeNullaryFunction(), FunctionArgList());
475     // Emit an artificial location for this function.
476     AL.Emit();
477 
478     llvm::BasicBlock *ExitBlock = nullptr;
479     if (Guard) {
480       // If we have a guard variable, check whether we've already performed
481       // these initializations. This happens for TLS initialization functions.
482       llvm::Value *GuardVal = Builder.CreateLoad(Guard);
483       llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
484                                                  "guard.uninitialized");
485       // Mark as initialized before initializing anything else. If the
486       // initializers use previously-initialized thread_local vars, that's
487       // probably supposed to be OK, but the standard doesn't say.
488       Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
489       llvm::BasicBlock *InitBlock = createBasicBlock("init");
490       ExitBlock = createBasicBlock("exit");
491       Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
492       EmitBlock(InitBlock);
493     }
494 
495     RunCleanupsScope Scope(*this);
496 
497     // When building in Objective-C++ ARC mode, create an autorelease pool
498     // around the global initializers.
499     if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
500       llvm::Value *token = EmitObjCAutoreleasePoolPush();
501       EmitObjCAutoreleasePoolCleanup(token);
502     }
503 
504     for (unsigned i = 0, e = Decls.size(); i != e; ++i)
505       if (Decls[i])
506         EmitRuntimeCall(Decls[i]);
507 
508     Scope.ForceCleanup();
509 
510     if (ExitBlock) {
511       Builder.CreateBr(ExitBlock);
512       EmitBlock(ExitBlock);
513     }
514   }
515 
516   FinishFunction();
517 }
518 
519 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
520                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
521                                                 &DtorsAndObjects) {
522   {
523     ArtificialLocation AL(*this, Builder);
524     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
525                   getTypes().arrangeNullaryFunction(), FunctionArgList());
526     // Emit an artificial location for this function.
527     AL.Emit();
528 
529     // Emit the dtors, in reverse order from construction.
530     for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
531       llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
532       llvm::CallInst *CI = Builder.CreateCall(Callee,
533                                           DtorsAndObjects[e - i - 1].second);
534       // Make sure the call and the callee agree on calling convention.
535       if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
536         CI->setCallingConv(F->getCallingConv());
537     }
538   }
539 
540   FinishFunction();
541 }
542 
543 /// generateDestroyHelper - Generates a helper function which, when
544 /// invoked, destroys the given object.
545 llvm::Function *CodeGenFunction::generateDestroyHelper(
546     llvm::Constant *addr, QualType type, Destroyer *destroyer,
547     bool useEHCleanupForArray, const VarDecl *VD) {
548   FunctionArgList args;
549   ImplicitParamDecl dst(getContext(), nullptr, SourceLocation(), nullptr,
550                         getContext().VoidPtrTy);
551   args.push_back(&dst);
552 
553   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
554       getContext().VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
555   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
556   llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
557       FTy, "__cxx_global_array_dtor", VD->getLocation());
558 
559   StartFunction(VD, getContext().VoidTy, fn, FI, args);
560 
561   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
562 
563   FinishFunction();
564 
565   return fn;
566 }
567