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