1 //===--- CGDecl.cpp - Emit LLVM Code for 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 to emit Decl nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
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;
28 
29 
30 void CodeGenFunction::EmitDecl(const Decl &D) {
31   switch (D.getKind()) {
32   default: assert(0 && "Unknown decl kind!");
33   case Decl::ParmVar:
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     // None of these decls require codegen support.
41     return;
42 
43   case Decl::Var: {
44     const VarDecl &VD = cast<VarDecl>(D);
45     assert(VD.isBlockVarDecl() &&
46            "Should not see file-scope variables inside a function!");
47     return EmitBlockVarDecl(VD);
48   }
49 
50   case Decl::Typedef: {   // typedef int X;
51     const TypedefDecl &TD = cast<TypedefDecl>(D);
52     QualType Ty = TD.getUnderlyingType();
53 
54     if (Ty->isVariablyModifiedType())
55       EmitVLASize(Ty);
56   }
57   }
58 }
59 
60 /// EmitBlockVarDecl - This method handles emission of any variable declaration
61 /// inside a function, including static vars etc.
62 void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
63   if (D.hasAttr<AsmLabelAttr>())
64     CGM.ErrorUnsupported(&D, "__asm__");
65 
66   switch (D.getStorageClass()) {
67   case VarDecl::None:
68   case VarDecl::Auto:
69   case VarDecl::Register:
70     return EmitLocalBlockVarDecl(D);
71   case VarDecl::Static:
72     return EmitStaticBlockVarDecl(D);
73   case VarDecl::Extern:
74   case VarDecl::PrivateExtern:
75     // Don't emit it now, allow it to be emitted lazily on its first use.
76     return;
77   }
78 
79   assert(0 && "Unknown storage class");
80 }
81 
82 llvm::GlobalVariable *
83 CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
84                                           const char *Separator,
85                                           llvm::GlobalValue::LinkageTypes
86                                           Linkage) {
87   QualType Ty = D.getType();
88   assert(Ty->isConstantSizeType() && "VLAs can't be static");
89 
90   std::string Name;
91   if (getContext().getLangOptions().CPlusPlus) {
92     Name = CGM.getMangledName(&D);
93   } else {
94     std::string ContextName;
95     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl))
96       ContextName = CGM.getMangledName(FD);
97     else if (isa<ObjCMethodDecl>(CurFuncDecl))
98       ContextName = CurFn->getName();
99     else
100       assert(0 && "Unknown context for block var decl");
101 
102     Name = ContextName + Separator + D.getNameAsString();
103   }
104 
105   const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
106   return new llvm::GlobalVariable(CGM.getModule(), LTy,
107                                   Ty.isConstant(getContext()), Linkage,
108                                   CGM.EmitNullConstant(D.getType()), Name, 0,
109                                   D.isThreadSpecified(), Ty.getAddressSpace());
110 }
111 
112 void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
113   llvm::Value *&DMEntry = LocalDeclMap[&D];
114   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
115 
116   llvm::GlobalVariable *GV =
117     CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage);
118 
119   // Store into LocalDeclMap before generating initializer to handle
120   // circular references.
121   DMEntry = GV;
122 
123   // Make sure to evaluate VLA bounds now so that we have them for later.
124   //
125   // FIXME: Can this happen?
126   if (D.getType()->isVariablyModifiedType())
127     EmitVLASize(D.getType());
128 
129   if (D.getType()->isReferenceType()) {
130     CGM.ErrorUnsupported(&D, "static declaration with reference type");
131     return;
132   }
133 
134   if (D.getInit()) {
135     llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
136 
137     // If constant emission failed, then this should be a C++ static
138     // initializer.
139     if (!Init) {
140       if (!getContext().getLangOptions().CPlusPlus)
141         CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
142       else
143         GenerateStaticCXXBlockVarDeclInit(D, GV);
144     } else {
145       // The initializer may differ in type from the global. Rewrite
146       // the global to match the initializer.  (We have to do this
147       // because some types, like unions, can't be completely represented
148       // in the LLVM type system.)
149       if (GV->getType() != Init->getType()) {
150         llvm::GlobalVariable *OldGV = GV;
151 
152         GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
153                                       OldGV->isConstant(),
154                                       OldGV->getLinkage(), Init, "",
155                                       0, D.isThreadSpecified(),
156                                       D.getType().getAddressSpace());
157 
158         // Steal the name of the old global
159         GV->takeName(OldGV);
160 
161         // Replace all uses of the old global with the new global
162         llvm::Constant *NewPtrForOldDecl =
163           llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
164         OldGV->replaceAllUsesWith(NewPtrForOldDecl);
165 
166         // Erase the old global, since it is no longer used.
167         OldGV->eraseFromParent();
168       }
169 
170       GV->setInitializer(Init);
171     }
172   }
173 
174   // FIXME: Merge attribute handling.
175   if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
176     SourceManager &SM = CGM.getContext().getSourceManager();
177     llvm::Constant *Ann =
178       CGM.EmitAnnotateAttr(GV, AA,
179                            SM.getInstantiationLineNumber(D.getLocation()));
180     CGM.AddAnnotation(Ann);
181   }
182 
183   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
184     GV->setSection(SA->getName());
185 
186   if (D.hasAttr<UsedAttr>())
187     CGM.AddUsedGlobal(GV);
188 
189   // We may have to cast the constant because of the initializer
190   // mismatch above.
191   //
192   // FIXME: It is really dangerous to store this in the map; if anyone
193   // RAUW's the GV uses of this constant will be invalid.
194   const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
195   const llvm::Type *LPtrTy =
196     llvm::PointerType::get(LTy, D.getType().getAddressSpace());
197   DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
198 
199   // Emit global variable debug descriptor for static vars.
200   CGDebugInfo *DI = getDebugInfo();
201   if (DI) {
202     DI->setLocation(D.getLocation());
203     DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
204   }
205 }
206 
207 /// BuildByRefType - This routine changes a __block variable declared as T x
208 ///   into:
209 ///
210 ///      struct {
211 ///        void *__isa;
212 ///        void *__forwarding;
213 ///        int32_t __flags;
214 ///        int32_t __size;
215 ///        void *__copy_helper;
216 ///        void *__destroy_helper;
217 ///        T x;
218 ///      } x
219 ///
220 /// Align is the alignment needed in bytes for x.
221 const llvm::Type *CodeGenFunction::BuildByRefType(QualType Ty,
222                                                   uint64_t Align) {
223   const llvm::Type *LTy = ConvertType(Ty);
224   bool needsCopyDispose = BlockRequiresCopying(Ty);
225   std::vector<const llvm::Type *> Types(needsCopyDispose*2+5);
226   const llvm::PointerType *PtrToInt8Ty
227     = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
228   Types[0] = PtrToInt8Ty;
229   Types[1] = PtrToInt8Ty;
230   Types[2] = llvm::Type::Int32Ty;
231   Types[3] = llvm::Type::Int32Ty;
232   if (needsCopyDispose) {
233     Types[4] = PtrToInt8Ty;
234     Types[5] = PtrToInt8Ty;
235   }
236   // FIXME: Align this on at least an Align boundary, assert if we can't.
237   assert((Align <= unsigned(Target.getPointerAlign(0))/8)
238          && "Can't align more than pointer yet");
239   Types[needsCopyDispose*2 + 4] = LTy;
240   return llvm::StructType::get(Types, false);
241 }
242 
243 /// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
244 /// variable declaration with auto, register, or no storage class specifier.
245 /// These turn into simple stack objects, or GlobalValues depending on target.
246 void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
247   QualType Ty = D.getType();
248   bool isByRef = D.hasAttr<BlocksAttr>();
249   bool needsDispose = false;
250   unsigned Align = 0;
251 
252   llvm::Value *DeclPtr;
253   if (Ty->isConstantSizeType()) {
254     if (!Target.useGlobalsForAutomaticVariables()) {
255       // A normal fixed sized variable becomes an alloca in the entry block.
256       const llvm::Type *LTy = ConvertTypeForMem(Ty);
257       Align = getContext().getDeclAlignInBytes(&D);
258       if (isByRef)
259         LTy = BuildByRefType(Ty, Align);
260       llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
261       Alloc->setName(D.getNameAsString().c_str());
262 
263       if (isByRef)
264         Align = std::max(Align, unsigned(Target.getPointerAlign(0) / 8));
265       Alloc->setAlignment(Align);
266       DeclPtr = Alloc;
267     } else {
268       // Targets that don't support recursion emit locals as globals.
269       const char *Class =
270         D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
271       DeclPtr = CreateStaticBlockVarDecl(D, Class,
272                                          llvm::GlobalValue
273                                          ::InternalLinkage);
274     }
275 
276     // FIXME: Can this happen?
277     if (Ty->isVariablyModifiedType())
278       EmitVLASize(Ty);
279   } else {
280     EnsureInsertPoint();
281 
282     if (!DidCallStackSave) {
283       // Save the stack.
284       const llvm::Type *LTy =
285         llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
286       llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
287 
288       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
289       llvm::Value *V = Builder.CreateCall(F);
290 
291       Builder.CreateStore(V, Stack);
292 
293       DidCallStackSave = true;
294 
295       {
296         // Push a cleanup block and restore the stack there.
297         CleanupScope scope(*this);
298 
299         V = Builder.CreateLoad(Stack, "tmp");
300         llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
301         Builder.CreateCall(F, V);
302       }
303     }
304 
305     // Get the element type.
306     const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
307     const llvm::Type *LElemPtrTy =
308       llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
309 
310     llvm::Value *VLASize = EmitVLASize(Ty);
311 
312     // Downcast the VLA size expression
313     VLASize = Builder.CreateIntCast(VLASize, llvm::Type::Int32Ty, false, "tmp");
314 
315     // Allocate memory for the array.
316     llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla");
317     DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
318   }
319 
320   llvm::Value *&DMEntry = LocalDeclMap[&D];
321   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
322   DMEntry = DeclPtr;
323 
324   // Emit debug info for local var declaration.
325   if (CGDebugInfo *DI = getDebugInfo()) {
326     assert(HaveInsertPoint() && "Unexpected unreachable point!");
327 
328     DI->setLocation(D.getLocation());
329     if (Target.useGlobalsForAutomaticVariables()) {
330       DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
331     } else if (isByRef) {
332       llvm::Value *Loc;
333       bool needsCopyDispose = BlockRequiresCopying(Ty);
334       Loc = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
335       Loc = Builder.CreateLoad(Loc, false);
336       Loc = Builder.CreateBitCast(Loc, DeclPtr->getType());
337       Loc = Builder.CreateStructGEP(Loc, needsCopyDispose*2+4, "x");
338       DI->EmitDeclareOfAutoVariable(&D, Loc, Builder);
339     } else
340       DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
341   }
342 
343   // If this local has an initializer, emit it now.
344   const Expr *Init = D.getInit();
345 
346   // If we are at an unreachable point, we don't need to emit the initializer
347   // unless it contains a label.
348   if (!HaveInsertPoint()) {
349     if (!ContainsLabel(Init))
350       Init = 0;
351     else
352       EnsureInsertPoint();
353   }
354 
355   if (Init) {
356     llvm::Value *Loc = DeclPtr;
357     if (isByRef) {
358       bool needsCopyDispose = BlockRequiresCopying(Ty);
359       Loc = Builder.CreateStructGEP(DeclPtr, needsCopyDispose*2+4, "x");
360     }
361     if (Ty->isReferenceType()) {
362       llvm::Value *V = EmitReferenceBindingToExpr(Init, Ty).getScalarVal();
363       EmitStoreOfScalar(V, Loc, false, Ty);
364     } else if (!hasAggregateLLVMType(Init->getType())) {
365       llvm::Value *V = EmitScalarExpr(Init);
366       EmitStoreOfScalar(V, Loc, D.getType().isVolatileQualified(),
367                         D.getType());
368     } else if (Init->getType()->isAnyComplexType()) {
369       EmitComplexExprIntoAddr(Init, Loc, D.getType().isVolatileQualified());
370     } else {
371       EmitAggExpr(Init, Loc, D.getType().isVolatileQualified());
372     }
373   }
374 
375   if (isByRef) {
376     const llvm::PointerType *PtrToInt8Ty
377       = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
378 
379     EnsureInsertPoint();
380     llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
381     llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
382     llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
383     llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
384     llvm::Value *V;
385     int flag = 0;
386     int flags = 0;
387 
388     needsDispose = true;
389 
390     if (Ty->isBlockPointerType()) {
391       flag |= BLOCK_FIELD_IS_BLOCK;
392       flags |= BLOCK_HAS_COPY_DISPOSE;
393     } else if (BlockRequiresCopying(Ty)) {
394       flag |= BLOCK_FIELD_IS_OBJECT;
395       flags |= BLOCK_HAS_COPY_DISPOSE;
396     }
397 
398     // FIXME: Someone double check this.
399     if (Ty.isObjCGCWeak())
400       flag |= BLOCK_FIELD_IS_WEAK;
401 
402     int isa = 0;
403     if (flag&BLOCK_FIELD_IS_WEAK)
404       isa = 1;
405     V = llvm::ConstantInt::get(llvm::Type::Int32Ty, isa);
406     V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
407     Builder.CreateStore(V, isa_field);
408 
409     V = Builder.CreateBitCast(DeclPtr, PtrToInt8Ty, "forwarding");
410     Builder.CreateStore(V, forwarding_field);
411 
412     V = llvm::ConstantInt::get(llvm::Type::Int32Ty, flags);
413     Builder.CreateStore(V, flags_field);
414 
415     const llvm::Type *V1;
416     V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
417     V = llvm::ConstantInt::get(llvm::Type::Int32Ty,
418                                (CGM.getTargetData().getTypeStoreSizeInBits(V1)
419                                 / 8));
420     Builder.CreateStore(V, size_field);
421 
422     if (flags & BLOCK_HAS_COPY_DISPOSE) {
423       BlockHasCopyDispose = true;
424       llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
425       Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag, Align),
426                           copy_helper);
427 
428       llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
429       Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
430                                                   Align),
431                           destroy_helper);
432     }
433   }
434 
435   // Handle CXX destruction of variables.
436   QualType DtorTy(Ty);
437   if (const ArrayType *Array = DtorTy->getAs<ArrayType>())
438     DtorTy = Array->getElementType();
439   if (const RecordType *RT = DtorTy->getAs<RecordType>())
440     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
441       if (!ClassDecl->hasTrivialDestructor()) {
442         const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext());
443         assert(D && "EmitLocalBlockVarDecl - destructor is nul");
444         assert(!Ty->getAs<ArrayType>() && "FIXME - destruction of arrays NYI");
445 
446         CleanupScope scope(*this);
447         EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr);
448       }
449   }
450 
451   // Handle the cleanup attribute
452   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
453     const FunctionDecl *FD = CA->getFunctionDecl();
454 
455     llvm::Constant* F = CGM.GetAddrOfFunction(GlobalDecl(FD));
456     assert(F && "Could not find function!");
457 
458     CleanupScope scope(*this);
459 
460     const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
461 
462     // In some cases, the type of the function argument will be different from
463     // the type of the pointer. An example of this is
464     // void f(void* arg);
465     // __attribute__((cleanup(f))) void *g;
466     //
467     // To fix this we insert a bitcast here.
468     QualType ArgTy = Info.arg_begin()->type;
469     DeclPtr = Builder.CreateBitCast(DeclPtr, ConvertType(ArgTy));
470 
471     CallArgList Args;
472     Args.push_back(std::make_pair(RValue::get(DeclPtr),
473                                   getContext().getPointerType(D.getType())));
474 
475     EmitCall(Info, F, Args);
476   }
477 
478   if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) {
479     CleanupScope scope(*this);
480     llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
481     V = Builder.CreateLoad(V, false);
482     BuildBlockRelease(V);
483   }
484 }
485 
486 /// Emit an alloca (or GlobalValue depending on target)
487 /// for the specified parameter and set up LocalDeclMap.
488 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
489   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
490   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
491          "Invalid argument to EmitParmDecl");
492   QualType Ty = D.getType();
493 
494   llvm::Value *DeclPtr;
495   if (!Ty->isConstantSizeType()) {
496     // Variable sized values always are passed by-reference.
497     DeclPtr = Arg;
498   } else {
499     // A fixed sized single-value variable becomes an alloca in the entry block.
500     const llvm::Type *LTy = ConvertTypeForMem(Ty);
501     if (LTy->isSingleValueType()) {
502       // TODO: Alignment
503       std::string Name = D.getNameAsString();
504       Name += ".addr";
505       DeclPtr = CreateTempAlloca(LTy);
506       DeclPtr->setName(Name.c_str());
507 
508       // Store the initial value into the alloca.
509       EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(), Ty);
510     } else {
511       // Otherwise, if this is an aggregate, just use the input pointer.
512       DeclPtr = Arg;
513     }
514     Arg->setName(D.getNameAsString());
515   }
516 
517   llvm::Value *&DMEntry = LocalDeclMap[&D];
518   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
519   DMEntry = DeclPtr;
520 
521   // Emit debug info for param declaration.
522   if (CGDebugInfo *DI = getDebugInfo()) {
523     DI->setLocation(D.getLocation());
524     DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
525   }
526 }
527 
528