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