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