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