1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Decl nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Type.h"
26 using namespace clang;
27 using namespace CodeGen;
30 void CodeGenFunction::EmitDecl(const Decl &D) {
31 switch (D.getKind()) {
32 default: assert(0 && "Unknown decl kind!");
34 assert(0 && "Parmdecls should not be in declstmts!");
35 case Decl::Function: // void X();
36 case Decl::Record: // struct/union/class X;
37 case Decl::Enum: // enum X;
38 case Decl::EnumConstant: // enum ? { X = ? }
39 case Decl::CXXRecord: // struct/union/class X; [C++]
40 case Decl::UsingDirective: // using X; [C++]
41 // None of these decls require codegen support.
45 const VarDecl &VD = cast<VarDecl>(D);
46 assert(VD.isBlockVarDecl() &&
47 "Should not see file-scope variables inside a function!");
48 return EmitBlockVarDecl(VD);
51 case Decl::Typedef: { // typedef int X;
52 const TypedefDecl &TD = cast<TypedefDecl>(D);
53 QualType Ty = TD.getUnderlyingType();
55 if (Ty->isVariablyModifiedType())
61 /// EmitBlockVarDecl - This method handles emission of any variable declaration
62 /// inside a function, including static vars etc.
63 void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
64 if (D.hasAttr<AsmLabelAttr>())
65 CGM.ErrorUnsupported(&D, "__asm__");
67 switch (D.getStorageClass()) {
70 case VarDecl::Register:
71 return EmitLocalBlockVarDecl(D);
73 return EmitStaticBlockVarDecl(D);
75 case VarDecl::PrivateExtern:
76 // Don't emit it now, allow it to be emitted lazily on its first use.
80 assert(0 && "Unknown storage class");
83 llvm::GlobalVariable *
84 CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
85 const char *Separator,
86 llvm::GlobalValue::LinkageTypes
88 QualType Ty = D.getType();
89 assert(Ty->isConstantSizeType() && "VLAs can't be static");
92 if (getContext().getLangOptions().CPlusPlus) {
93 Name = CGM.getMangledName(&D);
95 std::string ContextName;
96 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl))
97 ContextName = CGM.getMangledName(FD);
98 else if (isa<ObjCMethodDecl>(CurFuncDecl))
99 ContextName = CurFn->getName();
101 assert(0 && "Unknown context for block var decl");
103 Name = ContextName + Separator + D.getNameAsString();
106 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
107 llvm::GlobalVariable *GV =
108 new llvm::GlobalVariable(CGM.getModule(), LTy,
109 Ty.isConstant(getContext()), Linkage,
110 CGM.EmitNullConstant(D.getType()), Name, 0,
111 D.isThreadSpecified(), Ty.getAddressSpace());
112 GV->setAlignment(getContext().getDeclAlignInBytes(&D));
116 void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
117 llvm::Value *&DMEntry = LocalDeclMap[&D];
118 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
120 llvm::GlobalVariable *GV =
121 CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage);
123 // Store into LocalDeclMap before generating initializer to handle
124 // circular references.
127 // Make sure to evaluate VLA bounds now so that we have them for later.
129 // FIXME: Can this happen?
130 if (D.getType()->isVariablyModifiedType())
131 EmitVLASize(D.getType());
134 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
136 // If constant emission failed, then this should be a C++ static
139 if (!getContext().getLangOptions().CPlusPlus)
140 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
142 EmitStaticCXXBlockVarDeclInit(D, GV);
144 // The initializer may differ in type from the global. Rewrite
145 // the global to match the initializer. (We have to do this
146 // because some types, like unions, can't be completely represented
147 // in the LLVM type system.)
148 if (GV->getType() != Init->getType()) {
149 llvm::GlobalVariable *OldGV = GV;
151 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
153 OldGV->getLinkage(), Init, "",
154 0, D.isThreadSpecified(),
155 D.getType().getAddressSpace());
157 // Steal the name of the old global
160 // Replace all uses of the old global with the new global
161 llvm::Constant *NewPtrForOldDecl =
162 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
163 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
165 // Erase the old global, since it is no longer used.
166 OldGV->eraseFromParent();
169 GV->setInitializer(Init);
173 // FIXME: Merge attribute handling.
174 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
175 SourceManager &SM = CGM.getContext().getSourceManager();
176 llvm::Constant *Ann =
177 CGM.EmitAnnotateAttr(GV, AA,
178 SM.getInstantiationLineNumber(D.getLocation()));
179 CGM.AddAnnotation(Ann);
182 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
183 GV->setSection(SA->getName());
185 if (D.hasAttr<UsedAttr>())
186 CGM.AddUsedGlobal(GV);
188 // We may have to cast the constant because of the initializer
191 // FIXME: It is really dangerous to store this in the map; if anyone
192 // RAUW's the GV uses of this constant will be invalid.
193 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
194 const llvm::Type *LPtrTy =
195 llvm::PointerType::get(LTy, D.getType().getAddressSpace());
196 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
198 // Emit global variable debug descriptor for static vars.
199 CGDebugInfo *DI = getDebugInfo();
201 DI->setLocation(D.getLocation());
202 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
206 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
207 assert(ByRefValueInfo.count(VD) && "Did not find value!");
209 return ByRefValueInfo.find(VD)->second.second;
212 /// BuildByRefType - This routine changes a __block variable declared as T x
217 /// void *__forwarding;
220 /// void *__copy_helper; // only if needed
221 /// void *__destroy_helper; // only if needed
222 /// char padding[X]; // only if needed
226 const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
227 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
231 QualType Ty = D->getType();
233 std::vector<const llvm::Type *> Types;
235 const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
237 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
240 Types.push_back(Int8PtrTy);
242 // void *__forwarding;
243 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
246 Types.push_back(llvm::Type::getInt32Ty(VMContext));
249 Types.push_back(llvm::Type::getInt32Ty(VMContext));
251 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
252 if (HasCopyAndDispose) {
253 /// void *__copy_helper;
254 Types.push_back(Int8PtrTy);
256 /// void *__destroy_helper;
257 Types.push_back(Int8PtrTy);
261 unsigned Align = getContext().getDeclAlignInBytes(D);
262 if (Align > Target.getPointerAlign(0) / 8) {
263 // We have to insert padding.
265 // The struct above has 2 32-bit integers.
266 unsigned CurrentOffsetInBytes = 4 * 2;
268 // And either 2 or 4 pointers.
269 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
270 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
273 unsigned AlignedOffsetInBytes =
274 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align);
276 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
277 if (NumPaddingBytes > 0) {
278 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
279 // FIXME: We need a sema error for alignment larger than the minimum of
280 // the maximal stack alignmint and the alignment of malloc on the system.
281 if (NumPaddingBytes > 1)
282 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
286 // We want a packed struct.
292 Types.push_back(ConvertType(Ty));
294 const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
296 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
297 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
298 ByRefTypeHolder.get());
300 Info.first = ByRefTypeHolder.get();
302 Info.second = Types.size() - 1;
307 /// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
308 /// variable declaration with auto, register, or no storage class specifier.
309 /// These turn into simple stack objects, or GlobalValues depending on target.
310 void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
311 QualType Ty = D.getType();
312 bool isByRef = D.hasAttr<BlocksAttr>();
313 bool needsDispose = false;
316 llvm::Value *DeclPtr;
317 if (Ty->isConstantSizeType()) {
318 if (!Target.useGlobalsForAutomaticVariables()) {
319 // A normal fixed sized variable becomes an alloca in the entry block.
320 const llvm::Type *LTy = ConvertTypeForMem(Ty);
321 Align = getContext().getDeclAlignInBytes(&D);
323 LTy = BuildByRefType(&D);
324 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
325 Alloc->setName(D.getNameAsString().c_str());
328 Align = std::max(Align, unsigned(Target.getPointerAlign(0) / 8));
329 Alloc->setAlignment(Align);
332 // Targets that don't support recursion emit locals as globals.
334 D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
335 DeclPtr = CreateStaticBlockVarDecl(D, Class,
340 // FIXME: Can this happen?
341 if (Ty->isVariablyModifiedType())
346 if (!DidCallStackSave) {
348 const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext);
349 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
351 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
352 llvm::Value *V = Builder.CreateCall(F);
354 Builder.CreateStore(V, Stack);
356 DidCallStackSave = true;
359 // Push a cleanup block and restore the stack there.
360 CleanupScope scope(*this);
362 V = Builder.CreateLoad(Stack, "tmp");
363 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
364 Builder.CreateCall(F, V);
368 // Get the element type.
369 const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
370 const llvm::Type *LElemPtrTy =
371 llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
373 llvm::Value *VLASize = EmitVLASize(Ty);
375 // Downcast the VLA size expression
376 VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext),
379 // Allocate memory for the array.
380 llvm::AllocaInst *VLA =
381 Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla");
382 VLA->setAlignment(getContext().getDeclAlignInBytes(&D));
384 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
387 llvm::Value *&DMEntry = LocalDeclMap[&D];
388 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
391 // Emit debug info for local var declaration.
392 if (CGDebugInfo *DI = getDebugInfo()) {
393 assert(HaveInsertPoint() && "Unexpected unreachable point!");
395 DI->setLocation(D.getLocation());
396 if (Target.useGlobalsForAutomaticVariables()) {
397 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
399 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
402 // If this local has an initializer, emit it now.
403 const Expr *Init = D.getInit();
405 // If we are at an unreachable point, we don't need to emit the initializer
406 // unless it contains a label.
407 if (!HaveInsertPoint()) {
408 if (!ContainsLabel(Init))
415 llvm::Value *Loc = DeclPtr;
417 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
418 D.getNameAsString());
420 if (Ty->isReferenceType()) {
421 RValue RV = EmitReferenceBindingToExpr(Init, Ty, /*IsInitializer=*/true);
422 EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Ty);
423 } else if (!hasAggregateLLVMType(Init->getType())) {
424 llvm::Value *V = EmitScalarExpr(Init);
425 EmitStoreOfScalar(V, Loc, D.getType().isVolatileQualified(),
427 } else if (Init->getType()->isAnyComplexType()) {
428 EmitComplexExprIntoAddr(Init, Loc, D.getType().isVolatileQualified());
430 EmitAggExpr(Init, Loc, D.getType().isVolatileQualified());
435 const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext);
438 llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
439 llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
440 llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
441 llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
448 if (Ty->isBlockPointerType()) {
449 flag |= BLOCK_FIELD_IS_BLOCK;
450 flags |= BLOCK_HAS_COPY_DISPOSE;
451 } else if (BlockRequiresCopying(Ty)) {
452 flag |= BLOCK_FIELD_IS_OBJECT;
453 flags |= BLOCK_HAS_COPY_DISPOSE;
456 // FIXME: Someone double check this.
457 if (Ty.isObjCGCWeak())
458 flag |= BLOCK_FIELD_IS_WEAK;
461 if (flag&BLOCK_FIELD_IS_WEAK)
463 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), isa);
464 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
465 Builder.CreateStore(V, isa_field);
467 Builder.CreateStore(DeclPtr, forwarding_field);
469 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), flags);
470 Builder.CreateStore(V, flags_field);
472 const llvm::Type *V1;
473 V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
474 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
475 (CGM.getTargetData().getTypeStoreSizeInBits(V1)
477 Builder.CreateStore(V, size_field);
479 if (flags & BLOCK_HAS_COPY_DISPOSE) {
480 BlockHasCopyDispose = true;
481 llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
482 Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag, Align),
485 llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
486 Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
492 // Handle CXX destruction of variables.
494 if (const ArrayType *Array = DtorTy->getAs<ArrayType>())
495 DtorTy = Array->getElementType();
496 if (const RecordType *RT = DtorTy->getAs<RecordType>())
497 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
498 if (!ClassDecl->hasTrivialDestructor()) {
499 const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext());
500 assert(D && "EmitLocalBlockVarDecl - destructor is nul");
501 assert(!Ty->getAs<ArrayType>() && "FIXME - destruction of arrays NYI");
503 CleanupScope scope(*this);
504 EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr);
508 // Handle the cleanup attribute
509 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
510 const FunctionDecl *FD = CA->getFunctionDecl();
512 llvm::Constant* F = CGM.GetAddrOfFunction(FD);
513 assert(F && "Could not find function!");
515 CleanupScope scope(*this);
517 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
519 // In some cases, the type of the function argument will be different from
520 // the type of the pointer. An example of this is
521 // void f(void* arg);
522 // __attribute__((cleanup(f))) void *g;
524 // To fix this we insert a bitcast here.
525 QualType ArgTy = Info.arg_begin()->type;
526 DeclPtr = Builder.CreateBitCast(DeclPtr, ConvertType(ArgTy));
529 Args.push_back(std::make_pair(RValue::get(DeclPtr),
530 getContext().getPointerType(D.getType())));
532 EmitCall(Info, F, Args);
535 if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) {
536 CleanupScope scope(*this);
537 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
538 V = Builder.CreateLoad(V, false);
539 BuildBlockRelease(V);
543 /// Emit an alloca (or GlobalValue depending on target)
544 /// for the specified parameter and set up LocalDeclMap.
545 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
546 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
547 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
548 "Invalid argument to EmitParmDecl");
549 QualType Ty = D.getType();
551 llvm::Value *DeclPtr;
552 if (!Ty->isConstantSizeType()) {
553 // Variable sized values always are passed by-reference.
556 // A fixed sized single-value variable becomes an alloca in the entry block.
557 const llvm::Type *LTy = ConvertTypeForMem(Ty);
558 if (LTy->isSingleValueType()) {
560 std::string Name = D.getNameAsString();
562 DeclPtr = CreateTempAlloca(LTy);
563 DeclPtr->setName(Name.c_str());
565 // Store the initial value into the alloca.
566 EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(), Ty);
568 // Otherwise, if this is an aggregate, just use the input pointer.
571 Arg->setName(D.getNameAsString());
574 llvm::Value *&DMEntry = LocalDeclMap[&D];
575 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
578 // Emit debug info for param declaration.
579 if (CGDebugInfo *DI = getDebugInfo()) {
580 DI->setLocation(D.getLocation());
581 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);