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