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