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