CodeGenFunction.h revision 3b2e16b3d25f6b311dba2871e2a566c96238c3d2
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 struct 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 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 228 // enter/leave scopes. 229 llvm::DenseMap<const VariableArrayType*, llvm::Value*> VLASizeMap; 230 231 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 232 /// calling llvm.stacksave for multiple VLAs in the same scope. 233 bool DidCallStackSave; 234 235 struct CleanupEntry { 236 /// CleanupBlock - The block of code that does the actual cleanup. 237 llvm::BasicBlock *CleanupBlock; 238 239 /// Blocks - Basic blocks that were emitted in the current cleanup scope. 240 std::vector<llvm::BasicBlock *> Blocks; 241 242 /// BranchFixups - Branch instructions to basic blocks that haven't been 243 /// inserted into the current function yet. 244 std::vector<llvm::BranchInst *> BranchFixups; 245 246 explicit CleanupEntry(llvm::BasicBlock *cb) 247 : CleanupBlock(cb) {} 248 }; 249 250 /// CleanupEntries - Stack of cleanup entries. 251 llvm::SmallVector<CleanupEntry, 8> CleanupEntries; 252 253 typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap; 254 255 /// BlockScopes - Map of which "cleanup scope" scope basic blocks have. 256 BlockScopeMap BlockScopes; 257 258 /// CXXThisDecl - When parsing an C++ function, this will hold the implicit 259 /// 'this' declaration. 260 ImplicitParamDecl *CXXThisDecl; 261 262 /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary. 263 struct CXXLiveTemporaryInfo { 264 /// Temporary - The live temporary. 265 const CXXTemporary *Temporary; 266 267 /// ThisPtr - The pointer to the temporary. 268 llvm::Value *ThisPtr; 269 270 /// DtorBlock - The destructor block. 271 llvm::BasicBlock *DtorBlock; 272 273 /// CondPtr - If this is a conditional temporary, this is the pointer to 274 /// the condition variable that states whether the destructor should be 275 /// called or not. 276 llvm::Value *CondPtr; 277 278 CXXLiveTemporaryInfo(const CXXTemporary *temporary, 279 llvm::Value *thisptr, llvm::BasicBlock *dtorblock, 280 llvm::Value *condptr) 281 : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock), 282 CondPtr(condptr) { } 283 }; 284 285 llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries; 286 287 /// ConditionalTempDestructionStack - Contains the number of live temporaries 288 /// when PushConditionalTempDestruction was called. This is used so that 289 /// we know how many temporaries were created by a certain expression. 290 llvm::SmallVector<size_t, 4> ConditionalTempDestructionStack; 291 292public: 293 CodeGenFunction(CodeGenModule &cgm); 294 295 ASTContext &getContext() const; 296 CGDebugInfo *getDebugInfo() { return DebugInfo; } 297 298 llvm::BasicBlock *getInvokeDest() { return InvokeDest; } 299 void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; } 300 301 llvm::LLVMContext &getLLVMContext() { return VMContext; } 302 303 //===--------------------------------------------------------------------===// 304 // Objective-C 305 //===--------------------------------------------------------------------===// 306 307 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 308 309 void StartObjCMethod(const ObjCMethodDecl *MD, 310 const ObjCContainerDecl *CD); 311 312 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 313 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 314 const ObjCPropertyImplDecl *PID); 315 316 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 317 /// for the given property. 318 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 319 const ObjCPropertyImplDecl *PID); 320 321 //===--------------------------------------------------------------------===// 322 // Block Bits 323 //===--------------------------------------------------------------------===// 324 325 llvm::Value *BuildBlockLiteralTmp(const BlockExpr *); 326 llvm::Constant *BuildDescriptorBlockDecl(bool BlockHasCopyDispose, 327 uint64_t Size, 328 const llvm::StructType *, 329 std::vector<HelperInfo> *); 330 331 llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr, 332 const BlockInfo& Info, 333 const Decl *OuterFuncDecl, 334 llvm::DenseMap<const Decl*, llvm::Value*> ldm, 335 uint64_t &Size, uint64_t &Align, 336 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls, 337 bool &subBlockHasCopyDispose); 338 339 void BlockForwardSelf(); 340 llvm::Value *LoadBlockStruct(); 341 342 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E); 343 344 const llvm::Type *BuildByRefType(QualType Ty, uint64_t Align); 345 346 void GenerateCode(const FunctionDecl *FD, 347 llvm::Function *Fn); 348 void StartFunction(const Decl *D, QualType RetTy, 349 llvm::Function *Fn, 350 const FunctionArgList &Args, 351 SourceLocation StartLoc); 352 353 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 354 /// emission when possible. 355 void EmitReturnBlock(); 356 357 /// FinishFunction - Complete IR generation of the current function. It is 358 /// legal to call this function even if there is no current insertion point. 359 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 360 361 llvm::Constant *GenerateRtti(const CXXRecordDecl *RD); 362 void GenerateVtableForBase(const CXXRecordDecl *RD, 363 const CXXRecordDecl *Class, 364 llvm::Constant *rtti, 365 std::vector<llvm::Constant *> &methods, 366 bool isPrimary = false, 367 bool ForVirtualBase = false); 368 llvm::Value *GenerateVtable(const CXXRecordDecl *RD); 369 370 void EmitCtorPrologue(const CXXConstructorDecl *CD); 371 372 void SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD, 373 const FunctionDecl *FD, 374 llvm::Function *Fn, 375 const FunctionArgList &Args); 376 377 /// EmitDtorEpilogue - Emit all code that comes at the end of class's 378 /// destructor. This is to call destructors on members and base classes 379 /// in reverse order of their construction. 380 void EmitDtorEpilogue(const CXXDestructorDecl *DD); 381 382 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 383 /// arguments for the given function. This is also responsible for naming the 384 /// LLVM function arguments. 385 void EmitFunctionProlog(const CGFunctionInfo &FI, 386 llvm::Function *Fn, 387 const FunctionArgList &Args); 388 389 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 390 /// given temporary. 391 void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue); 392 393 const llvm::Type *ConvertTypeForMem(QualType T); 394 const llvm::Type *ConvertType(QualType T); 395 396 /// LoadObjCSelf - Load the value of self. This function is only valid while 397 /// generating code for an Objective-C method. 398 llvm::Value *LoadObjCSelf(); 399 400 /// TypeOfSelfObject - Return type of object that this self represents. 401 QualType TypeOfSelfObject(); 402 403 /// hasAggregateLLVMType - Return true if the specified AST type will map into 404 /// an aggregate LLVM type or is void. 405 static bool hasAggregateLLVMType(QualType T); 406 407 /// createBasicBlock - Create an LLVM basic block. 408 llvm::BasicBlock *createBasicBlock(const char *Name="", 409 llvm::Function *Parent=0, 410 llvm::BasicBlock *InsertBefore=0) { 411#ifdef NDEBUG 412 return llvm::BasicBlock::Create("", Parent, InsertBefore); 413#else 414 return llvm::BasicBlock::Create(Name, Parent, InsertBefore); 415#endif 416 } 417 418 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 419 /// label maps to. 420 llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S); 421 422 /// SimplifyForwardingBlocks - If the given basic block is only a 423 /// branch to another basic block, simplify it. This assumes that no 424 /// other code could potentially reference the basic block. 425 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 426 427 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 428 /// adding a fall-through branch from the current insert block if 429 /// necessary. It is legal to call this function even if there is no current 430 /// insertion point. 431 /// 432 /// IsFinished - If true, indicates that the caller has finished emitting 433 /// branches to the given block and does not expect to emit code into it. This 434 /// means the block can be ignored if it is unreachable. 435 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 436 437 /// EmitBranch - Emit a branch to the specified basic block from the current 438 /// insert block, taking care to avoid creation of branches from dummy 439 /// blocks. It is legal to call this function even if there is no current 440 /// insertion point. 441 /// 442 /// This function clears the current insertion point. The caller should follow 443 /// calls to this function with calls to Emit*Block prior to generation new 444 /// code. 445 void EmitBranch(llvm::BasicBlock *Block); 446 447 /// HaveInsertPoint - True if an insertion point is defined. If not, this 448 /// indicates that the current code being emitted is unreachable. 449 bool HaveInsertPoint() const { 450 return Builder.GetInsertBlock() != 0; 451 } 452 453 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 454 /// emitted IR has a place to go. Note that by definition, if this function 455 /// creates a block then that block is unreachable; callers may do better to 456 /// detect when no insertion point is defined and simply skip IR generation. 457 void EnsureInsertPoint() { 458 if (!HaveInsertPoint()) 459 EmitBlock(createBasicBlock()); 460 } 461 462 /// ErrorUnsupported - Print out an error that codegen doesn't support the 463 /// specified stmt yet. 464 void ErrorUnsupported(const Stmt *S, const char *Type, 465 bool OmitOnError=false); 466 467 //===--------------------------------------------------------------------===// 468 // Helpers 469 //===--------------------------------------------------------------------===// 470 471 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 472 /// block. 473 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty, 474 const char *Name = "tmp"); 475 476 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 477 /// expression and compare the result against zero, returning an Int1Ty value. 478 llvm::Value *EvaluateExprAsBool(const Expr *E); 479 480 /// EmitAnyExpr - Emit code to compute the specified expression which can have 481 /// any type. The result is returned as an RValue struct. If this is an 482 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 483 /// the result should be returned. 484 /// 485 /// \param IgnoreResult - True if the resulting value isn't used. 486 RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0, 487 bool isAggLocVolatile = false, bool IgnoreResult = false); 488 489 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 490 // or the value of the expression, depending on how va_list is defined. 491 llvm::Value *EmitVAListRef(const Expr *E); 492 493 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 494 /// always be accessible even if no aggregate location is provided. 495 RValue EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc = 0, 496 bool isAggLocVolatile = false); 497 498 /// EmitAggregateCopy - Emit an aggrate copy. 499 /// 500 /// \param isVolatile - True iff either the source or the destination is 501 /// volatile. 502 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 503 QualType EltTy, bool isVolatile=false); 504 505 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 506 507 /// StartBlock - Start new block named N. If insert block is a dummy block 508 /// then reuse it. 509 void StartBlock(const char *N); 510 511 /// getCGRecordLayout - Return record layout info. 512 const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy); 513 514 /// GetAddrOfStaticLocalVar - Return the address of a static local variable. 515 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD); 516 517 /// GetAddrOfLocalVar - Return the address of a local variable. 518 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD); 519 520 /// getAccessedFieldNo - Given an encoded value and a result number, return 521 /// the input field number being accessed. 522 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 523 524 unsigned GetIDForAddrOfLabel(const LabelStmt *L); 525 526 /// EmitMemSetToZero - Generate code to memset a value of the given type to 0. 527 void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty); 528 529 // EmitVAArg - Generate code to get an argument from the passed in pointer 530 // and update it accordingly. The return value is a pointer to the argument. 531 // FIXME: We should be able to get rid of this method and use the va_arg 532 // instruction in LLVM instead once it works well enough. 533 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 534 535 // EmitVLASize - Generate code for any VLA size expressions that might occur 536 // in a variably modified type. If Ty is a VLA, will return the value that 537 // corresponds to the size in bytes of the VLA type. Will return 0 otherwise. 538 /// 539 /// This function can be called with a null (unreachable) insert point. 540 llvm::Value *EmitVLASize(QualType Ty); 541 542 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes 543 // of a variable length array type. 544 llvm::Value *GetVLASize(const VariableArrayType *); 545 546 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 547 /// generating code for an C++ member function. 548 llvm::Value *LoadCXXThis(); 549 550 /// AddressCXXOfBaseClass - This function will add the necessary delta 551 /// to the load of 'this' and returns address of the base class. 552 // FIXME. This currently only does a derived to non-virtual base conversion. 553 // Other kinds of conversions will come later. 554 llvm::Value *AddressCXXOfBaseClass(llvm::Value *ThisValue, 555 const CXXRecordDecl *ClassDecl, 556 const CXXRecordDecl *BaseClassDecl); 557 558 void EmitClassMemberwiseCopy(llvm::Value *DestValue, llvm::Value *SrcValue, 559 const CXXRecordDecl *ClassDecl, 560 const CXXRecordDecl *BaseClassDecl); 561 562 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 563 llvm::Value *This, 564 CallExpr::const_arg_iterator ArgBeg, 565 CallExpr::const_arg_iterator ArgEnd); 566 567 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 568 llvm::Value *This); 569 570 void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr); 571 void PopCXXTemporary(); 572 573 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 574 575 //===--------------------------------------------------------------------===// 576 // Declaration Emission 577 //===--------------------------------------------------------------------===// 578 579 /// EmitDecl - Emit a declaration. 580 /// 581 /// This function can be called with a null (unreachable) insert point. 582 void EmitDecl(const Decl &D); 583 584 /// EmitBlockVarDecl - Emit a block variable declaration. 585 /// 586 /// This function can be called with a null (unreachable) insert point. 587 void EmitBlockVarDecl(const VarDecl &D); 588 589 /// EmitLocalBlockVarDecl - Emit a local block variable declaration. 590 /// 591 /// This function can be called with a null (unreachable) insert point. 592 void EmitLocalBlockVarDecl(const VarDecl &D); 593 594 void EmitStaticBlockVarDecl(const VarDecl &D); 595 596 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 597 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg); 598 599 //===--------------------------------------------------------------------===// 600 // Statement Emission 601 //===--------------------------------------------------------------------===// 602 603 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 604 void EmitStopPoint(const Stmt *S); 605 606 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 607 /// this function even if there is no current insertion point. 608 /// 609 /// This function may clear the current insertion point; callers should use 610 /// EnsureInsertPoint if they wish to subsequently generate code without first 611 /// calling EmitBlock, EmitBranch, or EmitStmt. 612 void EmitStmt(const Stmt *S); 613 614 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 615 /// necessarily require an insertion point or debug information; typically 616 /// because the statement amounts to a jump or a container of other 617 /// statements. 618 /// 619 /// \return True if the statement was handled. 620 bool EmitSimpleStmt(const Stmt *S); 621 622 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 623 llvm::Value *AggLoc = 0, bool isAggVol = false); 624 625 /// EmitLabel - Emit the block for the given label. It is legal to call this 626 /// function even if there is no current insertion point. 627 void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt. 628 629 void EmitLabelStmt(const LabelStmt &S); 630 void EmitGotoStmt(const GotoStmt &S); 631 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 632 void EmitIfStmt(const IfStmt &S); 633 void EmitWhileStmt(const WhileStmt &S); 634 void EmitDoStmt(const DoStmt &S); 635 void EmitForStmt(const ForStmt &S); 636 void EmitReturnStmt(const ReturnStmt &S); 637 void EmitDeclStmt(const DeclStmt &S); 638 void EmitBreakStmt(const BreakStmt &S); 639 void EmitContinueStmt(const ContinueStmt &S); 640 void EmitSwitchStmt(const SwitchStmt &S); 641 void EmitDefaultStmt(const DefaultStmt &S); 642 void EmitCaseStmt(const CaseStmt &S); 643 void EmitCaseStmtRange(const CaseStmt &S); 644 void EmitAsmStmt(const AsmStmt &S); 645 646 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 647 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 648 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 649 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 650 651 //===--------------------------------------------------------------------===// 652 // LValue Expression Emission 653 //===--------------------------------------------------------------------===// 654 655 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 656 RValue GetUndefRValue(QualType Ty); 657 658 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 659 /// and issue an ErrorUnsupported style diagnostic (using the 660 /// provided Name). 661 RValue EmitUnsupportedRValue(const Expr *E, 662 const char *Name); 663 664 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 665 /// an ErrorUnsupported style diagnostic (using the provided Name). 666 LValue EmitUnsupportedLValue(const Expr *E, 667 const char *Name); 668 669 /// EmitLValue - Emit code to compute a designator that specifies the location 670 /// of the expression. 671 /// 672 /// This can return one of two things: a simple address or a bitfield 673 /// reference. In either case, the LLVM Value* in the LValue structure is 674 /// guaranteed to be an LLVM pointer type. 675 /// 676 /// If this returns a bitfield reference, nothing about the pointee type of 677 /// the LLVM value is known: For example, it may not be a pointer to an 678 /// integer. 679 /// 680 /// If this returns a normal address, and if the lvalue's C type is fixed 681 /// size, this method guarantees that the returned pointer type will point to 682 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 683 /// variable length type, this is not possible. 684 /// 685 LValue EmitLValue(const Expr *E); 686 687 /// EmitLoadOfScalar - Load a scalar value from an address, taking 688 /// care to appropriately convert from the memory representation to 689 /// the LLVM value representation. 690 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 691 QualType Ty); 692 693 /// EmitStoreOfScalar - Store a scalar value to an address, taking 694 /// care to appropriately convert from the memory representation to 695 /// the LLVM value representation. 696 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 697 bool Volatile, QualType Ty); 698 699 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 700 /// this method emits the address of the lvalue, then loads the result as an 701 /// rvalue, returning the rvalue. 702 RValue EmitLoadOfLValue(LValue V, QualType LVType); 703 RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType); 704 RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType); 705 RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType); 706 RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType); 707 708 709 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 710 /// lvalue, where both are guaranteed to the have the same type, and that type 711 /// is 'Ty'. 712 void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty); 713 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst, 714 QualType Ty); 715 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty); 716 void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty); 717 718 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as 719 /// EmitStoreThroughLValue. 720 /// 721 /// \param Result [out] - If non-null, this will be set to a Value* for the 722 /// bit-field contents after the store, appropriate for use as the result of 723 /// an assignment to the bit-field. 724 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty, 725 llvm::Value **Result=0); 726 727 // Note: only availabe for agg return types 728 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 729 // Note: only available for agg return types 730 LValue EmitCallExprLValue(const CallExpr *E); 731 // Note: only available for agg return types 732 LValue EmitVAArgExprLValue(const VAArgExpr *E); 733 LValue EmitDeclRefLValue(const DeclRefExpr *E); 734 LValue EmitStringLiteralLValue(const StringLiteral *E); 735 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 736 LValue EmitPredefinedFunctionName(unsigned Type); 737 LValue EmitPredefinedLValue(const PredefinedExpr *E); 738 LValue EmitUnaryOpLValue(const UnaryOperator *E); 739 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); 740 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 741 LValue EmitMemberExpr(const MemberExpr *E); 742 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 743 LValue EmitConditionalOperator(const ConditionalOperator *E); 744 LValue EmitCastLValue(const CastExpr *E); 745 746 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 747 const ObjCIvarDecl *Ivar); 748 LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field, 749 bool isUnion, unsigned CVRQualifiers); 750 LValue EmitLValueForIvar(QualType ObjectTy, 751 llvm::Value* Base, const ObjCIvarDecl *Ivar, 752 unsigned CVRQualifiers); 753 754 LValue EmitLValueForBitfield(llvm::Value* Base, FieldDecl* Field, 755 unsigned CVRQualifiers); 756 757 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E); 758 759 LValue EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E); 760 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 761 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 762 763 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 764 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 765 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E); 766 LValue EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E); 767 LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E); 768 LValue EmitStmtExprLValue(const StmtExpr *E); 769 770 //===--------------------------------------------------------------------===// 771 // Scalar Expression Emission 772 //===--------------------------------------------------------------------===// 773 774 /// EmitCall - Generate a call of the given function, expecting the given 775 /// result type, and using the given argument list which specifies both the 776 /// LLVM arguments and the types they were derived from. 777 /// 778 /// \param TargetDecl - If given, the decl of the function in a 779 /// direct call; used to set attributes on the call (noreturn, 780 /// etc.). 781 RValue EmitCall(const CGFunctionInfo &FnInfo, 782 llvm::Value *Callee, 783 const CallArgList &Args, 784 const Decl *TargetDecl = 0); 785 786 RValue EmitCall(llvm::Value *Callee, QualType FnType, 787 CallExpr::const_arg_iterator ArgBeg, 788 CallExpr::const_arg_iterator ArgEnd, 789 const Decl *TargetDecl = 0); 790 RValue EmitCallExpr(const CallExpr *E); 791 792 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 793 llvm::Value *Callee, 794 llvm::Value *This, 795 CallExpr::const_arg_iterator ArgBeg, 796 CallExpr::const_arg_iterator ArgEnd); 797 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E); 798 799 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 800 const CXXMethodDecl *MD); 801 802 RValue EmitBuiltinExpr(const FunctionDecl *FD, 803 unsigned BuiltinID, const CallExpr *E); 804 805 RValue EmitBlockCallExpr(const CallExpr *E); 806 807 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 808 /// is unhandled by the current target. 809 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 810 811 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 812 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 813 814 llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...); 815 llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals, 816 bool isSplat = false); 817 818 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 819 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 820 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 821 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E); 822 RValue EmitObjCPropertyGet(const Expr *E); 823 RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S); 824 void EmitObjCPropertySet(const Expr *E, RValue Src); 825 void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src); 826 827 828 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in 829 /// expression. Will emit a temporary variable if E is not an LValue. 830 RValue EmitReferenceBindingToExpr(const Expr* E, QualType DestType); 831 832 //===--------------------------------------------------------------------===// 833 // Expression Emission 834 //===--------------------------------------------------------------------===// 835 836 // Expressions are broken into three classes: scalar, complex, aggregate. 837 838 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 839 /// scalar type, returning the result. 840 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign=false); 841 842 /// EmitScalarConversion - Emit a conversion from the specified type to the 843 /// specified destination type, both of which are LLVM scalar types. 844 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 845 QualType DstTy); 846 847 /// EmitComplexToScalarConversion - Emit a conversion from the specified 848 /// complex type to the specified destination type, where the destination type 849 /// is an LLVM scalar type. 850 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 851 QualType DstTy); 852 853 854 /// EmitAggExpr - Emit the computation of the specified expression of 855 /// aggregate type. The result is computed into DestPtr. Note that if 856 /// DestPtr is null, the value of the aggregate expression is not needed. 857 void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest, 858 bool IgnoreResult = false); 859 860 /// EmitGCMemmoveCollectable - Emit special API for structs with object 861 /// pointers. 862 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 863 unsigned long); 864 865 /// EmitComplexExpr - Emit the computation of the specified expression of 866 /// complex type, returning the result. 867 ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false, 868 bool IgnoreImag = false, 869 bool IgnoreRealAssign = false, 870 bool IgnoreImagAssign = false); 871 872 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression 873 /// of complex type, storing into the specified Value*. 874 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, 875 bool DestIsVolatile); 876 877 /// StoreComplexToAddr - Store a complex number into the specified address. 878 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, 879 bool DestIsVolatile); 880 /// LoadComplexFromAddr - Load a complex number from the specified address. 881 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); 882 883 /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global 884 /// for a static block var decl. 885 llvm::GlobalVariable * CreateStaticBlockVarDecl(const VarDecl &D, 886 const char *Separator, 887 llvm::GlobalValue::LinkageTypes 888 Linkage); 889 890 /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ 891 /// runtime initialized static block var decl. 892 void EmitStaticCXXBlockVarDeclInit(const VarDecl &D, 893 llvm::GlobalVariable *GV); 894 895 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 896 /// variable with global storage. 897 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr); 898 899 /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr 900 /// with the C++ runtime so that its destructor will be called at exit. 901 void EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor, 902 llvm::Constant *DeclPtr); 903 904 void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E); 905 906 RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E, 907 llvm::Value *AggLoc = 0, 908 bool isAggLocVolatile = false); 909 910 //===--------------------------------------------------------------------===// 911 // Internal Helpers 912 //===--------------------------------------------------------------------===// 913 914 /// ContainsLabel - Return true if the statement contains a label in it. If 915 /// this statement is not executed normally, it not containing a label means 916 /// that we can just remove the code. 917 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 918 919 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 920 /// to a constant, or if it does but contains a label, return 0. If it 921 /// constant folds to 'true' and does not contain a label, return 1, if it 922 /// constant folds to 'false' and does not contain a label, return -1. 923 int ConstantFoldsToSimpleInteger(const Expr *Cond); 924 925 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 926 /// if statement) to the specified blocks. Based on the condition, this might 927 /// try to simplify the codegen of the conditional based on the branch. 928 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 929 llvm::BasicBlock *FalseBlock); 930private: 931 932 /// EmitIndirectSwitches - Emit code for all of the switch 933 /// instructions in IndirectSwitches. 934 void EmitIndirectSwitches(); 935 936 void EmitReturnOfRValue(RValue RV, QualType Ty); 937 938 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 939 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 940 /// 941 /// \param AI - The first function argument of the expansion. 942 /// \return The argument following the last expanded function 943 /// argument. 944 llvm::Function::arg_iterator 945 ExpandTypeFromArgs(QualType Ty, LValue Dst, 946 llvm::Function::arg_iterator AI); 947 948 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 949 /// Ty, into individual arguments on the provided vector \arg Args. See 950 /// ABIArgInfo::Expand. 951 void ExpandTypeToArgs(QualType Ty, RValue Src, 952 llvm::SmallVector<llvm::Value*, 16> &Args); 953 954 llvm::Value* EmitAsmInput(const AsmStmt &S, 955 const TargetInfo::ConstraintInfo &Info, 956 const Expr *InputExpr, std::string &ConstraintStr); 957 958 /// EmitCleanupBlock - emits a single cleanup block. 959 void EmitCleanupBlock(); 960 961 /// AddBranchFixup - adds a branch instruction to the list of fixups for the 962 /// current cleanup scope. 963 void AddBranchFixup(llvm::BranchInst *BI); 964 965 /// EmitCallArg - Emit a single call argument. 966 RValue EmitCallArg(const Expr *E, QualType ArgType); 967 968 /// EmitCallArgs - Emit call arguments for a function. 969 /// The CallArgTypeInfo parameter is used for iterating over the known 970 /// argument types of the function being called. 971 template<typename T> 972 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo, 973 CallExpr::const_arg_iterator ArgBeg, 974 CallExpr::const_arg_iterator ArgEnd) { 975 CallExpr::const_arg_iterator Arg = ArgBeg; 976 977 // First, use the argument types that the type info knows about 978 if (CallArgTypeInfo) { 979 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(), 980 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) { 981 QualType ArgType = *I; 982 983 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 984 getTypePtr() == 985 getContext().getCanonicalType(Arg->getType()).getTypePtr() && 986 "type mismatch in call argument!"); 987 988 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 989 ArgType)); 990 } 991 992 // Either we've emitted all the call args, or we have a call to a 993 // variadic function. 994 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) && 995 "Extra arguments in non-variadic function!"); 996 997 } 998 999 // If we still have any arguments, emit them using the type of the argument. 1000 for (; Arg != ArgEnd; ++Arg) { 1001 QualType ArgType = Arg->getType(); 1002 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), 1003 ArgType)); 1004 } 1005 } 1006}; 1007 1008 1009} // end namespace CodeGen 1010} // end namespace clang 1011 1012#endif 1013