1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
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 is the internal per-function state used for llvm translation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef CLANG_CODEGEN_CODEGENFUNCTION_H
15 #define CLANG_CODEGEN_CODEGENFUNCTION_H
16 
17 #include "clang/AST/Type.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "CodeGenModule.h"
26 #include "CGBlocks.h"
27 #include "CGBuilder.h"
28 #include "CGCall.h"
29 #include "CGCXX.h"
30 #include "CGValue.h"
31 
32 namespace llvm {
33   class BasicBlock;
34   class LLVMContext;
35   class MDNode;
36   class Module;
37   class SwitchInst;
38   class Twine;
39   class Value;
40 }
41 
42 namespace clang {
43   class ASTContext;
44   class CXXDestructorDecl;
45   class CXXTryStmt;
46   class Decl;
47   class EnumConstantDecl;
48   class FunctionDecl;
49   class FunctionProtoType;
50   class LabelStmt;
51   class ObjCContainerDecl;
52   class ObjCInterfaceDecl;
53   class ObjCIvarDecl;
54   class ObjCMethodDecl;
55   class ObjCImplementationDecl;
56   class ObjCPropertyImplDecl;
57   class TargetInfo;
58   class TargetCodeGenInfo;
59   class VarDecl;
60   class ObjCForCollectionStmt;
61   class ObjCAtTryStmt;
62   class ObjCAtThrowStmt;
63   class ObjCAtSynchronizedStmt;
64 
65 namespace CodeGen {
66   class CodeGenTypes;
67   class CGDebugInfo;
68   class CGFunctionInfo;
69   class CGRecordLayout;
70   class CGBlockInfo;
71 
72 /// CodeGenFunction - This class organizes the per-function state that is used
73 /// while generating LLVM code.
74 class CodeGenFunction : public BlockFunction {
75   CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
76   void operator=(const CodeGenFunction&);  // DO NOT IMPLEMENT
77 public:
78   CodeGenModule &CGM;  // Per-module state.
79   const TargetInfo &Target;
80 
81   typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
82   CGBuilderTy Builder;
83 
84   /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
85   /// This excludes BlockDecls.
86   const Decl *CurFuncDecl;
87   /// CurCodeDecl - This is the inner-most code context, which includes blocks.
88   const Decl *CurCodeDecl;
89   const CGFunctionInfo *CurFnInfo;
90   QualType FnRetTy;
91   llvm::Function *CurFn;
92 
93   /// CurGD - The GlobalDecl for the current function being compiled.
94   GlobalDecl CurGD;
95 
96   /// ReturnBlock - Unified return block.
97   llvm::BasicBlock *ReturnBlock;
98   /// ReturnValue - The temporary alloca to hold the return value. This is null
99   /// iff the function has no return value.
100   llvm::Value *ReturnValue;
101 
102   /// AllocaInsertPoint - This is an instruction in the entry block before which
103   /// we prefer to insert allocas.
104   llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
105 
106   const llvm::Type *LLVMIntTy;
107   uint32_t LLVMPointerWidth;
108 
109   bool Exceptions;
110   bool CatchUndefined;
111 
112   /// \brief A mapping from NRVO variables to the flags used to indicate
113   /// when the NRVO has been applied to this variable.
114   llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
115 
116 public:
117   /// ObjCEHValueStack - Stack of Objective-C exception values, used for
118   /// rethrows.
119   llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
120 
121   /// PushCleanupBlock - Push a new cleanup entry on the stack and set the
122   /// passed in block as the cleanup block.
123   void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
124                         llvm::BasicBlock *CleanupExitBlock,
125                         llvm::BasicBlock *PreviousInvokeDest,
126                         bool EHOnly = false);
127   void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock) {
128     PushCleanupBlock(CleanupEntryBlock, 0, getInvokeDest(), false);
129   }
130 
131   /// CleanupBlockInfo - A struct representing a popped cleanup block.
132   struct CleanupBlockInfo {
133     /// CleanupEntryBlock - the cleanup entry block
134     llvm::BasicBlock *CleanupBlock;
135 
136     /// SwitchBlock - the block (if any) containing the switch instruction used
137     /// for jumping to the final destination.
138     llvm::BasicBlock *SwitchBlock;
139 
140     /// EndBlock - the default destination for the switch instruction.
141     llvm::BasicBlock *EndBlock;
142 
143     /// EHOnly - True iff this cleanup should only be performed on the
144     /// exceptional edge.
145     bool EHOnly;
146 
147     CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb,
148                      llvm::BasicBlock *eb, bool ehonly = false)
149       : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb), EHOnly(ehonly) {}
150   };
151 
152   /// EHCleanupBlock - RAII object that will create a cleanup block for the
153   /// exceptional edge and set the insert point to that block.  When destroyed,
154   /// it creates the cleanup edge and sets the insert point to the previous
155   /// block.
156   class EHCleanupBlock {
157     CodeGenFunction& CGF;
158     llvm::BasicBlock *PreviousInsertionBlock;
159     llvm::BasicBlock *CleanupHandler;
160     llvm::BasicBlock *PreviousInvokeDest;
161   public:
162     EHCleanupBlock(CodeGenFunction &cgf)
163       : CGF(cgf),
164         PreviousInsertionBlock(CGF.Builder.GetInsertBlock()),
165         CleanupHandler(CGF.createBasicBlock("ehcleanup", CGF.CurFn)),
166         PreviousInvokeDest(CGF.getInvokeDest()) {
167       llvm::BasicBlock *TerminateHandler = CGF.getTerminateHandler();
168       CGF.Builder.SetInsertPoint(CleanupHandler);
169       CGF.setInvokeDest(TerminateHandler);
170     }
171     ~EHCleanupBlock();
172   };
173 
174   /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all
175   /// branch fixups and return a block info struct with the switch block and end
176   /// block.  This will also reset the invoke handler to the previous value
177   /// from when the cleanup block was created.
178   CleanupBlockInfo PopCleanupBlock();
179 
180   /// DelayedCleanupBlock - RAII object that will create a cleanup block and set
181   /// the insert point to that block. When destructed, it sets the insert point
182   /// to the previous block and pushes a new cleanup entry on the stack.
183   class DelayedCleanupBlock {
184     CodeGenFunction& CGF;
185     llvm::BasicBlock *CurBB;
186     llvm::BasicBlock *CleanupEntryBB;
187     llvm::BasicBlock *CleanupExitBB;
188     llvm::BasicBlock *CurInvokeDest;
189     bool EHOnly;
190 
191   public:
192     DelayedCleanupBlock(CodeGenFunction &cgf, bool ehonly = false)
193       : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()),
194         CleanupEntryBB(CGF.createBasicBlock("cleanup")),
195         CleanupExitBB(0),
196         CurInvokeDest(CGF.getInvokeDest()),
197         EHOnly(ehonly) {
198       CGF.Builder.SetInsertPoint(CleanupEntryBB);
199     }
200 
201     llvm::BasicBlock *getCleanupExitBlock() {
202       if (!CleanupExitBB)
203         CleanupExitBB = CGF.createBasicBlock("cleanup.exit");
204       return CleanupExitBB;
205     }
206 
207     ~DelayedCleanupBlock() {
208       CGF.PushCleanupBlock(CleanupEntryBB, CleanupExitBB, CurInvokeDest,
209                            EHOnly);
210       // FIXME: This is silly, move this into the builder.
211       if (CurBB)
212         CGF.Builder.SetInsertPoint(CurBB);
213       else
214         CGF.Builder.ClearInsertionPoint();
215     }
216   };
217 
218   /// \brief Enters a new scope for capturing cleanups, all of which will be
219   /// executed once the scope is exited.
220   class CleanupScope {
221     CodeGenFunction& CGF;
222     size_t CleanupStackDepth;
223     bool OldDidCallStackSave;
224     bool PerformCleanup;
225 
226     CleanupScope(const CleanupScope &); // DO NOT IMPLEMENT
227     CleanupScope &operator=(const CleanupScope &); // DO NOT IMPLEMENT
228 
229   public:
230     /// \brief Enter a new cleanup scope.
231     explicit CleanupScope(CodeGenFunction &CGF)
232       : CGF(CGF), PerformCleanup(true)
233     {
234       CleanupStackDepth = CGF.CleanupEntries.size();
235       OldDidCallStackSave = CGF.DidCallStackSave;
236     }
237 
238     /// \brief Exit this cleanup scope, emitting any accumulated
239     /// cleanups.
240     ~CleanupScope() {
241       if (PerformCleanup) {
242         CGF.DidCallStackSave = OldDidCallStackSave;
243         CGF.EmitCleanupBlocks(CleanupStackDepth);
244       }
245     }
246 
247     /// \brief Determine whether this scope requires any cleanups.
248     bool requiresCleanups() const {
249       return CGF.CleanupEntries.size() > CleanupStackDepth;
250     }
251 
252     /// \brief Force the emission of cleanups now, instead of waiting
253     /// until this object is destroyed.
254     void ForceCleanup() {
255       assert(PerformCleanup && "Already forced cleanup");
256       CGF.DidCallStackSave = OldDidCallStackSave;
257       CGF.EmitCleanupBlocks(CleanupStackDepth);
258       PerformCleanup = false;
259     }
260   };
261 
262   /// CXXTemporariesCleanupScope - Enters a new scope for catching live
263   /// temporaries, all of which will be popped once the scope is exited.
264   class CXXTemporariesCleanupScope {
265     CodeGenFunction &CGF;
266     size_t NumLiveTemporaries;
267 
268     // DO NOT IMPLEMENT
269     CXXTemporariesCleanupScope(const CXXTemporariesCleanupScope &);
270     CXXTemporariesCleanupScope &operator=(const CXXTemporariesCleanupScope &);
271 
272   public:
273     explicit CXXTemporariesCleanupScope(CodeGenFunction &CGF)
274       : CGF(CGF), NumLiveTemporaries(CGF.LiveTemporaries.size()) { }
275 
276     ~CXXTemporariesCleanupScope() {
277       while (CGF.LiveTemporaries.size() > NumLiveTemporaries)
278         CGF.PopCXXTemporary();
279     }
280   };
281 
282 
283   /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup
284   /// blocks that have been added.
285   void EmitCleanupBlocks(size_t OldCleanupStackSize);
286 
287   /// EmitBranchThroughCleanup - Emit a branch from the current insert block
288   /// through the cleanup handling code (if any) and then on to \arg Dest.
289   ///
290   /// FIXME: Maybe this should really be in EmitBranch? Don't we always want
291   /// this behavior for branches?
292   void EmitBranchThroughCleanup(llvm::BasicBlock *Dest);
293 
294   /// BeginConditionalBranch - Should be called before a conditional part of an
295   /// expression is emitted. For example, before the RHS of the expression below
296   /// is emitted:
297   ///
298   /// b && f(T());
299   ///
300   /// This is used to make sure that any temporaries created in the conditional
301   /// branch are only destroyed if the branch is taken.
302   void BeginConditionalBranch() {
303     ++ConditionalBranchLevel;
304   }
305 
306   /// EndConditionalBranch - Should be called after a conditional part of an
307   /// expression has been emitted.
308   void EndConditionalBranch() {
309     assert(ConditionalBranchLevel != 0 &&
310            "Conditional branch mismatch!");
311 
312     --ConditionalBranchLevel;
313   }
314 
315 private:
316   CGDebugInfo *DebugInfo;
317 
318   /// IndirectBranch - The first time an indirect goto is seen we create a block
319   /// with an indirect branch.  Every time we see the address of a label taken,
320   /// we add the label to the indirect goto.  Every subsequent indirect goto is
321   /// codegen'd as a jump to the IndirectBranch's basic block.
322   llvm::IndirectBrInst *IndirectBranch;
323 
324   /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
325   /// decls.
326   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
327 
328   /// LabelMap - This keeps track of the LLVM basic block for each C label.
329   llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
330 
331   // BreakContinueStack - This keeps track of where break and continue
332   // statements should jump to.
333   struct BreakContinue {
334     BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
335       : BreakBlock(bb), ContinueBlock(cb) {}
336 
337     llvm::BasicBlock *BreakBlock;
338     llvm::BasicBlock *ContinueBlock;
339   };
340   llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
341 
342   /// SwitchInsn - This is nearest current switch instruction. It is null if if
343   /// current context is not in a switch.
344   llvm::SwitchInst *SwitchInsn;
345 
346   /// CaseRangeBlock - This block holds if condition check for last case
347   /// statement range in current switch instruction.
348   llvm::BasicBlock *CaseRangeBlock;
349 
350   /// InvokeDest - This is the nearest exception target for calls
351   /// which can unwind, when exceptions are being used.
352   llvm::BasicBlock *InvokeDest;
353 
354   // VLASizeMap - This keeps track of the associated size for each VLA type.
355   // We track this by the size expression rather than the type itself because
356   // in certain situations, like a const qualifier applied to an VLA typedef,
357   // multiple VLA types can share the same size expression.
358   // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
359   // enter/leave scopes.
360   llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
361 
362   /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
363   /// calling llvm.stacksave for multiple VLAs in the same scope.
364   bool DidCallStackSave;
365 
366   struct CleanupEntry {
367     /// CleanupEntryBlock - The block of code that does the actual cleanup.
368     llvm::BasicBlock *CleanupEntryBlock;
369 
370     /// CleanupExitBlock - The cleanup exit block.
371     llvm::BasicBlock *CleanupExitBlock;
372 
373     /// Blocks - Basic blocks that were emitted in the current cleanup scope.
374     std::vector<llvm::BasicBlock *> Blocks;
375 
376     /// BranchFixups - Branch instructions to basic blocks that haven't been
377     /// inserted into the current function yet.
378     std::vector<llvm::BranchInst *> BranchFixups;
379 
380     /// PreviousInvokeDest - The invoke handler from the start of the cleanup
381     /// region.
382     llvm::BasicBlock *PreviousInvokeDest;
383 
384     /// EHOnly - Perform this only on the exceptional edge, not the main edge.
385     bool EHOnly;
386 
387     explicit CleanupEntry(llvm::BasicBlock *CleanupEntryBlock,
388                           llvm::BasicBlock *CleanupExitBlock,
389                           llvm::BasicBlock *PreviousInvokeDest,
390                           bool ehonly)
391       : CleanupEntryBlock(CleanupEntryBlock),
392         CleanupExitBlock(CleanupExitBlock),
393         PreviousInvokeDest(PreviousInvokeDest),
394         EHOnly(ehonly) {}
395   };
396 
397   /// CleanupEntries - Stack of cleanup entries.
398   llvm::SmallVector<CleanupEntry, 8> CleanupEntries;
399 
400   typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap;
401 
402   /// BlockScopes - Map of which "cleanup scope" scope basic blocks have.
403   BlockScopeMap BlockScopes;
404 
405   /// CXXThisDecl - When generating code for a C++ member function,
406   /// this will hold the implicit 'this' declaration.
407   ImplicitParamDecl *CXXThisDecl;
408   llvm::Value *CXXThisValue;
409 
410   /// CXXVTTDecl - When generating code for a base object constructor or
411   /// base object destructor with virtual bases, this will hold the implicit
412   /// VTT parameter.
413   ImplicitParamDecl *CXXVTTDecl;
414   llvm::Value *CXXVTTValue;
415 
416   /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary.
417   struct CXXLiveTemporaryInfo {
418     /// Temporary - The live temporary.
419     const CXXTemporary *Temporary;
420 
421     /// ThisPtr - The pointer to the temporary.
422     llvm::Value *ThisPtr;
423 
424     /// DtorBlock - The destructor block.
425     llvm::BasicBlock *DtorBlock;
426 
427     /// CondPtr - If this is a conditional temporary, this is the pointer to the
428     /// condition variable that states whether the destructor should be called
429     /// or not.
430     llvm::Value *CondPtr;
431 
432     CXXLiveTemporaryInfo(const CXXTemporary *temporary,
433                          llvm::Value *thisptr, llvm::BasicBlock *dtorblock,
434                          llvm::Value *condptr)
435       : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock),
436       CondPtr(condptr) { }
437   };
438 
439   llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries;
440 
441   /// ConditionalBranchLevel - Contains the nesting level of the current
442   /// conditional branch. This is used so that we know if a temporary should be
443   /// destroyed conditionally.
444   unsigned ConditionalBranchLevel;
445 
446 
447   /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
448   /// type as well as the field number that contains the actual data.
449   llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
450                                               unsigned> > ByRefValueInfo;
451 
452   /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
453   /// number that holds the value.
454   unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
455 
456   llvm::BasicBlock *TerminateHandler;
457   llvm::BasicBlock *TrapBB;
458 
459   int UniqueAggrDestructorCount;
460 public:
461   CodeGenFunction(CodeGenModule &cgm);
462 
463   ASTContext &getContext() const;
464   CGDebugInfo *getDebugInfo() { return DebugInfo; }
465 
466   llvm::BasicBlock *getInvokeDest() { return InvokeDest; }
467   void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; }
468 
469   llvm::LLVMContext &getLLVMContext() { return VMContext; }
470 
471   //===--------------------------------------------------------------------===//
472   //                                  Objective-C
473   //===--------------------------------------------------------------------===//
474 
475   void GenerateObjCMethod(const ObjCMethodDecl *OMD);
476 
477   void StartObjCMethod(const ObjCMethodDecl *MD,
478                        const ObjCContainerDecl *CD);
479 
480   /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
481   void GenerateObjCGetter(ObjCImplementationDecl *IMP,
482                           const ObjCPropertyImplDecl *PID);
483   void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
484                                   ObjCMethodDecl *MD, bool ctor);
485 
486   /// GenerateObjCSetter - Synthesize an Objective-C property setter function
487   /// for the given property.
488   void GenerateObjCSetter(ObjCImplementationDecl *IMP,
489                           const ObjCPropertyImplDecl *PID);
490   bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
491   bool IvarTypeWithAggrGCObjects(QualType Ty);
492 
493   //===--------------------------------------------------------------------===//
494   //                                  Block Bits
495   //===--------------------------------------------------------------------===//
496 
497   llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
498   llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
499                                            bool BlockHasCopyDispose,
500                                            CharUnits Size,
501                                            const llvm::StructType *,
502                                            std::vector<HelperInfo> *);
503 
504   llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr,
505                                         CGBlockInfo &Info,
506                                         const Decl *OuterFuncDecl,
507                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm);
508 
509   llvm::Value *LoadBlockStruct();
510 
511   void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
512   void AllocateBlockDecl(const BlockDeclRefExpr *E);
513   llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
514     return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
515   }
516   llvm::Value *GetAddrOfBlockDecl(const ValueDecl *D, bool ByRef);
517   const llvm::Type *BuildByRefType(const ValueDecl *D);
518 
519   void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
520   void StartFunction(GlobalDecl GD, QualType RetTy,
521                      llvm::Function *Fn,
522                      const FunctionArgList &Args,
523                      SourceLocation StartLoc);
524 
525   void EmitConstructorBody(FunctionArgList &Args);
526   void EmitDestructorBody(FunctionArgList &Args);
527   void EmitFunctionBody(FunctionArgList &Args);
528 
529   /// EmitReturnBlock - Emit the unified return block, trying to avoid its
530   /// emission when possible.
531   void EmitReturnBlock();
532 
533   /// FinishFunction - Complete IR generation of the current function. It is
534   /// legal to call this function even if there is no current insertion point.
535   void FinishFunction(SourceLocation EndLoc=SourceLocation());
536 
537   /// GenerateThunk - Generate a thunk for the given method.
538   void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk);
539 
540   void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
541                         FunctionArgList &Args);
542 
543   /// InitializeVTablePointer - Initialize the vtable pointer of the given
544   /// subobject.
545   ///
546   void InitializeVTablePointer(BaseSubobject Base,
547                                const CXXRecordDecl *NearestVBase,
548                                uint64_t OffsetFromNearestVBase,
549                                llvm::Constant *VTable,
550                                const CXXRecordDecl *VTableClass);
551 
552   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
553   void InitializeVTablePointers(BaseSubobject Base,
554                                 const CXXRecordDecl *NearestVBase,
555                                 uint64_t OffsetFromNearestVBase,
556                                 bool BaseIsNonVirtualPrimaryBase,
557                                 llvm::Constant *VTable,
558                                 const CXXRecordDecl *VTableClass,
559                                 VisitedVirtualBasesSetTy& VBases);
560 
561   void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
562 
563 
564   /// EmitDtorEpilogue - Emit all code that comes at the end of class's
565   /// destructor. This is to call destructors on members and base classes in
566   /// reverse order of their construction.
567   void EmitDtorEpilogue(const CXXDestructorDecl *Dtor,
568                         CXXDtorType Type);
569 
570   /// EmitFunctionProlog - Emit the target specific LLVM code to load the
571   /// arguments for the given function. This is also responsible for naming the
572   /// LLVM function arguments.
573   void EmitFunctionProlog(const CGFunctionInfo &FI,
574                           llvm::Function *Fn,
575                           const FunctionArgList &Args);
576 
577   /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
578   /// given temporary.
579   void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue);
580 
581   /// EmitStartEHSpec - Emit the start of the exception spec.
582   void EmitStartEHSpec(const Decl *D);
583 
584   /// EmitEndEHSpec - Emit the end of the exception spec.
585   void EmitEndEHSpec(const Decl *D);
586 
587   /// getTerminateHandler - Return a handler that just calls terminate.
588   llvm::BasicBlock *getTerminateHandler();
589 
590   const llvm::Type *ConvertTypeForMem(QualType T);
591   const llvm::Type *ConvertType(QualType T);
592   const llvm::Type *ConvertType(const TypeDecl *T) {
593     return ConvertType(getContext().getTypeDeclType(T));
594   }
595 
596   /// LoadObjCSelf - Load the value of self. This function is only valid while
597   /// generating code for an Objective-C method.
598   llvm::Value *LoadObjCSelf();
599 
600   /// TypeOfSelfObject - Return type of object that this self represents.
601   QualType TypeOfSelfObject();
602 
603   /// hasAggregateLLVMType - Return true if the specified AST type will map into
604   /// an aggregate LLVM type or is void.
605   static bool hasAggregateLLVMType(QualType T);
606 
607   /// createBasicBlock - Create an LLVM basic block.
608   llvm::BasicBlock *createBasicBlock(const char *Name="",
609                                      llvm::Function *Parent=0,
610                                      llvm::BasicBlock *InsertBefore=0) {
611 #ifdef NDEBUG
612     return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
613 #else
614     return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
615 #endif
616   }
617 
618   /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
619   /// label maps to.
620   llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
621 
622   /// SimplifyForwardingBlocks - If the given basic block is only a branch to
623   /// another basic block, simplify it. This assumes that no other code could
624   /// potentially reference the basic block.
625   void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
626 
627   /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
628   /// adding a fall-through branch from the current insert block if
629   /// necessary. It is legal to call this function even if there is no current
630   /// insertion point.
631   ///
632   /// IsFinished - If true, indicates that the caller has finished emitting
633   /// branches to the given block and does not expect to emit code into it. This
634   /// means the block can be ignored if it is unreachable.
635   void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
636 
637   /// EmitBranch - Emit a branch to the specified basic block from the current
638   /// insert block, taking care to avoid creation of branches from dummy
639   /// blocks. It is legal to call this function even if there is no current
640   /// insertion point.
641   ///
642   /// This function clears the current insertion point. The caller should follow
643   /// calls to this function with calls to Emit*Block prior to generation new
644   /// code.
645   void EmitBranch(llvm::BasicBlock *Block);
646 
647   /// HaveInsertPoint - True if an insertion point is defined. If not, this
648   /// indicates that the current code being emitted is unreachable.
649   bool HaveInsertPoint() const {
650     return Builder.GetInsertBlock() != 0;
651   }
652 
653   /// EnsureInsertPoint - Ensure that an insertion point is defined so that
654   /// emitted IR has a place to go. Note that by definition, if this function
655   /// creates a block then that block is unreachable; callers may do better to
656   /// detect when no insertion point is defined and simply skip IR generation.
657   void EnsureInsertPoint() {
658     if (!HaveInsertPoint())
659       EmitBlock(createBasicBlock());
660   }
661 
662   /// ErrorUnsupported - Print out an error that codegen doesn't support the
663   /// specified stmt yet.
664   void ErrorUnsupported(const Stmt *S, const char *Type,
665                         bool OmitOnError=false);
666 
667   //===--------------------------------------------------------------------===//
668   //                                  Helpers
669   //===--------------------------------------------------------------------===//
670 
671   Qualifiers MakeQualifiers(QualType T) {
672     Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers();
673     Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T));
674     return Quals;
675   }
676 
677   /// CreateTempAlloca - This creates a alloca and inserts it into the entry
678   /// block. The caller is responsible for setting an appropriate alignment on
679   /// the alloca.
680   llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
681                                      const llvm::Twine &Name = "tmp");
682 
683   /// InitTempAlloca - Provide an initial value for the given alloca.
684   void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
685 
686   /// CreateIRTemp - Create a temporary IR object of the given type, with
687   /// appropriate alignment. This routine should only be used when an temporary
688   /// value needs to be stored into an alloca (for example, to avoid explicit
689   /// PHI construction), but the type is the IR type, not the type appropriate
690   /// for storing in memory.
691   llvm::Value *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
692 
693   /// CreateMemTemp - Create a temporary memory object of the given type, with
694   /// appropriate alignment.
695   llvm::Value *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
696 
697   /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
698   /// expression and compare the result against zero, returning an Int1Ty value.
699   llvm::Value *EvaluateExprAsBool(const Expr *E);
700 
701   /// EmitAnyExpr - Emit code to compute the specified expression which can have
702   /// any type.  The result is returned as an RValue struct.  If this is an
703   /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
704   /// the result should be returned.
705   ///
706   /// \param IgnoreResult - True if the resulting value isn't used.
707   RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
708                      bool IsAggLocVolatile = false, bool IgnoreResult = false,
709                      bool IsInitializer = false);
710 
711   // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
712   // or the value of the expression, depending on how va_list is defined.
713   llvm::Value *EmitVAListRef(const Expr *E);
714 
715   /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
716   /// always be accessible even if no aggregate location is provided.
717   RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
718                            bool IsInitializer = false);
719 
720   /// EmitsAnyExprToMem - Emits the code necessary to evaluate an
721   /// arbitrary expression into the given memory location.
722   void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
723                         bool IsLocationVolatile = false,
724                         bool IsInitializer = false);
725 
726   /// EmitAggregateCopy - Emit an aggrate copy.
727   ///
728   /// \param isVolatile - True iff either the source or the destination is
729   /// volatile.
730   void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
731                          QualType EltTy, bool isVolatile=false);
732 
733   /// StartBlock - Start new block named N. If insert block is a dummy block
734   /// then reuse it.
735   void StartBlock(const char *N);
736 
737   /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
738   llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
739 
740   /// GetAddrOfLocalVar - Return the address of a local variable.
741   llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
742 
743   /// getAccessedFieldNo - Given an encoded value and a result number, return
744   /// the input field number being accessed.
745   static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
746 
747   llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
748   llvm::BasicBlock *GetIndirectGotoBlock();
749 
750   /// EmitNullInitialization - Generate code to set a value of the given type to
751   /// null, If the type contains data member pointers, they will be initialized
752   /// to -1 in accordance with the Itanium C++ ABI.
753   void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
754 
755   // EmitVAArg - Generate code to get an argument from the passed in pointer
756   // and update it accordingly. The return value is a pointer to the argument.
757   // FIXME: We should be able to get rid of this method and use the va_arg
758   // instruction in LLVM instead once it works well enough.
759   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
760 
761   /// EmitVLASize - Generate code for any VLA size expressions that might occur
762   /// in a variably modified type. If Ty is a VLA, will return the value that
763   /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
764   ///
765   /// This function can be called with a null (unreachable) insert point.
766   llvm::Value *EmitVLASize(QualType Ty);
767 
768   // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
769   // of a variable length array type.
770   llvm::Value *GetVLASize(const VariableArrayType *);
771 
772   /// LoadCXXThis - Load the value of 'this'. This function is only valid while
773   /// generating code for an C++ member function.
774   llvm::Value *LoadCXXThis() {
775     assert(CXXThisValue && "no 'this' value for this function");
776     return CXXThisValue;
777   }
778 
779   /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
780   /// virtual bases.
781   llvm::Value *LoadCXXVTT() {
782     assert(CXXVTTValue && "no VTT value for this function");
783     return CXXVTTValue;
784   }
785 
786   /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
787   /// complete class to the given direct base.
788   llvm::Value *
789   GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
790                                         const CXXRecordDecl *Derived,
791                                         const CXXRecordDecl *Base,
792                                         bool BaseIsVirtual);
793 
794   /// GetAddressOfBaseClass - This function will add the necessary delta to the
795   /// load of 'this' and returns address of the base class.
796   llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
797                                      const CXXRecordDecl *Derived,
798                                      const CXXBaseSpecifierArray &BasePath,
799                                      bool NullCheckValue);
800 
801   llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
802                                         const CXXRecordDecl *Derived,
803                                         const CXXBaseSpecifierArray &BasePath,
804                                         bool NullCheckValue);
805 
806   llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
807                                          const CXXRecordDecl *ClassDecl,
808                                          const CXXRecordDecl *BaseClassDecl);
809 
810   void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
811                                       CXXCtorType CtorType,
812                                       const FunctionArgList &Args);
813   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
814                               bool ForVirtualBase, llvm::Value *This,
815                               CallExpr::const_arg_iterator ArgBeg,
816                               CallExpr::const_arg_iterator ArgEnd);
817 
818   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
819                                   const ConstantArrayType *ArrayTy,
820                                   llvm::Value *ArrayPtr,
821                                   CallExpr::const_arg_iterator ArgBeg,
822                                   CallExpr::const_arg_iterator ArgEnd);
823 
824   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
825                                   llvm::Value *NumElements,
826                                   llvm::Value *ArrayPtr,
827                                   CallExpr::const_arg_iterator ArgBeg,
828                                   CallExpr::const_arg_iterator ArgEnd);
829 
830   void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
831                                  const ArrayType *Array,
832                                  llvm::Value *This);
833 
834   void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
835                                  llvm::Value *NumElements,
836                                  llvm::Value *This);
837 
838   llvm::Constant *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
839                                                 const ArrayType *Array,
840                                                 llvm::Value *This);
841 
842   void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
843                              bool ForVirtualBase, llvm::Value *This);
844 
845   void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
846   void PopCXXTemporary();
847 
848   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
849   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
850 
851   void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
852                       QualType DeleteTy);
853 
854   llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
855   llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
856 
857   void EmitCheck(llvm::Value *, unsigned Size);
858 
859   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
860                                        bool isInc, bool isPre);
861   ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
862                                          bool isInc, bool isPre);
863   //===--------------------------------------------------------------------===//
864   //                            Declaration Emission
865   //===--------------------------------------------------------------------===//
866 
867   /// EmitDecl - Emit a declaration.
868   ///
869   /// This function can be called with a null (unreachable) insert point.
870   void EmitDecl(const Decl &D);
871 
872   /// EmitBlockVarDecl - Emit a block variable declaration.
873   ///
874   /// This function can be called with a null (unreachable) insert point.
875   void EmitBlockVarDecl(const VarDecl &D);
876 
877   /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
878   ///
879   /// This function can be called with a null (unreachable) insert point.
880   void EmitLocalBlockVarDecl(const VarDecl &D);
881 
882   void EmitStaticBlockVarDecl(const VarDecl &D,
883                               llvm::GlobalValue::LinkageTypes Linkage);
884 
885   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
886   void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
887 
888   //===--------------------------------------------------------------------===//
889   //                             Statement Emission
890   //===--------------------------------------------------------------------===//
891 
892   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
893   void EmitStopPoint(const Stmt *S);
894 
895   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
896   /// this function even if there is no current insertion point.
897   ///
898   /// This function may clear the current insertion point; callers should use
899   /// EnsureInsertPoint if they wish to subsequently generate code without first
900   /// calling EmitBlock, EmitBranch, or EmitStmt.
901   void EmitStmt(const Stmt *S);
902 
903   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
904   /// necessarily require an insertion point or debug information; typically
905   /// because the statement amounts to a jump or a container of other
906   /// statements.
907   ///
908   /// \return True if the statement was handled.
909   bool EmitSimpleStmt(const Stmt *S);
910 
911   RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
912                           llvm::Value *AggLoc = 0, bool isAggVol = false);
913 
914   /// EmitLabel - Emit the block for the given label. It is legal to call this
915   /// function even if there is no current insertion point.
916   void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
917 
918   void EmitLabelStmt(const LabelStmt &S);
919   void EmitGotoStmt(const GotoStmt &S);
920   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
921   void EmitIfStmt(const IfStmt &S);
922   void EmitWhileStmt(const WhileStmt &S);
923   void EmitDoStmt(const DoStmt &S);
924   void EmitForStmt(const ForStmt &S);
925   void EmitReturnStmt(const ReturnStmt &S);
926   void EmitDeclStmt(const DeclStmt &S);
927   void EmitBreakStmt(const BreakStmt &S);
928   void EmitContinueStmt(const ContinueStmt &S);
929   void EmitSwitchStmt(const SwitchStmt &S);
930   void EmitDefaultStmt(const DefaultStmt &S);
931   void EmitCaseStmt(const CaseStmt &S);
932   void EmitCaseStmtRange(const CaseStmt &S);
933   void EmitAsmStmt(const AsmStmt &S);
934 
935   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
936   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
937   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
938   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
939 
940   llvm::Constant *getUnwindResumeOrRethrowFn();
941   struct CXXTryStmtInfo {
942     llvm::BasicBlock *SavedLandingPad;
943     llvm::BasicBlock *HandlerBlock;
944     llvm::BasicBlock *FinallyBlock;
945   };
946   CXXTryStmtInfo EnterCXXTryStmt(const CXXTryStmt &S);
947   void ExitCXXTryStmt(const CXXTryStmt &S, CXXTryStmtInfo Info);
948 
949   void EmitCXXTryStmt(const CXXTryStmt &S);
950 
951   //===--------------------------------------------------------------------===//
952   //                         LValue Expression Emission
953   //===--------------------------------------------------------------------===//
954 
955   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
956   RValue GetUndefRValue(QualType Ty);
957 
958   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
959   /// and issue an ErrorUnsupported style diagnostic (using the
960   /// provided Name).
961   RValue EmitUnsupportedRValue(const Expr *E,
962                                const char *Name);
963 
964   /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
965   /// an ErrorUnsupported style diagnostic (using the provided Name).
966   LValue EmitUnsupportedLValue(const Expr *E,
967                                const char *Name);
968 
969   /// EmitLValue - Emit code to compute a designator that specifies the location
970   /// of the expression.
971   ///
972   /// This can return one of two things: a simple address or a bitfield
973   /// reference.  In either case, the LLVM Value* in the LValue structure is
974   /// guaranteed to be an LLVM pointer type.
975   ///
976   /// If this returns a bitfield reference, nothing about the pointee type of
977   /// the LLVM value is known: For example, it may not be a pointer to an
978   /// integer.
979   ///
980   /// If this returns a normal address, and if the lvalue's C type is fixed
981   /// size, this method guarantees that the returned pointer type will point to
982   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
983   /// variable length type, this is not possible.
984   ///
985   LValue EmitLValue(const Expr *E);
986 
987   /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
988   /// checking code to guard against undefined behavior.  This is only
989   /// suitable when we know that the address will be used to access the
990   /// object.
991   LValue EmitCheckedLValue(const Expr *E);
992 
993   /// EmitLoadOfScalar - Load a scalar value from an address, taking
994   /// care to appropriately convert from the memory representation to
995   /// the LLVM value representation.
996   llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
997                                 QualType Ty);
998 
999   /// EmitStoreOfScalar - Store a scalar value to an address, taking
1000   /// care to appropriately convert from the memory representation to
1001   /// the LLVM value representation.
1002   void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1003                          bool Volatile, QualType Ty);
1004 
1005   /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1006   /// this method emits the address of the lvalue, then loads the result as an
1007   /// rvalue, returning the rvalue.
1008   RValue EmitLoadOfLValue(LValue V, QualType LVType);
1009   RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
1010   RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
1011   RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
1012   RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
1013 
1014 
1015   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1016   /// lvalue, where both are guaranteed to the have the same type, and that type
1017   /// is 'Ty'.
1018   void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1019   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1020                                                 QualType Ty);
1021   void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
1022   void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
1023 
1024   /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1025   /// EmitStoreThroughLValue.
1026   ///
1027   /// \param Result [out] - If non-null, this will be set to a Value* for the
1028   /// bit-field contents after the store, appropriate for use as the result of
1029   /// an assignment to the bit-field.
1030   void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1031                                       llvm::Value **Result=0);
1032 
1033   // Note: only availabe for agg return types
1034   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1035   LValue EmitCompoundAssignOperatorLValue(const CompoundAssignOperator *E);
1036   // Note: only available for agg return types
1037   LValue EmitCallExprLValue(const CallExpr *E);
1038   // Note: only available for agg return types
1039   LValue EmitVAArgExprLValue(const VAArgExpr *E);
1040   LValue EmitDeclRefLValue(const DeclRefExpr *E);
1041   LValue EmitStringLiteralLValue(const StringLiteral *E);
1042   LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1043   LValue EmitPredefinedFunctionName(unsigned Type);
1044   LValue EmitPredefinedLValue(const PredefinedExpr *E);
1045   LValue EmitUnaryOpLValue(const UnaryOperator *E);
1046   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1047   LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1048   LValue EmitMemberExpr(const MemberExpr *E);
1049   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1050   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1051   LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1052   LValue EmitCastLValue(const CastExpr *E);
1053   LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E);
1054 
1055   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1056                               const ObjCIvarDecl *Ivar);
1057   LValue EmitLValueForAnonRecordField(llvm::Value* Base,
1058                                       const FieldDecl* Field,
1059                                       unsigned CVRQualifiers);
1060   LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1061                             unsigned CVRQualifiers);
1062 
1063   /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1064   /// if the Field is a reference, this will return the address of the reference
1065   /// and not the address of the value stored in the reference.
1066   LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1067                                           const FieldDecl* Field,
1068                                           unsigned CVRQualifiers);
1069 
1070   LValue EmitLValueForIvar(QualType ObjectTy,
1071                            llvm::Value* Base, const ObjCIvarDecl *Ivar,
1072                            unsigned CVRQualifiers);
1073 
1074   LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1075                                 unsigned CVRQualifiers);
1076 
1077   LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1078 
1079   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1080   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1081   LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1082   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1083 
1084   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1085   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1086   LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1087   LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1088   LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1089   LValue EmitStmtExprLValue(const StmtExpr *E);
1090   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1091 
1092   //===--------------------------------------------------------------------===//
1093   //                         Scalar Expression Emission
1094   //===--------------------------------------------------------------------===//
1095 
1096   /// EmitCall - Generate a call of the given function, expecting the given
1097   /// result type, and using the given argument list which specifies both the
1098   /// LLVM arguments and the types they were derived from.
1099   ///
1100   /// \param TargetDecl - If given, the decl of the function in a direct call;
1101   /// used to set attributes on the call (noreturn, etc.).
1102   RValue EmitCall(const CGFunctionInfo &FnInfo,
1103                   llvm::Value *Callee,
1104                   ReturnValueSlot ReturnValue,
1105                   const CallArgList &Args,
1106                   const Decl *TargetDecl = 0,
1107                   llvm::Instruction **callOrInvoke = 0);
1108 
1109   RValue EmitCall(QualType FnType, llvm::Value *Callee,
1110                   ReturnValueSlot ReturnValue,
1111                   CallExpr::const_arg_iterator ArgBeg,
1112                   CallExpr::const_arg_iterator ArgEnd,
1113                   const Decl *TargetDecl = 0);
1114   RValue EmitCallExpr(const CallExpr *E,
1115                       ReturnValueSlot ReturnValue = ReturnValueSlot());
1116 
1117   llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1118                                 const llvm::Type *Ty);
1119   llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1120                                 llvm::Value *&This, const llvm::Type *Ty);
1121 
1122   RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1123                            llvm::Value *Callee,
1124                            ReturnValueSlot ReturnValue,
1125                            llvm::Value *This,
1126                            llvm::Value *VTT,
1127                            CallExpr::const_arg_iterator ArgBeg,
1128                            CallExpr::const_arg_iterator ArgEnd);
1129   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1130                                ReturnValueSlot ReturnValue);
1131   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1132                                       ReturnValueSlot ReturnValue);
1133 
1134   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1135                                        const CXXMethodDecl *MD,
1136                                        ReturnValueSlot ReturnValue);
1137 
1138 
1139   RValue EmitBuiltinExpr(const FunctionDecl *FD,
1140                          unsigned BuiltinID, const CallExpr *E);
1141 
1142   RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1143 
1144   /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1145   /// is unhandled by the current target.
1146   llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1147 
1148   llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1149   llvm::Value *EmitNeonCall(llvm::Function *F,
1150                             llvm::SmallVectorImpl<llvm::Value*> &O,
1151                             const char *name);
1152 
1153   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1154   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1155 
1156   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1157   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1158   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1159   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
1160                              ReturnValueSlot Return = ReturnValueSlot());
1161   RValue EmitObjCPropertyGet(const Expr *E,
1162                              ReturnValueSlot Return = ReturnValueSlot());
1163   RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S,
1164                                   ReturnValueSlot Return = ReturnValueSlot());
1165   void EmitObjCPropertySet(const Expr *E, RValue Src);
1166   void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1167 
1168 
1169   /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1170   /// expression. Will emit a temporary variable if E is not an LValue.
1171   RValue EmitReferenceBindingToExpr(const Expr* E, bool IsInitializer = false);
1172 
1173   //===--------------------------------------------------------------------===//
1174   //                           Expression Emission
1175   //===--------------------------------------------------------------------===//
1176 
1177   // Expressions are broken into three classes: scalar, complex, aggregate.
1178 
1179   /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1180   /// scalar type, returning the result.
1181   llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1182 
1183   /// EmitScalarConversion - Emit a conversion from the specified type to the
1184   /// specified destination type, both of which are LLVM scalar types.
1185   llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1186                                     QualType DstTy);
1187 
1188   /// EmitComplexToScalarConversion - Emit a conversion from the specified
1189   /// complex type to the specified destination type, where the destination type
1190   /// is an LLVM scalar type.
1191   llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1192                                              QualType DstTy);
1193 
1194 
1195   /// EmitAggExpr - Emit the computation of the specified expression of
1196   /// aggregate type.  The result is computed into DestPtr.  Note that if
1197   /// DestPtr is null, the value of the aggregate expression is not needed.
1198   void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1199                    bool IgnoreResult = false, bool IsInitializer = false,
1200                    bool RequiresGCollection = false);
1201 
1202   /// EmitAggExprToLValue - Emit the computation of the specified expression of
1203   /// aggregate type into a temporary LValue.
1204   LValue EmitAggExprToLValue(const Expr *E);
1205 
1206   /// EmitGCMemmoveCollectable - Emit special API for structs with object
1207   /// pointers.
1208   void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1209                                 QualType Ty);
1210 
1211   /// EmitComplexExpr - Emit the computation of the specified expression of
1212   /// complex type, returning the result.
1213   ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1214                                 bool IgnoreImag = false,
1215                                 bool IgnoreRealAssign = false,
1216                                 bool IgnoreImagAssign = false);
1217 
1218   /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1219   /// of complex type, storing into the specified Value*.
1220   void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1221                                bool DestIsVolatile);
1222 
1223   /// StoreComplexToAddr - Store a complex number into the specified address.
1224   void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1225                           bool DestIsVolatile);
1226   /// LoadComplexFromAddr - Load a complex number from the specified address.
1227   ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1228 
1229   /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1230   /// static block var decl.
1231   llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1232                                                  const char *Separator,
1233                                        llvm::GlobalValue::LinkageTypes Linkage);
1234 
1235   /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1236   /// global variable that has already been created for it.  If the initializer
1237   /// has a different type than GV does, this may free GV and return a different
1238   /// one.  Otherwise it just returns GV.
1239   llvm::GlobalVariable *
1240   AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1241                                      llvm::GlobalVariable *GV);
1242 
1243 
1244   /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1245   /// initialized static block var decl.
1246   void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1247                                      llvm::GlobalVariable *GV);
1248 
1249   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1250   /// variable with global storage.
1251   void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1252 
1253   /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1254   /// with the C++ runtime so that its destructor will be called at exit.
1255   void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1256                                      llvm::Constant *DeclPtr);
1257 
1258   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1259   /// variables.
1260   void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1261                                  llvm::Constant **Decls,
1262                                  unsigned NumDecls);
1263 
1264   /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
1265   /// variables.
1266   void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
1267                                  const std::vector<std::pair<llvm::Constant*,
1268                                    llvm::Constant*> > &DtorsAndObjects);
1269 
1270   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1271 
1272   void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1273 
1274   RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1275                                     llvm::Value *AggLoc = 0,
1276                                     bool IsAggLocVolatile = false,
1277                                     bool IsInitializer = false);
1278 
1279   void EmitCXXThrowExpr(const CXXThrowExpr *E);
1280 
1281   //===--------------------------------------------------------------------===//
1282   //                             Internal Helpers
1283   //===--------------------------------------------------------------------===//
1284 
1285   /// ContainsLabel - Return true if the statement contains a label in it.  If
1286   /// this statement is not executed normally, it not containing a label means
1287   /// that we can just remove the code.
1288   static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1289 
1290   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1291   /// to a constant, or if it does but contains a label, return 0.  If it
1292   /// constant folds to 'true' and does not contain a label, return 1, if it
1293   /// constant folds to 'false' and does not contain a label, return -1.
1294   int ConstantFoldsToSimpleInteger(const Expr *Cond);
1295 
1296   /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1297   /// if statement) to the specified blocks.  Based on the condition, this might
1298   /// try to simplify the codegen of the conditional based on the branch.
1299   void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1300                             llvm::BasicBlock *FalseBlock);
1301 
1302   /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1303   /// generate a branch around the created basic block as necessary.
1304   llvm::BasicBlock* getTrapBB();
1305 
1306   /// EmitCallArg - Emit a single call argument.
1307   RValue EmitCallArg(const Expr *E, QualType ArgType);
1308 
1309   /// EmitDelegateCallArg - We are performing a delegate call; that
1310   /// is, the current function is delegating to another one.  Produce
1311   /// a r-value suitable for passing the given parameter.
1312   RValue EmitDelegateCallArg(const VarDecl *Param);
1313 
1314 private:
1315 
1316   void EmitReturnOfRValue(RValue RV, QualType Ty);
1317 
1318   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1319   /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1320   ///
1321   /// \param AI - The first function argument of the expansion.
1322   /// \return The argument following the last expanded function
1323   /// argument.
1324   llvm::Function::arg_iterator
1325   ExpandTypeFromArgs(QualType Ty, LValue Dst,
1326                      llvm::Function::arg_iterator AI);
1327 
1328   /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1329   /// Ty, into individual arguments on the provided vector \arg Args. See
1330   /// ABIArgInfo::Expand.
1331   void ExpandTypeToArgs(QualType Ty, RValue Src,
1332                         llvm::SmallVector<llvm::Value*, 16> &Args);
1333 
1334   llvm::Value* EmitAsmInput(const AsmStmt &S,
1335                             const TargetInfo::ConstraintInfo &Info,
1336                             const Expr *InputExpr, std::string &ConstraintStr);
1337 
1338   /// EmitCleanupBlock - emits a single cleanup block.
1339   void EmitCleanupBlock();
1340 
1341   /// AddBranchFixup - adds a branch instruction to the list of fixups for the
1342   /// current cleanup scope.
1343   void AddBranchFixup(llvm::BranchInst *BI);
1344 
1345   /// EmitCallArgs - Emit call arguments for a function.
1346   /// The CallArgTypeInfo parameter is used for iterating over the known
1347   /// argument types of the function being called.
1348   template<typename T>
1349   void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1350                     CallExpr::const_arg_iterator ArgBeg,
1351                     CallExpr::const_arg_iterator ArgEnd) {
1352       CallExpr::const_arg_iterator Arg = ArgBeg;
1353 
1354     // First, use the argument types that the type info knows about
1355     if (CallArgTypeInfo) {
1356       for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1357            E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1358         assert(Arg != ArgEnd && "Running over edge of argument list!");
1359         QualType ArgType = *I;
1360 
1361         assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1362                getTypePtr() ==
1363                getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1364                "type mismatch in call argument!");
1365 
1366         Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1367                                       ArgType));
1368       }
1369 
1370       // Either we've emitted all the call args, or we have a call to a
1371       // variadic function.
1372       assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1373              "Extra arguments in non-variadic function!");
1374 
1375     }
1376 
1377     // If we still have any arguments, emit them using the type of the argument.
1378     for (; Arg != ArgEnd; ++Arg) {
1379       QualType ArgType = Arg->getType();
1380       Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1381                                     ArgType));
1382     }
1383   }
1384 
1385   const TargetCodeGenInfo &getTargetHooks() const {
1386     return CGM.getTargetCodeGenInfo();
1387   }
1388 };
1389 
1390 
1391 }  // end namespace CodeGen
1392 }  // end namespace clang
1393 
1394 #endif
1395