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   /// BeginConditionalBranch - 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 BeginConditionalBranch() {
280     ++ConditionalBranchLevel;
281   }
282 
283   /// EndConditionalBranch - Should be called after a conditional part of an
284   /// expression has been emitted.
285   void EndConditionalBranch() {
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. The caller is responsible for setting an appropriate alignment on
659   /// the alloca.
660   llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
661                                      const llvm::Twine &Name = "tmp");
662 
663   /// CreateMemTemp - Create a temporary memory object of the given type, with
664   /// appropriate alignment.
665   llvm::Value *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
666 
667   /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
668   /// expression and compare the result against zero, returning an Int1Ty value.
669   llvm::Value *EvaluateExprAsBool(const Expr *E);
670 
671   /// EmitAnyExpr - Emit code to compute the specified expression which can have
672   /// any type.  The result is returned as an RValue struct.  If this is an
673   /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
674   /// the result should be returned.
675   ///
676   /// \param IgnoreResult - True if the resulting value isn't used.
677   RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
678                      bool IsAggLocVolatile = false, bool IgnoreResult = false,
679                      bool IsInitializer = false);
680 
681   // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
682   // or the value of the expression, depending on how va_list is defined.
683   llvm::Value *EmitVAListRef(const Expr *E);
684 
685   /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
686   /// always be accessible even if no aggregate location is provided.
687   RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
688                            bool IsInitializer = false);
689 
690   /// EmitAggregateCopy - Emit an aggrate copy.
691   ///
692   /// \param isVolatile - True iff either the source or the destination is
693   /// volatile.
694   void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
695                          QualType EltTy, bool isVolatile=false);
696 
697   void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty);
698 
699   /// StartBlock - Start new block named N. If insert block is a dummy block
700   /// then reuse it.
701   void StartBlock(const char *N);
702 
703   /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
704   llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
705 
706   /// GetAddrOfLocalVar - Return the address of a local variable.
707   llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
708 
709   /// getAccessedFieldNo - Given an encoded value and a result number, return
710   /// the input field number being accessed.
711   static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
712 
713   llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
714   llvm::BasicBlock *GetIndirectGotoBlock();
715 
716   /// EmitMemSetToZero - Generate code to memset a value of the given type to 0.
717   void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty);
718 
719   // EmitVAArg - Generate code to get an argument from the passed in pointer
720   // and update it accordingly. The return value is a pointer to the argument.
721   // FIXME: We should be able to get rid of this method and use the va_arg
722   // instruction in LLVM instead once it works well enough.
723   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
724 
725   /// EmitVLASize - Generate code for any VLA size expressions that might occur
726   /// in a variably modified type. If Ty is a VLA, will return the value that
727   /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
728   ///
729   /// This function can be called with a null (unreachable) insert point.
730   llvm::Value *EmitVLASize(QualType Ty);
731 
732   // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
733   // of a variable length array type.
734   llvm::Value *GetVLASize(const VariableArrayType *);
735 
736   /// LoadCXXThis - Load the value of 'this'. This function is only valid while
737   /// generating code for an C++ member function.
738   llvm::Value *LoadCXXThis();
739 
740   /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
741   /// virtual bases.
742   llvm::Value *LoadCXXVTT();
743 
744   /// GetAddressOfBaseClass - This function will add the necessary delta to the
745   /// load of 'this' and returns address of the base class.
746   // FIXME. This currently only does a derived to non-virtual base conversion.
747   // Other kinds of conversions will come later.
748   llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
749                                      const CXXRecordDecl *ClassDecl,
750                                      const CXXRecordDecl *BaseClassDecl,
751                                      bool NullCheckValue);
752 
753   llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
754                                         const CXXRecordDecl *ClassDecl,
755                                         const CXXRecordDecl *DerivedClassDecl,
756                                         bool NullCheckValue);
757 
758   llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
759                                          const CXXRecordDecl *ClassDecl,
760                                          const CXXRecordDecl *BaseClassDecl);
761 
762   void EmitClassAggrMemberwiseCopy(llvm::Value *DestValue,
763                                    llvm::Value *SrcValue,
764                                    const ArrayType *Array,
765                                    const CXXRecordDecl *BaseClassDecl,
766                                    QualType Ty);
767 
768   void EmitClassAggrCopyAssignment(llvm::Value *DestValue,
769                                    llvm::Value *SrcValue,
770                                    const ArrayType *Array,
771                                    const CXXRecordDecl *BaseClassDecl,
772                                    QualType Ty);
773 
774   void EmitClassMemberwiseCopy(llvm::Value *DestValue, llvm::Value *SrcValue,
775                                const CXXRecordDecl *ClassDecl,
776                                const CXXRecordDecl *BaseClassDecl,
777                                QualType Ty);
778 
779   void EmitClassCopyAssignment(llvm::Value *DestValue, llvm::Value *SrcValue,
780                                const CXXRecordDecl *ClassDecl,
781                                const CXXRecordDecl *BaseClassDecl,
782                                QualType Ty);
783 
784   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
785                               llvm::Value *This,
786                               CallExpr::const_arg_iterator ArgBeg,
787                               CallExpr::const_arg_iterator ArgEnd);
788 
789   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
790                                   const ConstantArrayType *ArrayTy,
791                                   llvm::Value *ArrayPtr,
792                                   CallExpr::const_arg_iterator ArgBeg,
793                                   CallExpr::const_arg_iterator ArgEnd);
794 
795   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
796                                   llvm::Value *NumElements,
797                                   llvm::Value *ArrayPtr,
798                                   CallExpr::const_arg_iterator ArgBeg,
799                                   CallExpr::const_arg_iterator ArgEnd);
800 
801   void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
802                                  const ArrayType *Array,
803                                  llvm::Value *This);
804 
805   void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
806                                  llvm::Value *NumElements,
807                                  llvm::Value *This);
808 
809   llvm::Constant *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
810                                                 const ArrayType *Array,
811                                                 llvm::Value *This);
812 
813   void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
814                              llvm::Value *This);
815 
816   void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
817   void PopCXXTemporary();
818 
819   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
820   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
821 
822   void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
823                       QualType DeleteTy);
824 
825   llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
826   llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
827 
828   void EmitCheck(llvm::Value *, unsigned Size);
829 
830   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
831                                        bool isInc, bool isPre);
832   ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
833                                          bool isInc, bool isPre);
834   //===--------------------------------------------------------------------===//
835   //                            Declaration Emission
836   //===--------------------------------------------------------------------===//
837 
838   /// EmitDecl - Emit a declaration.
839   ///
840   /// This function can be called with a null (unreachable) insert point.
841   void EmitDecl(const Decl &D);
842 
843   /// EmitBlockVarDecl - Emit a block variable declaration.
844   ///
845   /// This function can be called with a null (unreachable) insert point.
846   void EmitBlockVarDecl(const VarDecl &D);
847 
848   /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
849   ///
850   /// This function can be called with a null (unreachable) insert point.
851   void EmitLocalBlockVarDecl(const VarDecl &D);
852 
853   void EmitStaticBlockVarDecl(const VarDecl &D,
854                               llvm::GlobalValue::LinkageTypes Linkage);
855 
856   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
857   void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
858 
859   //===--------------------------------------------------------------------===//
860   //                             Statement Emission
861   //===--------------------------------------------------------------------===//
862 
863   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
864   void EmitStopPoint(const Stmt *S);
865 
866   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
867   /// this function even if there is no current insertion point.
868   ///
869   /// This function may clear the current insertion point; callers should use
870   /// EnsureInsertPoint if they wish to subsequently generate code without first
871   /// calling EmitBlock, EmitBranch, or EmitStmt.
872   void EmitStmt(const Stmt *S);
873 
874   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
875   /// necessarily require an insertion point or debug information; typically
876   /// because the statement amounts to a jump or a container of other
877   /// statements.
878   ///
879   /// \return True if the statement was handled.
880   bool EmitSimpleStmt(const Stmt *S);
881 
882   RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
883                           llvm::Value *AggLoc = 0, bool isAggVol = false);
884 
885   /// EmitLabel - Emit the block for the given label. It is legal to call this
886   /// function even if there is no current insertion point.
887   void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
888 
889   void EmitLabelStmt(const LabelStmt &S);
890   void EmitGotoStmt(const GotoStmt &S);
891   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
892   void EmitIfStmt(const IfStmt &S);
893   void EmitWhileStmt(const WhileStmt &S);
894   void EmitDoStmt(const DoStmt &S);
895   void EmitForStmt(const ForStmt &S);
896   void EmitReturnStmt(const ReturnStmt &S);
897   void EmitDeclStmt(const DeclStmt &S);
898   void EmitBreakStmt(const BreakStmt &S);
899   void EmitContinueStmt(const ContinueStmt &S);
900   void EmitSwitchStmt(const SwitchStmt &S);
901   void EmitDefaultStmt(const DefaultStmt &S);
902   void EmitCaseStmt(const CaseStmt &S);
903   void EmitCaseStmtRange(const CaseStmt &S);
904   void EmitAsmStmt(const AsmStmt &S);
905 
906   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
907   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
908   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
909   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
910 
911   void EmitCXXTryStmt(const CXXTryStmt &S);
912 
913   //===--------------------------------------------------------------------===//
914   //                         LValue Expression Emission
915   //===--------------------------------------------------------------------===//
916 
917   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
918   RValue GetUndefRValue(QualType Ty);
919 
920   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
921   /// and issue an ErrorUnsupported style diagnostic (using the
922   /// provided Name).
923   RValue EmitUnsupportedRValue(const Expr *E,
924                                const char *Name);
925 
926   /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
927   /// an ErrorUnsupported style diagnostic (using the provided Name).
928   LValue EmitUnsupportedLValue(const Expr *E,
929                                const char *Name);
930 
931   /// EmitLValue - Emit code to compute a designator that specifies the location
932   /// of the expression.
933   ///
934   /// This can return one of two things: a simple address or a bitfield
935   /// reference.  In either case, the LLVM Value* in the LValue structure is
936   /// guaranteed to be an LLVM pointer type.
937   ///
938   /// If this returns a bitfield reference, nothing about the pointee type of
939   /// the LLVM value is known: For example, it may not be a pointer to an
940   /// integer.
941   ///
942   /// If this returns a normal address, and if the lvalue's C type is fixed
943   /// size, this method guarantees that the returned pointer type will point to
944   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
945   /// variable length type, this is not possible.
946   ///
947   LValue EmitLValue(const Expr *E);
948 
949   /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
950   /// checking code to guard against undefined behavior.  This is only
951   /// suitable when we know that the address will be used to access the
952   /// object.
953   LValue EmitCheckedLValue(const Expr *E);
954 
955   /// EmitLoadOfScalar - Load a scalar value from an address, taking
956   /// care to appropriately convert from the memory representation to
957   /// the LLVM value representation.
958   llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
959                                 QualType Ty);
960 
961   /// EmitStoreOfScalar - Store a scalar value to an address, taking
962   /// care to appropriately convert from the memory representation to
963   /// the LLVM value representation.
964   void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
965                          bool Volatile, QualType Ty);
966 
967   /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
968   /// this method emits the address of the lvalue, then loads the result as an
969   /// rvalue, returning the rvalue.
970   RValue EmitLoadOfLValue(LValue V, QualType LVType);
971   RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
972   RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
973   RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
974   RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
975 
976 
977   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
978   /// lvalue, where both are guaranteed to the have the same type, and that type
979   /// is 'Ty'.
980   void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
981   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
982                                                 QualType Ty);
983   void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
984   void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
985 
986   /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
987   /// EmitStoreThroughLValue.
988   ///
989   /// \param Result [out] - If non-null, this will be set to a Value* for the
990   /// bit-field contents after the store, appropriate for use as the result of
991   /// an assignment to the bit-field.
992   void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
993                                       llvm::Value **Result=0);
994 
995   // Note: only availabe for agg return types
996   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
997   // Note: only available for agg return types
998   LValue EmitCallExprLValue(const CallExpr *E);
999   // Note: only available for agg return types
1000   LValue EmitVAArgExprLValue(const VAArgExpr *E);
1001   LValue EmitDeclRefLValue(const DeclRefExpr *E);
1002   LValue EmitStringLiteralLValue(const StringLiteral *E);
1003   LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1004   LValue EmitPredefinedFunctionName(unsigned Type);
1005   LValue EmitPredefinedLValue(const PredefinedExpr *E);
1006   LValue EmitUnaryOpLValue(const UnaryOperator *E);
1007   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1008   LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1009   LValue EmitMemberExpr(const MemberExpr *E);
1010   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1011   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1012   LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1013   LValue EmitCastLValue(const CastExpr *E);
1014   LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E);
1015 
1016   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1017                               const ObjCIvarDecl *Ivar);
1018   LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1019                             unsigned CVRQualifiers);
1020 
1021   /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1022   /// if the Field is a reference, this will return the address of the reference
1023   /// and not the address of the value stored in the reference.
1024   LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1025                                           const FieldDecl* Field,
1026                                           unsigned CVRQualifiers);
1027 
1028   LValue EmitLValueForIvar(QualType ObjectTy,
1029                            llvm::Value* Base, const ObjCIvarDecl *Ivar,
1030                            unsigned CVRQualifiers);
1031 
1032   LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1033                                 unsigned CVRQualifiers);
1034 
1035   LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1036 
1037   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1038   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1039   LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1040   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1041 
1042   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1043   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1044   LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1045   LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1046   LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1047   LValue EmitStmtExprLValue(const StmtExpr *E);
1048   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1049 
1050   //===--------------------------------------------------------------------===//
1051   //                         Scalar Expression Emission
1052   //===--------------------------------------------------------------------===//
1053 
1054   /// EmitCall - Generate a call of the given function, expecting the given
1055   /// result type, and using the given argument list which specifies both the
1056   /// LLVM arguments and the types they were derived from.
1057   ///
1058   /// \param TargetDecl - If given, the decl of the function in a direct call;
1059   /// used to set attributes on the call (noreturn, etc.).
1060   RValue EmitCall(const CGFunctionInfo &FnInfo,
1061                   llvm::Value *Callee,
1062                   ReturnValueSlot ReturnValue,
1063                   const CallArgList &Args,
1064                   const Decl *TargetDecl = 0);
1065 
1066   RValue EmitCall(QualType FnType, llvm::Value *Callee,
1067                   ReturnValueSlot ReturnValue,
1068                   CallExpr::const_arg_iterator ArgBeg,
1069                   CallExpr::const_arg_iterator ArgEnd,
1070                   const Decl *TargetDecl = 0);
1071   RValue EmitCallExpr(const CallExpr *E,
1072                       ReturnValueSlot ReturnValue = ReturnValueSlot());
1073 
1074   llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1075                                 const llvm::Type *Ty);
1076   llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1077                                 llvm::Value *&This, const llvm::Type *Ty);
1078 
1079   RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1080                            llvm::Value *Callee,
1081                            ReturnValueSlot ReturnValue,
1082                            llvm::Value *This,
1083                            llvm::Value *VTT,
1084                            CallExpr::const_arg_iterator ArgBeg,
1085                            CallExpr::const_arg_iterator ArgEnd);
1086   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1087                                ReturnValueSlot ReturnValue);
1088   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1089                                       ReturnValueSlot ReturnValue);
1090 
1091   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1092                                        const CXXMethodDecl *MD,
1093                                        ReturnValueSlot ReturnValue);
1094 
1095 
1096   RValue EmitBuiltinExpr(const FunctionDecl *FD,
1097                          unsigned BuiltinID, const CallExpr *E);
1098 
1099   RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1100 
1101   /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1102   /// is unhandled by the current target.
1103   llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1104 
1105   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1106   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1107 
1108   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1109   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1110   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1111   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E);
1112   RValue EmitObjCPropertyGet(const Expr *E);
1113   RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S);
1114   void EmitObjCPropertySet(const Expr *E, RValue Src);
1115   void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1116 
1117 
1118   /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1119   /// expression. Will emit a temporary variable if E is not an LValue.
1120   RValue EmitReferenceBindingToExpr(const Expr* E, bool IsInitializer = false);
1121 
1122   //===--------------------------------------------------------------------===//
1123   //                           Expression Emission
1124   //===--------------------------------------------------------------------===//
1125 
1126   // Expressions are broken into three classes: scalar, complex, aggregate.
1127 
1128   /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1129   /// scalar type, returning the result.
1130   llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1131 
1132   /// EmitScalarConversion - Emit a conversion from the specified type to the
1133   /// specified destination type, both of which are LLVM scalar types.
1134   llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1135                                     QualType DstTy);
1136 
1137   /// EmitComplexToScalarConversion - Emit a conversion from the specified
1138   /// complex type to the specified destination type, where the destination type
1139   /// is an LLVM scalar type.
1140   llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1141                                              QualType DstTy);
1142 
1143 
1144   /// EmitAggExpr - Emit the computation of the specified expression of
1145   /// aggregate type.  The result is computed into DestPtr.  Note that if
1146   /// DestPtr is null, the value of the aggregate expression is not needed.
1147   void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1148                    bool IgnoreResult = false, bool IsInitializer = false,
1149                    bool RequiresGCollection = false);
1150 
1151   /// EmitAggExprToLValue - Emit the computation of the specified expression of
1152   /// aggregate type into a temporary LValue.
1153   LValue EmitAggExprToLValue(const Expr *E);
1154 
1155   /// EmitGCMemmoveCollectable - Emit special API for structs with object
1156   /// pointers.
1157   void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1158                                 QualType Ty);
1159 
1160   /// EmitComplexExpr - Emit the computation of the specified expression of
1161   /// complex type, returning the result.
1162   ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1163                                 bool IgnoreImag = false,
1164                                 bool IgnoreRealAssign = false,
1165                                 bool IgnoreImagAssign = false);
1166 
1167   /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1168   /// of complex type, storing into the specified Value*.
1169   void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1170                                bool DestIsVolatile);
1171 
1172   /// StoreComplexToAddr - Store a complex number into the specified address.
1173   void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1174                           bool DestIsVolatile);
1175   /// LoadComplexFromAddr - Load a complex number from the specified address.
1176   ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1177 
1178   /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1179   /// static block var decl.
1180   llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1181                                                  const char *Separator,
1182                                        llvm::GlobalValue::LinkageTypes Linkage);
1183 
1184   /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1185   /// global variable that has already been created for it.  If the initializer
1186   /// has a different type than GV does, this may free GV and return a different
1187   /// one.  Otherwise it just returns GV.
1188   llvm::GlobalVariable *
1189   AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1190                                      llvm::GlobalVariable *GV);
1191 
1192 
1193   /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1194   /// initialized static block var decl.
1195   void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1196                                      llvm::GlobalVariable *GV);
1197 
1198   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1199   /// variable with global storage.
1200   void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1201 
1202   /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1203   /// with the C++ runtime so that its destructor will be called at exit.
1204   void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1205                                      llvm::Constant *DeclPtr);
1206 
1207   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1208   /// variables.
1209   void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1210                                  llvm::Constant **Decls,
1211                                  unsigned NumDecls);
1212 
1213   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1214 
1215   void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1216 
1217   RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1218                                     llvm::Value *AggLoc = 0,
1219                                     bool IsAggLocVolatile = false,
1220                                     bool IsInitializer = false);
1221 
1222   void EmitCXXThrowExpr(const CXXThrowExpr *E);
1223 
1224   //===--------------------------------------------------------------------===//
1225   //                             Internal Helpers
1226   //===--------------------------------------------------------------------===//
1227 
1228   /// ContainsLabel - Return true if the statement contains a label in it.  If
1229   /// this statement is not executed normally, it not containing a label means
1230   /// that we can just remove the code.
1231   static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1232 
1233   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1234   /// to a constant, or if it does but contains a label, return 0.  If it
1235   /// constant folds to 'true' and does not contain a label, return 1, if it
1236   /// constant folds to 'false' and does not contain a label, return -1.
1237   int ConstantFoldsToSimpleInteger(const Expr *Cond);
1238 
1239   /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1240   /// if statement) to the specified blocks.  Based on the condition, this might
1241   /// try to simplify the codegen of the conditional based on the branch.
1242   void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1243                             llvm::BasicBlock *FalseBlock);
1244 
1245   /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1246   /// generate a branch around the created basic block as necessary.
1247   llvm::BasicBlock* getTrapBB();
1248 private:
1249 
1250   void EmitReturnOfRValue(RValue RV, QualType Ty);
1251 
1252   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1253   /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1254   ///
1255   /// \param AI - The first function argument of the expansion.
1256   /// \return The argument following the last expanded function
1257   /// argument.
1258   llvm::Function::arg_iterator
1259   ExpandTypeFromArgs(QualType Ty, LValue Dst,
1260                      llvm::Function::arg_iterator AI);
1261 
1262   /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1263   /// Ty, into individual arguments on the provided vector \arg Args. See
1264   /// ABIArgInfo::Expand.
1265   void ExpandTypeToArgs(QualType Ty, RValue Src,
1266                         llvm::SmallVector<llvm::Value*, 16> &Args);
1267 
1268   llvm::Value* EmitAsmInput(const AsmStmt &S,
1269                             const TargetInfo::ConstraintInfo &Info,
1270                             const Expr *InputExpr, std::string &ConstraintStr);
1271 
1272   /// EmitCleanupBlock - emits a single cleanup block.
1273   void EmitCleanupBlock();
1274 
1275   /// AddBranchFixup - adds a branch instruction to the list of fixups for the
1276   /// current cleanup scope.
1277   void AddBranchFixup(llvm::BranchInst *BI);
1278 
1279   /// EmitCallArg - Emit a single call argument.
1280   RValue EmitCallArg(const Expr *E, QualType ArgType);
1281 
1282   /// EmitCallArgs - Emit call arguments for a function.
1283   /// The CallArgTypeInfo parameter is used for iterating over the known
1284   /// argument types of the function being called.
1285   template<typename T>
1286   void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1287                     CallExpr::const_arg_iterator ArgBeg,
1288                     CallExpr::const_arg_iterator ArgEnd) {
1289       CallExpr::const_arg_iterator Arg = ArgBeg;
1290 
1291     // First, use the argument types that the type info knows about
1292     if (CallArgTypeInfo) {
1293       for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1294            E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1295         assert(Arg != ArgEnd && "Running over edge of argument list!");
1296         QualType ArgType = *I;
1297 
1298         assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1299                getTypePtr() ==
1300                getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1301                "type mismatch in call argument!");
1302 
1303         Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1304                                       ArgType));
1305       }
1306 
1307       // Either we've emitted all the call args, or we have a call to a
1308       // variadic function.
1309       assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1310              "Extra arguments in non-variadic function!");
1311 
1312     }
1313 
1314     // If we still have any arguments, emit them using the type of the argument.
1315     for (; Arg != ArgEnd; ++Arg) {
1316       QualType ArgType = Arg->getType();
1317       Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1318                                     ArgType));
1319     }
1320   }
1321 };
1322 
1323 
1324 }  // end namespace CodeGen
1325 }  // end namespace clang
1326 
1327 #endif
1328