]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/CodeGen/CGDecl.cpp
Update clang to r84949.
[FreeBSD/FreeBSD.git] / lib / CodeGen / CGDecl.cpp
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   case Decl::UsingDirective: // using X; [C++]
41     // None of these decls require codegen support.
42     return;
43
44   case Decl::Var: {
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);
49   }
50
51   case Decl::Typedef: {   // typedef int X;
52     const TypedefDecl &TD = cast<TypedefDecl>(D);
53     QualType Ty = TD.getUnderlyingType();
54
55     if (Ty->isVariablyModifiedType())
56       EmitVLASize(Ty);
57   }
58   }
59 }
60
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__");
66
67   switch (D.getStorageClass()) {
68   case VarDecl::None:
69   case VarDecl::Auto:
70   case VarDecl::Register:
71     return EmitLocalBlockVarDecl(D);
72   case VarDecl::Static:
73     return EmitStaticBlockVarDecl(D);
74   case VarDecl::Extern:
75   case VarDecl::PrivateExtern:
76     // Don't emit it now, allow it to be emitted lazily on its first use.
77     return;
78   }
79
80   assert(0 && "Unknown storage class");
81 }
82
83 llvm::GlobalVariable *
84 CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
85                                           const char *Separator,
86                                           llvm::GlobalValue::LinkageTypes
87                                           Linkage) {
88   QualType Ty = D.getType();
89   assert(Ty->isConstantSizeType() && "VLAs can't be static");
90
91   std::string Name;
92   if (getContext().getLangOptions().CPlusPlus) {
93     Name = CGM.getMangledName(&D);
94   } else {
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();
100     else
101       assert(0 && "Unknown context for block var decl");
102
103     Name = ContextName + Separator + D.getNameAsString();
104   }
105
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));
113   return GV;
114 }
115
116 void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
117   llvm::Value *&DMEntry = LocalDeclMap[&D];
118   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
119
120   llvm::GlobalVariable *GV =
121     CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage);
122
123   // Store into LocalDeclMap before generating initializer to handle
124   // circular references.
125   DMEntry = GV;
126
127   // Make sure to evaluate VLA bounds now so that we have them for later.
128   //
129   // FIXME: Can this happen?
130   if (D.getType()->isVariablyModifiedType())
131     EmitVLASize(D.getType());
132
133   if (D.getInit()) {
134     llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
135
136     // If constant emission failed, then this should be a C++ static
137     // initializer.
138     if (!Init) {
139       if (!getContext().getLangOptions().CPlusPlus)
140         CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
141       else
142         EmitStaticCXXBlockVarDeclInit(D, GV);
143     } else {
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;
150
151         GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
152                                       OldGV->isConstant(),
153                                       OldGV->getLinkage(), Init, "",
154                                       0, D.isThreadSpecified(),
155                                       D.getType().getAddressSpace());
156
157         // Steal the name of the old global
158         GV->takeName(OldGV);
159
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);
164
165         // Erase the old global, since it is no longer used.
166         OldGV->eraseFromParent();
167       }
168
169       GV->setInitializer(Init);
170     }
171   }
172
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);
180   }
181
182   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
183     GV->setSection(SA->getName());
184
185   if (D.hasAttr<UsedAttr>())
186     CGM.AddUsedGlobal(GV);
187
188   // We may have to cast the constant because of the initializer
189   // mismatch above.
190   //
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);
197
198   // Emit global variable debug descriptor for static vars.
199   CGDebugInfo *DI = getDebugInfo();
200   if (DI) {
201     DI->setLocation(D.getLocation());
202     DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
203   }
204 }
205
206 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
207   assert(ByRefValueInfo.count(VD) && "Did not find value!");
208   
209   return ByRefValueInfo.find(VD)->second.second;
210 }
211
212 /// BuildByRefType - This routine changes a __block variable declared as T x
213 ///   into:
214 ///
215 ///      struct {
216 ///        void *__isa;
217 ///        void *__forwarding;
218 ///        int32_t __flags;
219 ///        int32_t __size;
220 ///        void *__copy_helper;       // only if needed
221 ///        void *__destroy_helper;    // only if needed
222 ///        char padding[X];           // only if needed
223 ///        T x;
224 ///      } x
225 ///
226 const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
227   std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
228   if (Info.first)
229     return Info.first;
230   
231   QualType Ty = D->getType();
232
233   std::vector<const llvm::Type *> Types;
234   
235   const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
236
237   llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
238   
239   // void *__isa;
240   Types.push_back(Int8PtrTy);
241   
242   // void *__forwarding;
243   Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
244   
245   // int32_t __flags;
246   Types.push_back(llvm::Type::getInt32Ty(VMContext));
247     
248   // int32_t __size;
249   Types.push_back(llvm::Type::getInt32Ty(VMContext));
250
251   bool HasCopyAndDispose = BlockRequiresCopying(Ty);
252   if (HasCopyAndDispose) {
253     /// void *__copy_helper;
254     Types.push_back(Int8PtrTy);
255     
256     /// void *__destroy_helper;
257     Types.push_back(Int8PtrTy);
258   }
259
260   bool Packed = false;
261   unsigned Align = getContext().getDeclAlignInBytes(D);
262   if (Align > Target.getPointerAlign(0) / 8) {
263     // We have to insert padding.
264     
265     // The struct above has 2 32-bit integers.
266     unsigned CurrentOffsetInBytes = 4 * 2;
267     
268     // And either 2 or 4 pointers.
269     CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
270       CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
271     
272     // Align the offset.
273     unsigned AlignedOffsetInBytes = 
274       llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align);
275     
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);
283     
284       Types.push_back(Ty);
285
286       // We want a packed struct.
287       Packed = true;
288     }
289   }
290
291   // T x;
292   Types.push_back(ConvertType(Ty));
293   
294   const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
295   
296   cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
297   CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(), 
298                               ByRefTypeHolder.get());
299   
300   Info.first = ByRefTypeHolder.get();
301   
302   Info.second = Types.size() - 1;
303   
304   return Info.first;
305 }
306
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;
314   unsigned Align = 0;
315
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);
322       if (isByRef)
323         LTy = BuildByRefType(&D);
324       llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
325       Alloc->setName(D.getNameAsString().c_str());
326
327       if (isByRef)
328         Align = std::max(Align, unsigned(Target.getPointerAlign(0) / 8));
329       Alloc->setAlignment(Align);
330       DeclPtr = Alloc;
331     } else {
332       // Targets that don't support recursion emit locals as globals.
333       const char *Class =
334         D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
335       DeclPtr = CreateStaticBlockVarDecl(D, Class,
336                                          llvm::GlobalValue
337                                          ::InternalLinkage);
338     }
339
340     // FIXME: Can this happen?
341     if (Ty->isVariablyModifiedType())
342       EmitVLASize(Ty);
343   } else {
344     EnsureInsertPoint();
345
346     if (!DidCallStackSave) {
347       // Save the stack.
348       const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext);
349       llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
350
351       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
352       llvm::Value *V = Builder.CreateCall(F);
353
354       Builder.CreateStore(V, Stack);
355
356       DidCallStackSave = true;
357
358       {
359         // Push a cleanup block and restore the stack there.
360         CleanupScope scope(*this);
361
362         V = Builder.CreateLoad(Stack, "tmp");
363         llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
364         Builder.CreateCall(F, V);
365       }
366     }
367
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());
372
373     llvm::Value *VLASize = EmitVLASize(Ty);
374
375     // Downcast the VLA size expression
376     VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext),
377                                     false, "tmp");
378
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));
383
384     DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
385   }
386
387   llvm::Value *&DMEntry = LocalDeclMap[&D];
388   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
389   DMEntry = DeclPtr;
390
391   // Emit debug info for local var declaration.
392   if (CGDebugInfo *DI = getDebugInfo()) {
393     assert(HaveInsertPoint() && "Unexpected unreachable point!");
394
395     DI->setLocation(D.getLocation());
396     if (Target.useGlobalsForAutomaticVariables()) {
397       DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
398     } else
399       DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
400   }
401
402   // If this local has an initializer, emit it now.
403   const Expr *Init = D.getInit();
404
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))
409       Init = 0;
410     else
411       EnsureInsertPoint();
412   }
413
414   if (Init) {
415     llvm::Value *Loc = DeclPtr;
416     if (isByRef)
417       Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D), 
418                                     D.getNameAsString());
419
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(),
426                         D.getType());
427     } else if (Init->getType()->isAnyComplexType()) {
428       EmitComplexExprIntoAddr(Init, Loc, D.getType().isVolatileQualified());
429     } else {
430       EmitAggExpr(Init, Loc, D.getType().isVolatileQualified());
431     }
432   }
433
434   if (isByRef) {
435     const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext);
436
437     EnsureInsertPoint();
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);
442     llvm::Value *V;
443     int flag = 0;
444     int flags = 0;
445
446     needsDispose = true;
447
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;
454     }
455
456     // FIXME: Someone double check this.
457     if (Ty.isObjCGCWeak())
458       flag |= BLOCK_FIELD_IS_WEAK;
459
460     int isa = 0;
461     if (flag&BLOCK_FIELD_IS_WEAK)
462       isa = 1;
463     V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), isa);
464     V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
465     Builder.CreateStore(V, isa_field);
466
467     Builder.CreateStore(DeclPtr, forwarding_field);
468
469     V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), flags);
470     Builder.CreateStore(V, flags_field);
471
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)
476                                 / 8));
477     Builder.CreateStore(V, size_field);
478
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),
483                           copy_helper);
484
485       llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
486       Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
487                                                   Align),
488                           destroy_helper);
489     }
490   }
491
492   // Handle CXX destruction of variables.
493   QualType DtorTy(Ty);
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");
502
503         CleanupScope scope(*this);
504         EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr);
505       }
506   }
507
508   // Handle the cleanup attribute
509   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
510     const FunctionDecl *FD = CA->getFunctionDecl();
511
512     llvm::Constant* F = CGM.GetAddrOfFunction(FD);
513     assert(F && "Could not find function!");
514
515     CleanupScope scope(*this);
516
517     const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
518
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;
523     //
524     // To fix this we insert a bitcast here.
525     QualType ArgTy = Info.arg_begin()->type;
526     DeclPtr = Builder.CreateBitCast(DeclPtr, ConvertType(ArgTy));
527
528     CallArgList Args;
529     Args.push_back(std::make_pair(RValue::get(DeclPtr),
530                                   getContext().getPointerType(D.getType())));
531
532     EmitCall(Info, F, Args);
533   }
534
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);
540   }
541 }
542
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();
550
551   llvm::Value *DeclPtr;
552   if (!Ty->isConstantSizeType()) {
553     // Variable sized values always are passed by-reference.
554     DeclPtr = Arg;
555   } else {
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()) {
559       // TODO: Alignment
560       std::string Name = D.getNameAsString();
561       Name += ".addr";
562       DeclPtr = CreateTempAlloca(LTy);
563       DeclPtr->setName(Name.c_str());
564
565       // Store the initial value into the alloca.
566       EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(), Ty);
567     } else {
568       // Otherwise, if this is an aggregate, just use the input pointer.
569       DeclPtr = Arg;
570     }
571     Arg->setName(D.getNameAsString());
572   }
573
574   llvm::Value *&DMEntry = LocalDeclMap[&D];
575   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
576   DMEntry = DeclPtr;
577
578   // Emit debug info for param declaration.
579   if (CGDebugInfo *DI = getDebugInfo()) {
580     DI->setLocation(D.getLocation());
581     DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
582   }
583 }
584