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