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 "CGBuilder.h" 18 #include "CGDebugInfo.h" 19 #include "CGLoopInfo.h" 20 #include "CGValue.h" 21 #include "CodeGenModule.h" 22 #include "CodeGenPGO.h" 23 #include "EHScopeStack.h" 24 #include "clang/AST/CharUnits.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/Type.h" 28 #include "clang/Basic/ABI.h" 29 #include "clang/Basic/CapturedStmt.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Frontend/CodeGenOptions.h" 32 #include "llvm/ADT/ArrayRef.h" 33 #include "llvm/ADT/DenseMap.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/IR/ValueHandle.h" 36 #include "llvm/Support/Debug.h" 37 38 namespace llvm { 39 class BasicBlock; 40 class LLVMContext; 41 class MDNode; 42 class Module; 43 class SwitchInst; 44 class Twine; 45 class Value; 46 class CallSite; 47 } 48 49 namespace clang { 50 class ASTContext; 51 class BlockDecl; 52 class CXXDestructorDecl; 53 class CXXForRangeStmt; 54 class CXXTryStmt; 55 class Decl; 56 class LabelDecl; 57 class EnumConstantDecl; 58 class FunctionDecl; 59 class FunctionProtoType; 60 class LabelStmt; 61 class ObjCContainerDecl; 62 class ObjCInterfaceDecl; 63 class ObjCIvarDecl; 64 class ObjCMethodDecl; 65 class ObjCImplementationDecl; 66 class ObjCPropertyImplDecl; 67 class TargetInfo; 68 class TargetCodeGenInfo; 69 class VarDecl; 70 class ObjCForCollectionStmt; 71 class ObjCAtTryStmt; 72 class ObjCAtThrowStmt; 73 class ObjCAtSynchronizedStmt; 74 class ObjCAutoreleasePoolStmt; 75 76 namespace CodeGen { 77 class CodeGenTypes; 78 class CGFunctionInfo; 79 class CGRecordLayout; 80 class CGBlockInfo; 81 class CGCXXABI; 82 class BlockFlags; 83 class BlockFieldFlags; 84 85 /// The kind of evaluation to perform on values of a particular 86 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 87 /// CGExprAgg? 88 /// 89 /// TODO: should vectors maybe be split out into their own thing? 90 enum TypeEvaluationKind { 91 TEK_Scalar, 92 TEK_Complex, 93 TEK_Aggregate 94 }; 95 96 class SuppressDebugLocation { 97 llvm::DebugLoc CurLoc; 98 llvm::IRBuilderBase &Builder; 99 public: 100 SuppressDebugLocation(llvm::IRBuilderBase &Builder) 101 : CurLoc(Builder.getCurrentDebugLocation()), Builder(Builder) { 102 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 103 } 104 ~SuppressDebugLocation() { 105 Builder.SetCurrentDebugLocation(CurLoc); 106 } 107 }; 108 109 /// CodeGenFunction - This class organizes the per-function state that is used 110 /// while generating LLVM code. 111 class CodeGenFunction : public CodeGenTypeCache { 112 CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 113 void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 114 115 friend class CGCXXABI; 116 public: 117 /// A jump destination is an abstract label, branching to which may 118 /// require a jump out through normal cleanups. 119 struct JumpDest { 120 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {} 121 JumpDest(llvm::BasicBlock *Block, 122 EHScopeStack::stable_iterator Depth, 123 unsigned Index) 124 : Block(Block), ScopeDepth(Depth), Index(Index) {} 125 126 bool isValid() const { return Block != nullptr; } 127 llvm::BasicBlock *getBlock() const { return Block; } 128 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 129 unsigned getDestIndex() const { return Index; } 130 131 // This should be used cautiously. 132 void setScopeDepth(EHScopeStack::stable_iterator depth) { 133 ScopeDepth = depth; 134 } 135 136 private: 137 llvm::BasicBlock *Block; 138 EHScopeStack::stable_iterator ScopeDepth; 139 unsigned Index; 140 }; 141 142 CodeGenModule &CGM; // Per-module state. 143 const TargetInfo &Target; 144 145 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 146 LoopInfoStack LoopStack; 147 CGBuilderTy Builder; 148 149 /// \brief CGBuilder insert helper. This function is called after an 150 /// instruction is created using Builder. 151 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, 152 llvm::BasicBlock *BB, 153 llvm::BasicBlock::iterator InsertPt) const; 154 155 /// CurFuncDecl - Holds the Decl for the current outermost 156 /// non-closure context. 157 const Decl *CurFuncDecl; 158 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 159 const Decl *CurCodeDecl; 160 const CGFunctionInfo *CurFnInfo; 161 QualType FnRetTy; 162 llvm::Function *CurFn; 163 164 /// CurGD - The GlobalDecl for the current function being compiled. 165 GlobalDecl CurGD; 166 167 /// PrologueCleanupDepth - The cleanup depth enclosing all the 168 /// cleanups associated with the parameters. 169 EHScopeStack::stable_iterator PrologueCleanupDepth; 170 171 /// ReturnBlock - Unified return block. 172 JumpDest ReturnBlock; 173 174 /// ReturnValue - The temporary alloca to hold the return value. This is null 175 /// iff the function has no return value. 176 llvm::Value *ReturnValue; 177 178 /// AllocaInsertPoint - This is an instruction in the entry block before which 179 /// we prefer to insert allocas. 180 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 181 182 /// \brief API for captured statement code generation. 183 class CGCapturedStmtInfo { 184 public: 185 explicit CGCapturedStmtInfo(const CapturedStmt &S, 186 CapturedRegionKind K = CR_Default) 187 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) { 188 189 RecordDecl::field_iterator Field = 190 S.getCapturedRecordDecl()->field_begin(); 191 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 192 E = S.capture_end(); 193 I != E; ++I, ++Field) { 194 if (I->capturesThis()) 195 CXXThisFieldDecl = *Field; 196 else 197 CaptureFields[I->getCapturedVar()] = *Field; 198 } 199 } 200 201 virtual ~CGCapturedStmtInfo(); 202 203 CapturedRegionKind getKind() const { return Kind; } 204 205 void setContextValue(llvm::Value *V) { ThisValue = V; } 206 // \brief Retrieve the value of the context parameter. 207 llvm::Value *getContextValue() const { return ThisValue; } 208 209 /// \brief Lookup the captured field decl for a variable. 210 const FieldDecl *lookup(const VarDecl *VD) const { 211 return CaptureFields.lookup(VD); 212 } 213 214 bool isCXXThisExprCaptured() const { return CXXThisFieldDecl != nullptr; } 215 FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 216 217 /// \brief Emit the captured statement body. 218 virtual void EmitBody(CodeGenFunction &CGF, Stmt *S) { 219 RegionCounter Cnt = CGF.getPGORegionCounter(S); 220 Cnt.beginRegion(CGF.Builder); 221 CGF.EmitStmt(S); 222 } 223 224 /// \brief Get the name of the capture helper. 225 virtual StringRef getHelperName() const { return "__captured_stmt"; } 226 227 private: 228 /// \brief The kind of captured statement being generated. 229 CapturedRegionKind Kind; 230 231 /// \brief Keep the map between VarDecl and FieldDecl. 232 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 233 234 /// \brief The base address of the captured record, passed in as the first 235 /// argument of the parallel region function. 236 llvm::Value *ThisValue; 237 238 /// \brief Captured 'this' type. 239 FieldDecl *CXXThisFieldDecl; 240 }; 241 CGCapturedStmtInfo *CapturedStmtInfo; 242 243 /// BoundsChecking - Emit run-time bounds checks. Higher values mean 244 /// potentially higher performance penalties. 245 unsigned char BoundsChecking; 246 247 /// \brief Sanitizer options to use for this function. 248 const SanitizerOptions *SanOpts; 249 250 /// \brief True if CodeGen currently emits code implementing sanitizer checks. 251 bool IsSanitizerScope; 252 253 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope. 254 class SanitizerScope { 255 CodeGenFunction *CGF; 256 public: 257 SanitizerScope(CodeGenFunction *CGF); 258 ~SanitizerScope(); 259 }; 260 261 /// In ARC, whether we should autorelease the return value. 262 bool AutoreleaseResult; 263 264 const CodeGen::CGBlockInfo *BlockInfo; 265 llvm::Value *BlockPointer; 266 267 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 268 FieldDecl *LambdaThisCaptureField; 269 270 /// \brief A mapping from NRVO variables to the flags used to indicate 271 /// when the NRVO has been applied to this variable. 272 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 273 274 EHScopeStack EHStack; 275 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 276 277 /// Header for data within LifetimeExtendedCleanupStack. 278 struct LifetimeExtendedCleanupHeader { 279 /// The size of the following cleanup object. 280 size_t Size : 29; 281 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 282 unsigned Kind : 3; 283 284 size_t getSize() const { return Size; } 285 CleanupKind getKind() const { return static_cast<CleanupKind>(Kind); } 286 }; 287 288 /// i32s containing the indexes of the cleanup destinations. 289 llvm::AllocaInst *NormalCleanupDest; 290 291 unsigned NextCleanupDestIndex; 292 293 /// FirstBlockInfo - The head of a singly-linked-list of block layouts. 294 CGBlockInfo *FirstBlockInfo; 295 296 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 297 llvm::BasicBlock *EHResumeBlock; 298 299 /// The exception slot. All landing pads write the current exception pointer 300 /// into this alloca. 301 llvm::Value *ExceptionSlot; 302 303 /// The selector slot. Under the MandatoryCleanup model, all landing pads 304 /// write the current selector value into this alloca. 305 llvm::AllocaInst *EHSelectorSlot; 306 307 /// Emits a landing pad for the current EH stack. 308 llvm::BasicBlock *EmitLandingPad(); 309 310 llvm::BasicBlock *getInvokeDestImpl(); 311 312 template <class T> 313 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 314 return DominatingValue<T>::save(*this, value); 315 } 316 317 public: 318 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 319 /// rethrows. 320 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 321 322 /// A class controlling the emission of a finally block. 323 class FinallyInfo { 324 /// Where the catchall's edge through the cleanup should go. 325 JumpDest RethrowDest; 326 327 /// A function to call to enter the catch. 328 llvm::Constant *BeginCatchFn; 329 330 /// An i1 variable indicating whether or not the @finally is 331 /// running for an exception. 332 llvm::AllocaInst *ForEHVar; 333 334 /// An i8* variable into which the exception pointer to rethrow 335 /// has been saved. 336 llvm::AllocaInst *SavedExnVar; 337 338 public: 339 void enter(CodeGenFunction &CGF, const Stmt *Finally, 340 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, 341 llvm::Constant *rethrowFn); 342 void exit(CodeGenFunction &CGF); 343 }; 344 345 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 346 /// current full-expression. Safe against the possibility that 347 /// we're currently inside a conditionally-evaluated expression. 348 template <class T, class A0> 349 void pushFullExprCleanup(CleanupKind kind, A0 a0) { 350 // If we're not in a conditional branch, or if none of the 351 // arguments requires saving, then use the unconditional cleanup. 352 if (!isInConditionalBranch()) 353 return EHStack.pushCleanup<T>(kind, a0); 354 355 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 356 357 typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType; 358 EHStack.pushCleanup<CleanupType>(kind, a0_saved); 359 initFullExprCleanup(); 360 } 361 362 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 363 /// current full-expression. Safe against the possibility that 364 /// we're currently inside a conditionally-evaluated expression. 365 template <class T, class A0, class A1> 366 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) { 367 // If we're not in a conditional branch, or if none of the 368 // arguments requires saving, then use the unconditional cleanup. 369 if (!isInConditionalBranch()) 370 return EHStack.pushCleanup<T>(kind, a0, a1); 371 372 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 373 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 374 375 typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType; 376 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved); 377 initFullExprCleanup(); 378 } 379 380 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 381 /// current full-expression. Safe against the possibility that 382 /// we're currently inside a conditionally-evaluated expression. 383 template <class T, class A0, class A1, class A2> 384 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) { 385 // If we're not in a conditional branch, or if none of the 386 // arguments requires saving, then use the unconditional cleanup. 387 if (!isInConditionalBranch()) { 388 return EHStack.pushCleanup<T>(kind, a0, a1, a2); 389 } 390 391 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 392 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 393 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 394 395 typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType; 396 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved); 397 initFullExprCleanup(); 398 } 399 400 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 401 /// current full-expression. Safe against the possibility that 402 /// we're currently inside a conditionally-evaluated expression. 403 template <class T, class A0, class A1, class A2, class A3> 404 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) { 405 // If we're not in a conditional branch, or if none of the 406 // arguments requires saving, then use the unconditional cleanup. 407 if (!isInConditionalBranch()) { 408 return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3); 409 } 410 411 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 412 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 413 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 414 typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3); 415 416 typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType; 417 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, 418 a2_saved, a3_saved); 419 initFullExprCleanup(); 420 } 421 422 /// \brief Queue a cleanup to be pushed after finishing the current 423 /// full-expression. 424 template <class T, class A0, class A1, class A2, class A3> 425 void pushCleanupAfterFullExpr(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) { 426 assert(!isInConditionalBranch() && "can't defer conditional cleanup"); 427 428 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind }; 429 430 size_t OldSize = LifetimeExtendedCleanupStack.size(); 431 LifetimeExtendedCleanupStack.resize( 432 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size); 433 434 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 435 new (Buffer) LifetimeExtendedCleanupHeader(Header); 436 new (Buffer + sizeof(Header)) T(a0, a1, a2, a3); 437 } 438 439 /// Set up the last cleaup that was pushed as a conditional 440 /// full-expression cleanup. 441 void initFullExprCleanup(); 442 443 /// PushDestructorCleanup - Push a cleanup to call the 444 /// complete-object destructor of an object of the given type at the 445 /// given address. Does nothing if T is not a C++ class type with a 446 /// non-trivial destructor. 447 void PushDestructorCleanup(QualType T, llvm::Value *Addr); 448 449 /// PushDestructorCleanup - Push a cleanup to call the 450 /// complete-object variant of the given destructor on the object at 451 /// the given address. 452 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, 453 llvm::Value *Addr); 454 455 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 456 /// process all branch fixups. 457 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 458 459 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 460 /// The block cannot be reactivated. Pops it if it's the top of the 461 /// stack. 462 /// 463 /// \param DominatingIP - An instruction which is known to 464 /// dominate the current IP (if set) and which lies along 465 /// all paths of execution between the current IP and the 466 /// the point at which the cleanup comes into scope. 467 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 468 llvm::Instruction *DominatingIP); 469 470 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 471 /// Cannot be used to resurrect a deactivated cleanup. 472 /// 473 /// \param DominatingIP - An instruction which is known to 474 /// dominate the current IP (if set) and which lies along 475 /// all paths of execution between the current IP and the 476 /// the point at which the cleanup comes into scope. 477 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 478 llvm::Instruction *DominatingIP); 479 480 /// \brief Enters a new scope for capturing cleanups, all of which 481 /// will be executed once the scope is exited. 482 class RunCleanupsScope { 483 EHScopeStack::stable_iterator CleanupStackDepth; 484 size_t LifetimeExtendedCleanupStackSize; 485 bool OldDidCallStackSave; 486 protected: 487 bool PerformCleanup; 488 private: 489 490 RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 491 void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 492 493 protected: 494 CodeGenFunction& CGF; 495 496 public: 497 /// \brief Enter a new cleanup scope. 498 explicit RunCleanupsScope(CodeGenFunction &CGF) 499 : PerformCleanup(true), CGF(CGF) 500 { 501 CleanupStackDepth = CGF.EHStack.stable_begin(); 502 LifetimeExtendedCleanupStackSize = 503 CGF.LifetimeExtendedCleanupStack.size(); 504 OldDidCallStackSave = CGF.DidCallStackSave; 505 CGF.DidCallStackSave = false; 506 } 507 508 /// \brief Exit this cleanup scope, emitting any accumulated 509 /// cleanups. 510 ~RunCleanupsScope() { 511 if (PerformCleanup) { 512 CGF.DidCallStackSave = OldDidCallStackSave; 513 CGF.PopCleanupBlocks(CleanupStackDepth, 514 LifetimeExtendedCleanupStackSize); 515 } 516 } 517 518 /// \brief Determine whether this scope requires any cleanups. 519 bool requiresCleanups() const { 520 return CGF.EHStack.stable_begin() != CleanupStackDepth; 521 } 522 523 /// \brief Force the emission of cleanups now, instead of waiting 524 /// until this object is destroyed. 525 void ForceCleanup() { 526 assert(PerformCleanup && "Already forced cleanup"); 527 CGF.DidCallStackSave = OldDidCallStackSave; 528 CGF.PopCleanupBlocks(CleanupStackDepth, 529 LifetimeExtendedCleanupStackSize); 530 PerformCleanup = false; 531 } 532 }; 533 534 class LexicalScope: protected RunCleanupsScope { 535 SourceRange Range; 536 SmallVector<const LabelDecl*, 4> Labels; 537 LexicalScope *ParentScope; 538 539 LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION; 540 void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION; 541 542 public: 543 /// \brief Enter a new cleanup scope. 544 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 545 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 546 CGF.CurLexicalScope = this; 547 if (CGDebugInfo *DI = CGF.getDebugInfo()) 548 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 549 } 550 551 void addLabel(const LabelDecl *label) { 552 assert(PerformCleanup && "adding label to dead scope?"); 553 Labels.push_back(label); 554 } 555 556 /// \brief Exit this cleanup scope, emitting any accumulated 557 /// cleanups. 558 ~LexicalScope() { 559 if (CGDebugInfo *DI = CGF.getDebugInfo()) 560 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 561 562 // If we should perform a cleanup, force them now. Note that 563 // this ends the cleanup scope before rescoping any labels. 564 if (PerformCleanup) ForceCleanup(); 565 } 566 567 /// \brief Force the emission of cleanups now, instead of waiting 568 /// until this object is destroyed. 569 void ForceCleanup() { 570 CGF.CurLexicalScope = ParentScope; 571 RunCleanupsScope::ForceCleanup(); 572 573 if (!Labels.empty()) 574 rescopeLabels(); 575 } 576 577 void rescopeLabels(); 578 }; 579 580 581 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 582 /// that have been added. 583 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 584 585 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 586 /// that have been added, then adds all lifetime-extended cleanups from 587 /// the given position to the stack. 588 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 589 size_t OldLifetimeExtendedStackSize); 590 591 void ResolveBranchFixups(llvm::BasicBlock *Target); 592 593 /// The given basic block lies in the current EH scope, but may be a 594 /// target of a potentially scope-crossing jump; get a stable handle 595 /// to which we can perform this jump later. 596 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 597 return JumpDest(Target, 598 EHStack.getInnermostNormalCleanup(), 599 NextCleanupDestIndex++); 600 } 601 602 /// The given basic block lies in the current EH scope, but may be a 603 /// target of a potentially scope-crossing jump; get a stable handle 604 /// to which we can perform this jump later. 605 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 606 return getJumpDestInCurrentScope(createBasicBlock(Name)); 607 } 608 609 /// EmitBranchThroughCleanup - Emit a branch from the current insert 610 /// block through the normal cleanup handling code (if any) and then 611 /// on to \arg Dest. 612 void EmitBranchThroughCleanup(JumpDest Dest); 613 614 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 615 /// specified destination obviously has no cleanups to run. 'false' is always 616 /// a conservatively correct answer for this method. 617 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 618 619 /// popCatchScope - Pops the catch scope at the top of the EHScope 620 /// stack, emitting any required code (other than the catch handlers 621 /// themselves). 622 void popCatchScope(); 623 624 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 625 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 626 627 /// An object to manage conditionally-evaluated expressions. 628 class ConditionalEvaluation { 629 llvm::BasicBlock *StartBB; 630 631 public: 632 ConditionalEvaluation(CodeGenFunction &CGF) 633 : StartBB(CGF.Builder.GetInsertBlock()) {} 634 635 void begin(CodeGenFunction &CGF) { 636 assert(CGF.OutermostConditional != this); 637 if (!CGF.OutermostConditional) 638 CGF.OutermostConditional = this; 639 } 640 641 void end(CodeGenFunction &CGF) { 642 assert(CGF.OutermostConditional != nullptr); 643 if (CGF.OutermostConditional == this) 644 CGF.OutermostConditional = nullptr; 645 } 646 647 /// Returns a block which will be executed prior to each 648 /// evaluation of the conditional code. 649 llvm::BasicBlock *getStartingBlock() const { 650 return StartBB; 651 } 652 }; 653 654 /// isInConditionalBranch - Return true if we're currently emitting 655 /// one branch or the other of a conditional expression. 656 bool isInConditionalBranch() const { return OutermostConditional != nullptr; } 657 658 void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) { 659 assert(isInConditionalBranch()); 660 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 661 new llvm::StoreInst(value, addr, &block->back()); 662 } 663 664 /// An RAII object to record that we're evaluating a statement 665 /// expression. 666 class StmtExprEvaluation { 667 CodeGenFunction &CGF; 668 669 /// We have to save the outermost conditional: cleanups in a 670 /// statement expression aren't conditional just because the 671 /// StmtExpr is. 672 ConditionalEvaluation *SavedOutermostConditional; 673 674 public: 675 StmtExprEvaluation(CodeGenFunction &CGF) 676 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 677 CGF.OutermostConditional = nullptr; 678 } 679 680 ~StmtExprEvaluation() { 681 CGF.OutermostConditional = SavedOutermostConditional; 682 CGF.EnsureInsertPoint(); 683 } 684 }; 685 686 /// An object which temporarily prevents a value from being 687 /// destroyed by aggressive peephole optimizations that assume that 688 /// all uses of a value have been realized in the IR. 689 class PeepholeProtection { 690 llvm::Instruction *Inst; 691 friend class CodeGenFunction; 692 693 public: 694 PeepholeProtection() : Inst(nullptr) {} 695 }; 696 697 /// A non-RAII class containing all the information about a bound 698 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 699 /// this which makes individual mappings very simple; using this 700 /// class directly is useful when you have a variable number of 701 /// opaque values or don't want the RAII functionality for some 702 /// reason. 703 class OpaqueValueMappingData { 704 const OpaqueValueExpr *OpaqueValue; 705 bool BoundLValue; 706 CodeGenFunction::PeepholeProtection Protection; 707 708 OpaqueValueMappingData(const OpaqueValueExpr *ov, 709 bool boundLValue) 710 : OpaqueValue(ov), BoundLValue(boundLValue) {} 711 public: 712 OpaqueValueMappingData() : OpaqueValue(nullptr) {} 713 714 static bool shouldBindAsLValue(const Expr *expr) { 715 // gl-values should be bound as l-values for obvious reasons. 716 // Records should be bound as l-values because IR generation 717 // always keeps them in memory. Expressions of function type 718 // act exactly like l-values but are formally required to be 719 // r-values in C. 720 return expr->isGLValue() || 721 expr->getType()->isFunctionType() || 722 hasAggregateEvaluationKind(expr->getType()); 723 } 724 725 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 726 const OpaqueValueExpr *ov, 727 const Expr *e) { 728 if (shouldBindAsLValue(ov)) 729 return bind(CGF, ov, CGF.EmitLValue(e)); 730 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 731 } 732 733 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 734 const OpaqueValueExpr *ov, 735 const LValue &lv) { 736 assert(shouldBindAsLValue(ov)); 737 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 738 return OpaqueValueMappingData(ov, true); 739 } 740 741 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 742 const OpaqueValueExpr *ov, 743 const RValue &rv) { 744 assert(!shouldBindAsLValue(ov)); 745 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 746 747 OpaqueValueMappingData data(ov, false); 748 749 // Work around an extremely aggressive peephole optimization in 750 // EmitScalarConversion which assumes that all other uses of a 751 // value are extant. 752 data.Protection = CGF.protectFromPeepholes(rv); 753 754 return data; 755 } 756 757 bool isValid() const { return OpaqueValue != nullptr; } 758 void clear() { OpaqueValue = nullptr; } 759 760 void unbind(CodeGenFunction &CGF) { 761 assert(OpaqueValue && "no data to unbind!"); 762 763 if (BoundLValue) { 764 CGF.OpaqueLValues.erase(OpaqueValue); 765 } else { 766 CGF.OpaqueRValues.erase(OpaqueValue); 767 CGF.unprotectFromPeepholes(Protection); 768 } 769 } 770 }; 771 772 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 773 class OpaqueValueMapping { 774 CodeGenFunction &CGF; 775 OpaqueValueMappingData Data; 776 777 public: 778 static bool shouldBindAsLValue(const Expr *expr) { 779 return OpaqueValueMappingData::shouldBindAsLValue(expr); 780 } 781 782 /// Build the opaque value mapping for the given conditional 783 /// operator if it's the GNU ?: extension. This is a common 784 /// enough pattern that the convenience operator is really 785 /// helpful. 786 /// 787 OpaqueValueMapping(CodeGenFunction &CGF, 788 const AbstractConditionalOperator *op) : CGF(CGF) { 789 if (isa<ConditionalOperator>(op)) 790 // Leave Data empty. 791 return; 792 793 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 794 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 795 e->getCommon()); 796 } 797 798 OpaqueValueMapping(CodeGenFunction &CGF, 799 const OpaqueValueExpr *opaqueValue, 800 LValue lvalue) 801 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 802 } 803 804 OpaqueValueMapping(CodeGenFunction &CGF, 805 const OpaqueValueExpr *opaqueValue, 806 RValue rvalue) 807 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 808 } 809 810 void pop() { 811 Data.unbind(CGF); 812 Data.clear(); 813 } 814 815 ~OpaqueValueMapping() { 816 if (Data.isValid()) Data.unbind(CGF); 817 } 818 }; 819 820 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 821 /// number that holds the value. 822 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 823 824 /// BuildBlockByrefAddress - Computes address location of the 825 /// variable which is declared as __block. 826 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr, 827 const VarDecl *V); 828 private: 829 CGDebugInfo *DebugInfo; 830 bool DisableDebugInfo; 831 832 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 833 /// calling llvm.stacksave for multiple VLAs in the same scope. 834 bool DidCallStackSave; 835 836 /// IndirectBranch - The first time an indirect goto is seen we create a block 837 /// with an indirect branch. Every time we see the address of a label taken, 838 /// we add the label to the indirect goto. Every subsequent indirect goto is 839 /// codegen'd as a jump to the IndirectBranch's basic block. 840 llvm::IndirectBrInst *IndirectBranch; 841 842 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 843 /// decls. 844 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy; 845 DeclMapTy LocalDeclMap; 846 847 /// LabelMap - This keeps track of the LLVM basic block for each C label. 848 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 849 850 // BreakContinueStack - This keeps track of where break and continue 851 // statements should jump to. 852 struct BreakContinue { 853 BreakContinue(JumpDest Break, JumpDest Continue) 854 : BreakBlock(Break), ContinueBlock(Continue) {} 855 856 JumpDest BreakBlock; 857 JumpDest ContinueBlock; 858 }; 859 SmallVector<BreakContinue, 8> BreakContinueStack; 860 861 CodeGenPGO PGO; 862 863 public: 864 /// Get a counter for instrumentation of the region associated with the given 865 /// statement. 866 RegionCounter getPGORegionCounter(const Stmt *S) { 867 return RegionCounter(PGO, S); 868 } 869 private: 870 871 /// SwitchInsn - This is nearest current switch instruction. It is null if 872 /// current context is not in a switch. 873 llvm::SwitchInst *SwitchInsn; 874 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 875 SmallVector<uint64_t, 16> *SwitchWeights; 876 877 /// CaseRangeBlock - This block holds if condition check for last case 878 /// statement range in current switch instruction. 879 llvm::BasicBlock *CaseRangeBlock; 880 881 /// OpaqueLValues - Keeps track of the current set of opaque value 882 /// expressions. 883 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 884 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 885 886 // VLASizeMap - This keeps track of the associated size for each VLA type. 887 // We track this by the size expression rather than the type itself because 888 // in certain situations, like a const qualifier applied to an VLA typedef, 889 // multiple VLA types can share the same size expression. 890 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 891 // enter/leave scopes. 892 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 893 894 /// A block containing a single 'unreachable' instruction. Created 895 /// lazily by getUnreachableBlock(). 896 llvm::BasicBlock *UnreachableBlock; 897 898 /// Counts of the number return expressions in the function. 899 unsigned NumReturnExprs; 900 901 /// Count the number of simple (constant) return expressions in the function. 902 unsigned NumSimpleReturnExprs; 903 904 /// The last regular (non-return) debug location (breakpoint) in the function. 905 SourceLocation LastStopPoint; 906 907 public: 908 /// A scope within which we are constructing the fields of an object which 909 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 910 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 911 class FieldConstructionScope { 912 public: 913 FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This) 914 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 915 CGF.CXXDefaultInitExprThis = This; 916 } 917 ~FieldConstructionScope() { 918 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 919 } 920 921 private: 922 CodeGenFunction &CGF; 923 llvm::Value *OldCXXDefaultInitExprThis; 924 }; 925 926 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 927 /// is overridden to be the object under construction. 928 class CXXDefaultInitExprScope { 929 public: 930 CXXDefaultInitExprScope(CodeGenFunction &CGF) 931 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) { 932 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis; 933 } 934 ~CXXDefaultInitExprScope() { 935 CGF.CXXThisValue = OldCXXThisValue; 936 } 937 938 public: 939 CodeGenFunction &CGF; 940 llvm::Value *OldCXXThisValue; 941 }; 942 943 private: 944 /// CXXThisDecl - When generating code for a C++ member function, 945 /// this will hold the implicit 'this' declaration. 946 ImplicitParamDecl *CXXABIThisDecl; 947 llvm::Value *CXXABIThisValue; 948 llvm::Value *CXXThisValue; 949 950 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 951 /// this expression. 952 llvm::Value *CXXDefaultInitExprThis; 953 954 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 955 /// destructor, this will hold the implicit argument (e.g. VTT). 956 ImplicitParamDecl *CXXStructorImplicitParamDecl; 957 llvm::Value *CXXStructorImplicitParamValue; 958 959 /// OutermostConditional - Points to the outermost active 960 /// conditional control. This is used so that we know if a 961 /// temporary should be destroyed conditionally. 962 ConditionalEvaluation *OutermostConditional; 963 964 /// The current lexical scope. 965 LexicalScope *CurLexicalScope; 966 967 /// The current source location that should be used for exception 968 /// handling code. 969 SourceLocation CurEHLocation; 970 971 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 972 /// type as well as the field number that contains the actual data. 973 llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *, 974 unsigned> > ByRefValueInfo; 975 976 llvm::BasicBlock *TerminateLandingPad; 977 llvm::BasicBlock *TerminateHandler; 978 llvm::BasicBlock *TrapBB; 979 980 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'. 981 /// In the kernel metadata node, reference the kernel function and metadata 982 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2): 983 /// - A node for the vec_type_hint(<type>) qualifier contains string 984 /// "vec_type_hint", an undefined value of the <type> data type, 985 /// and a Boolean that is true if the <type> is integer and signed. 986 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string 987 /// "work_group_size_hint", and three 32-bit integers X, Y and Z. 988 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string 989 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z. 990 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 991 llvm::Function *Fn); 992 993 public: 994 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 995 ~CodeGenFunction(); 996 997 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 998 ASTContext &getContext() const { return CGM.getContext(); } 999 CGDebugInfo *getDebugInfo() { 1000 if (DisableDebugInfo) 1001 return nullptr; 1002 return DebugInfo; 1003 } 1004 void disableDebugInfo() { DisableDebugInfo = true; } 1005 void enableDebugInfo() { DisableDebugInfo = false; } 1006 1007 bool shouldUseFusedARCCalls() { 1008 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1009 } 1010 1011 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 1012 1013 /// Returns a pointer to the function's exception object and selector slot, 1014 /// which is assigned in every landing pad. 1015 llvm::Value *getExceptionSlot(); 1016 llvm::Value *getEHSelectorSlot(); 1017 1018 /// Returns the contents of the function's exception object and selector 1019 /// slots. 1020 llvm::Value *getExceptionFromSlot(); 1021 llvm::Value *getSelectorFromSlot(); 1022 1023 llvm::Value *getNormalCleanupDestSlot(); 1024 1025 llvm::BasicBlock *getUnreachableBlock() { 1026 if (!UnreachableBlock) { 1027 UnreachableBlock = createBasicBlock("unreachable"); 1028 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 1029 } 1030 return UnreachableBlock; 1031 } 1032 1033 llvm::BasicBlock *getInvokeDest() { 1034 if (!EHStack.requiresLandingPad()) return nullptr; 1035 return getInvokeDestImpl(); 1036 } 1037 1038 const TargetInfo &getTarget() const { return Target; } 1039 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1040 1041 //===--------------------------------------------------------------------===// 1042 // Cleanups 1043 //===--------------------------------------------------------------------===// 1044 1045 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty); 1046 1047 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1048 llvm::Value *arrayEndPointer, 1049 QualType elementType, 1050 Destroyer *destroyer); 1051 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1052 llvm::Value *arrayEnd, 1053 QualType elementType, 1054 Destroyer *destroyer); 1055 1056 void pushDestroy(QualType::DestructionKind dtorKind, 1057 llvm::Value *addr, QualType type); 1058 void pushEHDestroy(QualType::DestructionKind dtorKind, 1059 llvm::Value *addr, QualType type); 1060 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type, 1061 Destroyer *destroyer, bool useEHCleanupForArray); 1062 void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr, 1063 QualType type, Destroyer *destroyer, 1064 bool useEHCleanupForArray); 1065 void pushStackRestore(CleanupKind kind, llvm::Value *SPMem); 1066 void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer, 1067 bool useEHCleanupForArray); 1068 llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type, 1069 Destroyer *destroyer, 1070 bool useEHCleanupForArray, 1071 const VarDecl *VD); 1072 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1073 QualType type, Destroyer *destroyer, 1074 bool checkZeroLength, bool useEHCleanup); 1075 1076 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1077 1078 /// Determines whether an EH cleanup is required to destroy a type 1079 /// with the given destruction kind. 1080 bool needsEHCleanup(QualType::DestructionKind kind) { 1081 switch (kind) { 1082 case QualType::DK_none: 1083 return false; 1084 case QualType::DK_cxx_destructor: 1085 case QualType::DK_objc_weak_lifetime: 1086 return getLangOpts().Exceptions; 1087 case QualType::DK_objc_strong_lifetime: 1088 return getLangOpts().Exceptions && 1089 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1090 } 1091 llvm_unreachable("bad destruction kind"); 1092 } 1093 1094 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1095 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1096 } 1097 1098 //===--------------------------------------------------------------------===// 1099 // Objective-C 1100 //===--------------------------------------------------------------------===// 1101 1102 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1103 1104 void StartObjCMethod(const ObjCMethodDecl *MD, 1105 const ObjCContainerDecl *CD, 1106 SourceLocation StartLoc); 1107 1108 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1109 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1110 const ObjCPropertyImplDecl *PID); 1111 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1112 const ObjCPropertyImplDecl *propImpl, 1113 const ObjCMethodDecl *GetterMothodDecl, 1114 llvm::Constant *AtomicHelperFn); 1115 1116 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1117 ObjCMethodDecl *MD, bool ctor); 1118 1119 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1120 /// for the given property. 1121 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1122 const ObjCPropertyImplDecl *PID); 1123 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1124 const ObjCPropertyImplDecl *propImpl, 1125 llvm::Constant *AtomicHelperFn); 1126 bool IndirectObjCSetterArg(const CGFunctionInfo &FI); 1127 bool IvarTypeWithAggrGCObjects(QualType Ty); 1128 1129 //===--------------------------------------------------------------------===// 1130 // Block Bits 1131 //===--------------------------------------------------------------------===// 1132 1133 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1134 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 1135 static void destroyBlockInfos(CGBlockInfo *info); 1136 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 1137 const CGBlockInfo &Info, 1138 llvm::StructType *, 1139 llvm::Constant *BlockVarLayout); 1140 1141 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1142 const CGBlockInfo &Info, 1143 const DeclMapTy &ldm, 1144 bool IsLambdaConversionToBlock); 1145 1146 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1147 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1148 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1149 const ObjCPropertyImplDecl *PID); 1150 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 1151 const ObjCPropertyImplDecl *PID); 1152 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 1153 1154 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 1155 1156 class AutoVarEmission; 1157 1158 void emitByrefStructureInit(const AutoVarEmission &emission); 1159 void enterByrefCleanup(const AutoVarEmission &emission); 1160 1161 llvm::Value *LoadBlockStruct() { 1162 assert(BlockPointer && "no block pointer set!"); 1163 return BlockPointer; 1164 } 1165 1166 void AllocateBlockCXXThisPointer(const CXXThisExpr *E); 1167 void AllocateBlockDecl(const DeclRefExpr *E); 1168 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 1169 llvm::Type *BuildByRefType(const VarDecl *var); 1170 1171 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1172 const CGFunctionInfo &FnInfo); 1173 /// \brief Emit code for the start of a function. 1174 /// \param Loc The location to be associated with the function. 1175 /// \param StartLoc The location of the function body. 1176 void StartFunction(GlobalDecl GD, 1177 QualType RetTy, 1178 llvm::Function *Fn, 1179 const CGFunctionInfo &FnInfo, 1180 const FunctionArgList &Args, 1181 SourceLocation Loc = SourceLocation(), 1182 SourceLocation StartLoc = SourceLocation()); 1183 1184 void EmitConstructorBody(FunctionArgList &Args); 1185 void EmitDestructorBody(FunctionArgList &Args); 1186 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 1187 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body); 1188 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, RegionCounter &Cnt); 1189 1190 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 1191 CallArgList &CallArgs); 1192 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 1193 void EmitLambdaBlockInvokeBody(); 1194 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 1195 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 1196 1197 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 1198 /// emission when possible. 1199 void EmitReturnBlock(); 1200 1201 /// FinishFunction - Complete IR generation of the current function. It is 1202 /// legal to call this function even if there is no current insertion point. 1203 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1204 1205 void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo); 1206 1207 void EmitCallAndReturnForThunk(GlobalDecl GD, llvm::Value *Callee, 1208 const ThunkInfo *Thunk); 1209 1210 /// GenerateThunk - Generate a thunk for the given method. 1211 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1212 GlobalDecl GD, const ThunkInfo &Thunk); 1213 1214 void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1215 GlobalDecl GD, const ThunkInfo &Thunk); 1216 1217 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1218 FunctionArgList &Args); 1219 1220 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init, 1221 ArrayRef<VarDecl *> ArrayIndexes); 1222 1223 /// InitializeVTablePointer - Initialize the vtable pointer of the given 1224 /// subobject. 1225 /// 1226 void InitializeVTablePointer(BaseSubobject Base, 1227 const CXXRecordDecl *NearestVBase, 1228 CharUnits OffsetFromNearestVBase, 1229 const CXXRecordDecl *VTableClass); 1230 1231 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1232 void InitializeVTablePointers(BaseSubobject Base, 1233 const CXXRecordDecl *NearestVBase, 1234 CharUnits OffsetFromNearestVBase, 1235 bool BaseIsNonVirtualPrimaryBase, 1236 const CXXRecordDecl *VTableClass, 1237 VisitedVirtualBasesSetTy& VBases); 1238 1239 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1240 1241 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1242 /// to by This. 1243 llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty); 1244 1245 1246 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 1247 /// expr can be devirtualized. 1248 bool CanDevirtualizeMemberFunctionCall(const Expr *Base, 1249 const CXXMethodDecl *MD); 1250 1251 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1252 /// given phase of destruction for a destructor. The end result 1253 /// should call destructors on members and base classes in reverse 1254 /// order of their construction. 1255 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1256 1257 /// ShouldInstrumentFunction - Return true if the current function should be 1258 /// instrumented with __cyg_profile_func_* calls 1259 bool ShouldInstrumentFunction(); 1260 1261 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 1262 /// instrumentation function with the current function and the call site, if 1263 /// function instrumentation is enabled. 1264 void EmitFunctionInstrumentation(const char *Fn); 1265 1266 /// EmitMCountInstrumentation - Emit call to .mcount. 1267 void EmitMCountInstrumentation(); 1268 1269 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 1270 /// arguments for the given function. This is also responsible for naming the 1271 /// LLVM function arguments. 1272 void EmitFunctionProlog(const CGFunctionInfo &FI, 1273 llvm::Function *Fn, 1274 const FunctionArgList &Args); 1275 1276 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 1277 /// given temporary. 1278 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 1279 SourceLocation EndLoc); 1280 1281 /// EmitStartEHSpec - Emit the start of the exception spec. 1282 void EmitStartEHSpec(const Decl *D); 1283 1284 /// EmitEndEHSpec - Emit the end of the exception spec. 1285 void EmitEndEHSpec(const Decl *D); 1286 1287 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 1288 llvm::BasicBlock *getTerminateLandingPad(); 1289 1290 /// getTerminateHandler - Return a handler (not a landing pad, just 1291 /// a catch handler) that just calls terminate. This is used when 1292 /// a terminate scope encloses a try. 1293 llvm::BasicBlock *getTerminateHandler(); 1294 1295 llvm::Type *ConvertTypeForMem(QualType T); 1296 llvm::Type *ConvertType(QualType T); 1297 llvm::Type *ConvertType(const TypeDecl *T) { 1298 return ConvertType(getContext().getTypeDeclType(T)); 1299 } 1300 1301 /// LoadObjCSelf - Load the value of self. This function is only valid while 1302 /// generating code for an Objective-C method. 1303 llvm::Value *LoadObjCSelf(); 1304 1305 /// TypeOfSelfObject - Return type of object that this self represents. 1306 QualType TypeOfSelfObject(); 1307 1308 /// hasAggregateLLVMType - Return true if the specified AST type will map into 1309 /// an aggregate LLVM type or is void. 1310 static TypeEvaluationKind getEvaluationKind(QualType T); 1311 1312 static bool hasScalarEvaluationKind(QualType T) { 1313 return getEvaluationKind(T) == TEK_Scalar; 1314 } 1315 1316 static bool hasAggregateEvaluationKind(QualType T) { 1317 return getEvaluationKind(T) == TEK_Aggregate; 1318 } 1319 1320 /// createBasicBlock - Create an LLVM basic block. 1321 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 1322 llvm::Function *parent = nullptr, 1323 llvm::BasicBlock *before = nullptr) { 1324 #ifdef NDEBUG 1325 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 1326 #else 1327 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 1328 #endif 1329 } 1330 1331 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 1332 /// label maps to. 1333 JumpDest getJumpDestForLabel(const LabelDecl *S); 1334 1335 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 1336 /// another basic block, simplify it. This assumes that no other code could 1337 /// potentially reference the basic block. 1338 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 1339 1340 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 1341 /// adding a fall-through branch from the current insert block if 1342 /// necessary. It is legal to call this function even if there is no current 1343 /// insertion point. 1344 /// 1345 /// IsFinished - If true, indicates that the caller has finished emitting 1346 /// branches to the given block and does not expect to emit code into it. This 1347 /// means the block can be ignored if it is unreachable. 1348 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 1349 1350 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 1351 /// near its uses, and leave the insertion point in it. 1352 void EmitBlockAfterUses(llvm::BasicBlock *BB); 1353 1354 /// EmitBranch - Emit a branch to the specified basic block from the current 1355 /// insert block, taking care to avoid creation of branches from dummy 1356 /// blocks. It is legal to call this function even if there is no current 1357 /// insertion point. 1358 /// 1359 /// This function clears the current insertion point. The caller should follow 1360 /// calls to this function with calls to Emit*Block prior to generation new 1361 /// code. 1362 void EmitBranch(llvm::BasicBlock *Block); 1363 1364 /// HaveInsertPoint - True if an insertion point is defined. If not, this 1365 /// indicates that the current code being emitted is unreachable. 1366 bool HaveInsertPoint() const { 1367 return Builder.GetInsertBlock() != nullptr; 1368 } 1369 1370 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 1371 /// emitted IR has a place to go. Note that by definition, if this function 1372 /// creates a block then that block is unreachable; callers may do better to 1373 /// detect when no insertion point is defined and simply skip IR generation. 1374 void EnsureInsertPoint() { 1375 if (!HaveInsertPoint()) 1376 EmitBlock(createBasicBlock()); 1377 } 1378 1379 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1380 /// specified stmt yet. 1381 void ErrorUnsupported(const Stmt *S, const char *Type); 1382 1383 //===--------------------------------------------------------------------===// 1384 // Helpers 1385 //===--------------------------------------------------------------------===// 1386 1387 LValue MakeAddrLValue(llvm::Value *V, QualType T, 1388 CharUnits Alignment = CharUnits()) { 1389 return LValue::MakeAddr(V, T, Alignment, getContext(), 1390 CGM.getTBAAInfo(T)); 1391 } 1392 1393 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 1394 CharUnits Alignment; 1395 if (!T->isIncompleteType()) 1396 Alignment = getContext().getTypeAlignInChars(T); 1397 return LValue::MakeAddr(V, T, Alignment, getContext(), 1398 CGM.getTBAAInfo(T)); 1399 } 1400 1401 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 1402 /// block. The caller is responsible for setting an appropriate alignment on 1403 /// the alloca. 1404 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, 1405 const Twine &Name = "tmp"); 1406 1407 /// InitTempAlloca - Provide an initial value for the given alloca. 1408 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value); 1409 1410 /// CreateIRTemp - Create a temporary IR object of the given type, with 1411 /// appropriate alignment. This routine should only be used when an temporary 1412 /// value needs to be stored into an alloca (for example, to avoid explicit 1413 /// PHI construction), but the type is the IR type, not the type appropriate 1414 /// for storing in memory. 1415 llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp"); 1416 1417 /// CreateMemTemp - Create a temporary memory object of the given type, with 1418 /// appropriate alignment. 1419 llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp"); 1420 1421 /// CreateAggTemp - Create a temporary memory object for the given 1422 /// aggregate type. 1423 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 1424 CharUnits Alignment = getContext().getTypeAlignInChars(T); 1425 return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment, 1426 T.getQualifiers(), 1427 AggValueSlot::IsNotDestructed, 1428 AggValueSlot::DoesNotNeedGCBarriers, 1429 AggValueSlot::IsNotAliased); 1430 } 1431 1432 /// CreateInAllocaTmp - Create a temporary memory object for the given 1433 /// aggregate type. 1434 AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca"); 1435 1436 /// Emit a cast to void* in the appropriate address space. 1437 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 1438 1439 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 1440 /// expression and compare the result against zero, returning an Int1Ty value. 1441 llvm::Value *EvaluateExprAsBool(const Expr *E); 1442 1443 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 1444 void EmitIgnoredExpr(const Expr *E); 1445 1446 /// EmitAnyExpr - Emit code to compute the specified expression which can have 1447 /// any type. The result is returned as an RValue struct. If this is an 1448 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 1449 /// the result should be returned. 1450 /// 1451 /// \param ignoreResult True if the resulting value isn't used. 1452 RValue EmitAnyExpr(const Expr *E, 1453 AggValueSlot aggSlot = AggValueSlot::ignored(), 1454 bool ignoreResult = false); 1455 1456 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 1457 // or the value of the expression, depending on how va_list is defined. 1458 llvm::Value *EmitVAListRef(const Expr *E); 1459 1460 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 1461 /// always be accessible even if no aggregate location is provided. 1462 RValue EmitAnyExprToTemp(const Expr *E); 1463 1464 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 1465 /// arbitrary expression into the given memory location. 1466 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location, 1467 Qualifiers Quals, bool IsInitializer); 1468 1469 /// EmitExprAsInit - Emits the code necessary to initialize a 1470 /// location in memory with the given initializer. 1471 void EmitExprAsInit(const Expr *init, const ValueDecl *D, 1472 LValue lvalue, bool capturedByInit); 1473 1474 /// hasVolatileMember - returns true if aggregate type has a volatile 1475 /// member. 1476 bool hasVolatileMember(QualType T) { 1477 if (const RecordType *RT = T->getAs<RecordType>()) { 1478 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 1479 return RD->hasVolatileMember(); 1480 } 1481 return false; 1482 } 1483 /// EmitAggregateCopy - Emit an aggregate assignment. 1484 /// 1485 /// The difference to EmitAggregateCopy is that tail padding is not copied. 1486 /// This is required for correctness when assigning non-POD structures in C++. 1487 void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1488 QualType EltTy) { 1489 bool IsVolatile = hasVolatileMember(EltTy); 1490 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(), 1491 true); 1492 } 1493 1494 /// EmitAggregateCopy - Emit an aggregate copy. 1495 /// 1496 /// \param isVolatile - True iff either the source or the destination is 1497 /// volatile. 1498 /// \param isAssignment - If false, allow padding to be copied. This often 1499 /// yields more efficient. 1500 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1501 QualType EltTy, bool isVolatile=false, 1502 CharUnits Alignment = CharUnits::Zero(), 1503 bool isAssignment = false); 1504 1505 /// StartBlock - Start new block named N. If insert block is a dummy block 1506 /// then reuse it. 1507 void StartBlock(const char *N); 1508 1509 /// GetAddrOfLocalVar - Return the address of a local variable. 1510 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) { 1511 llvm::Value *Res = LocalDeclMap[VD]; 1512 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 1513 return Res; 1514 } 1515 1516 /// getOpaqueLValueMapping - Given an opaque value expression (which 1517 /// must be mapped to an l-value), return its mapping. 1518 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 1519 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 1520 1521 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 1522 it = OpaqueLValues.find(e); 1523 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 1524 return it->second; 1525 } 1526 1527 /// getOpaqueRValueMapping - Given an opaque value expression (which 1528 /// must be mapped to an r-value), return its mapping. 1529 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 1530 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 1531 1532 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 1533 it = OpaqueRValues.find(e); 1534 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 1535 return it->second; 1536 } 1537 1538 /// getAccessedFieldNo - Given an encoded value and a result number, return 1539 /// the input field number being accessed. 1540 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 1541 1542 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 1543 llvm::BasicBlock *GetIndirectGotoBlock(); 1544 1545 /// EmitNullInitialization - Generate code to set a value of the given type to 1546 /// null, If the type contains data member pointers, they will be initialized 1547 /// to -1 in accordance with the Itanium C++ ABI. 1548 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty); 1549 1550 // EmitVAArg - Generate code to get an argument from the passed in pointer 1551 // and update it accordingly. The return value is a pointer to the argument. 1552 // FIXME: We should be able to get rid of this method and use the va_arg 1553 // instruction in LLVM instead once it works well enough. 1554 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 1555 1556 /// emitArrayLength - Compute the length of an array, even if it's a 1557 /// VLA, and drill down to the base element type. 1558 llvm::Value *emitArrayLength(const ArrayType *arrayType, 1559 QualType &baseType, 1560 llvm::Value *&addr); 1561 1562 /// EmitVLASize - Capture all the sizes for the VLA expressions in 1563 /// the given variably-modified type and store them in the VLASizeMap. 1564 /// 1565 /// This function can be called with a null (unreachable) insert point. 1566 void EmitVariablyModifiedType(QualType Ty); 1567 1568 /// getVLASize - Returns an LLVM value that corresponds to the size, 1569 /// in non-variably-sized elements, of a variable length array type, 1570 /// plus that largest non-variably-sized element type. Assumes that 1571 /// the type has already been emitted with EmitVariablyModifiedType. 1572 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 1573 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 1574 1575 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 1576 /// generating code for an C++ member function. 1577 llvm::Value *LoadCXXThis() { 1578 assert(CXXThisValue && "no 'this' value for this function"); 1579 return CXXThisValue; 1580 } 1581 1582 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 1583 /// virtual bases. 1584 // FIXME: Every place that calls LoadCXXVTT is something 1585 // that needs to be abstracted properly. 1586 llvm::Value *LoadCXXVTT() { 1587 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 1588 return CXXStructorImplicitParamValue; 1589 } 1590 1591 /// LoadCXXStructorImplicitParam - Load the implicit parameter 1592 /// for a constructor/destructor. 1593 llvm::Value *LoadCXXStructorImplicitParam() { 1594 assert(CXXStructorImplicitParamValue && 1595 "no implicit argument value for this function"); 1596 return CXXStructorImplicitParamValue; 1597 } 1598 1599 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 1600 /// complete class to the given direct base. 1601 llvm::Value * 1602 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value, 1603 const CXXRecordDecl *Derived, 1604 const CXXRecordDecl *Base, 1605 bool BaseIsVirtual); 1606 1607 /// GetAddressOfBaseClass - This function will add the necessary delta to the 1608 /// load of 'this' and returns address of the base class. 1609 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 1610 const CXXRecordDecl *Derived, 1611 CastExpr::path_const_iterator PathBegin, 1612 CastExpr::path_const_iterator PathEnd, 1613 bool NullCheckValue); 1614 1615 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 1616 const CXXRecordDecl *Derived, 1617 CastExpr::path_const_iterator PathBegin, 1618 CastExpr::path_const_iterator PathEnd, 1619 bool NullCheckValue); 1620 1621 /// GetVTTParameter - Return the VTT parameter that should be passed to a 1622 /// base constructor/destructor with virtual bases. 1623 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 1624 /// to ItaniumCXXABI.cpp together with all the references to VTT. 1625 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 1626 bool Delegating); 1627 1628 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1629 CXXCtorType CtorType, 1630 const FunctionArgList &Args, 1631 SourceLocation Loc); 1632 // It's important not to confuse this and the previous function. Delegating 1633 // constructors are the C++0x feature. The constructor delegate optimization 1634 // is used to reduce duplication in the base and complete consturctors where 1635 // they are substantially the same. 1636 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1637 const FunctionArgList &Args); 1638 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 1639 bool ForVirtualBase, bool Delegating, 1640 llvm::Value *This, 1641 CallExpr::const_arg_iterator ArgBeg, 1642 CallExpr::const_arg_iterator ArgEnd); 1643 1644 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1645 llvm::Value *This, llvm::Value *Src, 1646 CallExpr::const_arg_iterator ArgBeg, 1647 CallExpr::const_arg_iterator ArgEnd); 1648 1649 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1650 const ConstantArrayType *ArrayTy, 1651 llvm::Value *ArrayPtr, 1652 CallExpr::const_arg_iterator ArgBeg, 1653 CallExpr::const_arg_iterator ArgEnd, 1654 bool ZeroInitialization = false); 1655 1656 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1657 llvm::Value *NumElements, 1658 llvm::Value *ArrayPtr, 1659 CallExpr::const_arg_iterator ArgBeg, 1660 CallExpr::const_arg_iterator ArgEnd, 1661 bool ZeroInitialization = false); 1662 1663 static Destroyer destroyCXXObject; 1664 1665 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 1666 bool ForVirtualBase, bool Delegating, 1667 llvm::Value *This); 1668 1669 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 1670 llvm::Value *NewPtr, llvm::Value *NumElements, 1671 llvm::Value *AllocSizeWithoutCookie); 1672 1673 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 1674 llvm::Value *Ptr); 1675 1676 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 1677 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 1678 1679 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 1680 QualType DeleteTy); 1681 1682 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1683 const Expr *Arg, bool IsDelete); 1684 1685 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 1686 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 1687 llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E); 1688 1689 /// \brief Situations in which we might emit a check for the suitability of a 1690 /// pointer or glvalue. 1691 enum TypeCheckKind { 1692 /// Checking the operand of a load. Must be suitably sized and aligned. 1693 TCK_Load, 1694 /// Checking the destination of a store. Must be suitably sized and aligned. 1695 TCK_Store, 1696 /// Checking the bound value in a reference binding. Must be suitably sized 1697 /// and aligned, but is not required to refer to an object (until the 1698 /// reference is used), per core issue 453. 1699 TCK_ReferenceBinding, 1700 /// Checking the object expression in a non-static data member access. Must 1701 /// be an object within its lifetime. 1702 TCK_MemberAccess, 1703 /// Checking the 'this' pointer for a call to a non-static member function. 1704 /// Must be an object within its lifetime. 1705 TCK_MemberCall, 1706 /// Checking the 'this' pointer for a constructor call. 1707 TCK_ConstructorCall, 1708 /// Checking the operand of a static_cast to a derived pointer type. Must be 1709 /// null or an object within its lifetime. 1710 TCK_DowncastPointer, 1711 /// Checking the operand of a static_cast to a derived reference type. Must 1712 /// be an object within its lifetime. 1713 TCK_DowncastReference 1714 }; 1715 1716 /// \brief Whether any type-checking sanitizers are enabled. If \c false, 1717 /// calls to EmitTypeCheck can be skipped. 1718 bool sanitizePerformTypeCheck() const; 1719 1720 /// \brief Emit a check that \p V is the address of storage of the 1721 /// appropriate size and alignment for an object of type \p Type. 1722 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 1723 QualType Type, CharUnits Alignment = CharUnits::Zero()); 1724 1725 /// \brief Emit a check that \p Base points into an array object, which 1726 /// we can access at index \p Index. \p Accessed should be \c false if we 1727 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 1728 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 1729 QualType IndexType, bool Accessed); 1730 1731 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1732 bool isInc, bool isPre); 1733 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 1734 bool isInc, bool isPre); 1735 //===--------------------------------------------------------------------===// 1736 // Declaration Emission 1737 //===--------------------------------------------------------------------===// 1738 1739 /// EmitDecl - Emit a declaration. 1740 /// 1741 /// This function can be called with a null (unreachable) insert point. 1742 void EmitDecl(const Decl &D); 1743 1744 /// EmitVarDecl - Emit a local variable declaration. 1745 /// 1746 /// This function can be called with a null (unreachable) insert point. 1747 void EmitVarDecl(const VarDecl &D); 1748 1749 void EmitScalarInit(const Expr *init, const ValueDecl *D, 1750 LValue lvalue, bool capturedByInit); 1751 void EmitScalarInit(llvm::Value *init, LValue lvalue); 1752 1753 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 1754 llvm::Value *Address); 1755 1756 /// EmitAutoVarDecl - Emit an auto variable declaration. 1757 /// 1758 /// This function can be called with a null (unreachable) insert point. 1759 void EmitAutoVarDecl(const VarDecl &D); 1760 1761 class AutoVarEmission { 1762 friend class CodeGenFunction; 1763 1764 const VarDecl *Variable; 1765 1766 /// The alignment of the variable. 1767 CharUnits Alignment; 1768 1769 /// The address of the alloca. Null if the variable was emitted 1770 /// as a global constant. 1771 llvm::Value *Address; 1772 1773 llvm::Value *NRVOFlag; 1774 1775 /// True if the variable is a __block variable. 1776 bool IsByRef; 1777 1778 /// True if the variable is of aggregate type and has a constant 1779 /// initializer. 1780 bool IsConstantAggregate; 1781 1782 /// Non-null if we should use lifetime annotations. 1783 llvm::Value *SizeForLifetimeMarkers; 1784 1785 struct Invalid {}; 1786 AutoVarEmission(Invalid) : Variable(nullptr) {} 1787 1788 AutoVarEmission(const VarDecl &variable) 1789 : Variable(&variable), Address(nullptr), NRVOFlag(nullptr), 1790 IsByRef(false), IsConstantAggregate(false), 1791 SizeForLifetimeMarkers(nullptr) {} 1792 1793 bool wasEmittedAsGlobal() const { return Address == nullptr; } 1794 1795 public: 1796 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 1797 1798 bool useLifetimeMarkers() const { 1799 return SizeForLifetimeMarkers != nullptr; 1800 } 1801 llvm::Value *getSizeForLifetimeMarkers() const { 1802 assert(useLifetimeMarkers()); 1803 return SizeForLifetimeMarkers; 1804 } 1805 1806 /// Returns the raw, allocated address, which is not necessarily 1807 /// the address of the object itself. 1808 llvm::Value *getAllocatedAddress() const { 1809 return Address; 1810 } 1811 1812 /// Returns the address of the object within this declaration. 1813 /// Note that this does not chase the forwarding pointer for 1814 /// __block decls. 1815 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const { 1816 if (!IsByRef) return Address; 1817 1818 return CGF.Builder.CreateStructGEP(Address, 1819 CGF.getByRefValueLLVMField(Variable), 1820 Variable->getNameAsString()); 1821 } 1822 }; 1823 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 1824 void EmitAutoVarInit(const AutoVarEmission &emission); 1825 void EmitAutoVarCleanups(const AutoVarEmission &emission); 1826 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 1827 QualType::DestructionKind dtorKind); 1828 1829 void EmitStaticVarDecl(const VarDecl &D, 1830 llvm::GlobalValue::LinkageTypes Linkage); 1831 1832 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 1833 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer, 1834 unsigned ArgNo); 1835 1836 /// protectFromPeepholes - Protect a value that we're intending to 1837 /// store to the side, but which will probably be used later, from 1838 /// aggressive peepholing optimizations that might delete it. 1839 /// 1840 /// Pass the result to unprotectFromPeepholes to declare that 1841 /// protection is no longer required. 1842 /// 1843 /// There's no particular reason why this shouldn't apply to 1844 /// l-values, it's just that no existing peepholes work on pointers. 1845 PeepholeProtection protectFromPeepholes(RValue rvalue); 1846 void unprotectFromPeepholes(PeepholeProtection protection); 1847 1848 //===--------------------------------------------------------------------===// 1849 // Statement Emission 1850 //===--------------------------------------------------------------------===// 1851 1852 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 1853 void EmitStopPoint(const Stmt *S); 1854 1855 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 1856 /// this function even if there is no current insertion point. 1857 /// 1858 /// This function may clear the current insertion point; callers should use 1859 /// EnsureInsertPoint if they wish to subsequently generate code without first 1860 /// calling EmitBlock, EmitBranch, or EmitStmt. 1861 void EmitStmt(const Stmt *S); 1862 1863 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 1864 /// necessarily require an insertion point or debug information; typically 1865 /// because the statement amounts to a jump or a container of other 1866 /// statements. 1867 /// 1868 /// \return True if the statement was handled. 1869 bool EmitSimpleStmt(const Stmt *S); 1870 1871 llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 1872 AggValueSlot AVS = AggValueSlot::ignored()); 1873 llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S, 1874 bool GetLast = false, 1875 AggValueSlot AVS = 1876 AggValueSlot::ignored()); 1877 1878 /// EmitLabel - Emit the block for the given label. It is legal to call this 1879 /// function even if there is no current insertion point. 1880 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 1881 1882 void EmitLabelStmt(const LabelStmt &S); 1883 void EmitAttributedStmt(const AttributedStmt &S); 1884 void EmitGotoStmt(const GotoStmt &S); 1885 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 1886 void EmitIfStmt(const IfStmt &S); 1887 1888 void EmitCondBrHints(llvm::LLVMContext &Context, llvm::BranchInst *CondBr, 1889 const ArrayRef<const Attr *> &Attrs); 1890 void EmitWhileStmt(const WhileStmt &S, 1891 const ArrayRef<const Attr *> &Attrs = None); 1892 void EmitDoStmt(const DoStmt &S, const ArrayRef<const Attr *> &Attrs = None); 1893 void EmitForStmt(const ForStmt &S, 1894 const ArrayRef<const Attr *> &Attrs = None); 1895 void EmitReturnStmt(const ReturnStmt &S); 1896 void EmitDeclStmt(const DeclStmt &S); 1897 void EmitBreakStmt(const BreakStmt &S); 1898 void EmitContinueStmt(const ContinueStmt &S); 1899 void EmitSwitchStmt(const SwitchStmt &S); 1900 void EmitDefaultStmt(const DefaultStmt &S); 1901 void EmitCaseStmt(const CaseStmt &S); 1902 void EmitCaseStmtRange(const CaseStmt &S); 1903 void EmitAsmStmt(const AsmStmt &S); 1904 1905 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 1906 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 1907 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 1908 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 1909 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 1910 1911 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1912 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1913 1914 void EmitCXXTryStmt(const CXXTryStmt &S); 1915 void EmitSEHTryStmt(const SEHTryStmt &S); 1916 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 1917 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 1918 const ArrayRef<const Attr *> &Attrs = None); 1919 1920 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 1921 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 1922 llvm::Value *GenerateCapturedStmtArgument(const CapturedStmt &S); 1923 1924 void EmitOMPParallelDirective(const OMPParallelDirective &S); 1925 void EmitOMPSimdDirective(const OMPSimdDirective &S); 1926 void EmitOMPForDirective(const OMPForDirective &S); 1927 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 1928 void EmitOMPSectionDirective(const OMPSectionDirective &S); 1929 void EmitOMPSingleDirective(const OMPSingleDirective &S); 1930 void EmitOMPMasterDirective(const OMPMasterDirective &S); 1931 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 1932 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 1933 void EmitOMPTaskDirective(const OMPTaskDirective &S); 1934 1935 //===--------------------------------------------------------------------===// 1936 // LValue Expression Emission 1937 //===--------------------------------------------------------------------===// 1938 1939 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 1940 RValue GetUndefRValue(QualType Ty); 1941 1942 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 1943 /// and issue an ErrorUnsupported style diagnostic (using the 1944 /// provided Name). 1945 RValue EmitUnsupportedRValue(const Expr *E, 1946 const char *Name); 1947 1948 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 1949 /// an ErrorUnsupported style diagnostic (using the provided Name). 1950 LValue EmitUnsupportedLValue(const Expr *E, 1951 const char *Name); 1952 1953 /// EmitLValue - Emit code to compute a designator that specifies the location 1954 /// of the expression. 1955 /// 1956 /// This can return one of two things: a simple address or a bitfield 1957 /// reference. In either case, the LLVM Value* in the LValue structure is 1958 /// guaranteed to be an LLVM pointer type. 1959 /// 1960 /// If this returns a bitfield reference, nothing about the pointee type of 1961 /// the LLVM value is known: For example, it may not be a pointer to an 1962 /// integer. 1963 /// 1964 /// If this returns a normal address, and if the lvalue's C type is fixed 1965 /// size, this method guarantees that the returned pointer type will point to 1966 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 1967 /// variable length type, this is not possible. 1968 /// 1969 LValue EmitLValue(const Expr *E); 1970 1971 /// \brief Same as EmitLValue but additionally we generate checking code to 1972 /// guard against undefined behavior. This is only suitable when we know 1973 /// that the address will be used to access the object. 1974 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 1975 1976 RValue convertTempToRValue(llvm::Value *addr, QualType type, 1977 SourceLocation Loc); 1978 1979 void EmitAtomicInit(Expr *E, LValue lvalue); 1980 1981 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 1982 AggValueSlot slot = AggValueSlot::ignored()); 1983 1984 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 1985 1986 /// EmitToMemory - Change a scalar value from its value 1987 /// representation to its in-memory representation. 1988 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 1989 1990 /// EmitFromMemory - Change a scalar value from its memory 1991 /// representation to its value representation. 1992 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 1993 1994 /// EmitLoadOfScalar - Load a scalar value from an address, taking 1995 /// care to appropriately convert from the memory representation to 1996 /// the LLVM value representation. 1997 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 1998 unsigned Alignment, QualType Ty, 1999 SourceLocation Loc, 2000 llvm::MDNode *TBAAInfo = nullptr, 2001 QualType TBAABaseTy = QualType(), 2002 uint64_t TBAAOffset = 0); 2003 2004 /// EmitLoadOfScalar - Load a scalar value from an address, taking 2005 /// care to appropriately convert from the memory representation to 2006 /// the LLVM value representation. The l-value must be a simple 2007 /// l-value. 2008 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 2009 2010 /// EmitStoreOfScalar - Store a scalar value to an address, taking 2011 /// care to appropriately convert from the memory representation to 2012 /// the LLVM value representation. 2013 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 2014 bool Volatile, unsigned Alignment, QualType Ty, 2015 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false, 2016 QualType TBAABaseTy = QualType(), 2017 uint64_t TBAAOffset = 0); 2018 2019 /// EmitStoreOfScalar - Store a scalar value to an address, taking 2020 /// care to appropriately convert from the memory representation to 2021 /// the LLVM value representation. The l-value must be a simple 2022 /// l-value. The isInit flag indicates whether this is an initialization. 2023 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 2024 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 2025 2026 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 2027 /// this method emits the address of the lvalue, then loads the result as an 2028 /// rvalue, returning the rvalue. 2029 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 2030 RValue EmitLoadOfExtVectorElementLValue(LValue V); 2031 RValue EmitLoadOfBitfieldLValue(LValue LV); 2032 RValue EmitLoadOfGlobalRegLValue(LValue LV); 2033 2034 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 2035 /// lvalue, where both are guaranteed to the have the same type, and that type 2036 /// is 'Ty'. 2037 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false); 2038 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 2039 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 2040 2041 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 2042 /// as EmitStoreThroughLValue. 2043 /// 2044 /// \param Result [out] - If non-null, this will be set to a Value* for the 2045 /// bit-field contents after the store, appropriate for use as the result of 2046 /// an assignment to the bit-field. 2047 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 2048 llvm::Value **Result=nullptr); 2049 2050 /// Emit an l-value for an assignment (simple or compound) of complex type. 2051 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 2052 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 2053 LValue EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E, 2054 llvm::Value *&Result); 2055 2056 // Note: only available for agg return types 2057 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 2058 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 2059 // Note: only available for agg return types 2060 LValue EmitCallExprLValue(const CallExpr *E); 2061 // Note: only available for agg return types 2062 LValue EmitVAArgExprLValue(const VAArgExpr *E); 2063 LValue EmitDeclRefLValue(const DeclRefExpr *E); 2064 LValue EmitReadRegister(const VarDecl *VD); 2065 LValue EmitStringLiteralLValue(const StringLiteral *E); 2066 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 2067 LValue EmitPredefinedLValue(const PredefinedExpr *E); 2068 LValue EmitUnaryOpLValue(const UnaryOperator *E); 2069 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 2070 bool Accessed = false); 2071 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 2072 LValue EmitMemberExpr(const MemberExpr *E); 2073 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 2074 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 2075 LValue EmitInitListLValue(const InitListExpr *E); 2076 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 2077 LValue EmitCastLValue(const CastExpr *E); 2078 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 2079 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 2080 2081 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 2082 2083 class ConstantEmission { 2084 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 2085 ConstantEmission(llvm::Constant *C, bool isReference) 2086 : ValueAndIsReference(C, isReference) {} 2087 public: 2088 ConstantEmission() {} 2089 static ConstantEmission forReference(llvm::Constant *C) { 2090 return ConstantEmission(C, true); 2091 } 2092 static ConstantEmission forValue(llvm::Constant *C) { 2093 return ConstantEmission(C, false); 2094 } 2095 2096 LLVM_EXPLICIT operator bool() const { 2097 return ValueAndIsReference.getOpaqueValue() != nullptr; 2098 } 2099 2100 bool isReference() const { return ValueAndIsReference.getInt(); } 2101 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 2102 assert(isReference()); 2103 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 2104 refExpr->getType()); 2105 } 2106 2107 llvm::Constant *getValue() const { 2108 assert(!isReference()); 2109 return ValueAndIsReference.getPointer(); 2110 } 2111 }; 2112 2113 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 2114 2115 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 2116 AggValueSlot slot = AggValueSlot::ignored()); 2117 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 2118 2119 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2120 const ObjCIvarDecl *Ivar); 2121 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 2122 LValue EmitLValueForLambdaField(const FieldDecl *Field); 2123 2124 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 2125 /// if the Field is a reference, this will return the address of the reference 2126 /// and not the address of the value stored in the reference. 2127 LValue EmitLValueForFieldInitialization(LValue Base, 2128 const FieldDecl* Field); 2129 2130 LValue EmitLValueForIvar(QualType ObjectTy, 2131 llvm::Value* Base, const ObjCIvarDecl *Ivar, 2132 unsigned CVRQualifiers); 2133 2134 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 2135 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 2136 LValue EmitLambdaLValue(const LambdaExpr *E); 2137 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 2138 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 2139 2140 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 2141 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 2142 LValue EmitStmtExprLValue(const StmtExpr *E); 2143 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 2144 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 2145 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init); 2146 2147 //===--------------------------------------------------------------------===// 2148 // Scalar Expression Emission 2149 //===--------------------------------------------------------------------===// 2150 2151 /// EmitCall - Generate a call of the given function, expecting the given 2152 /// result type, and using the given argument list which specifies both the 2153 /// LLVM arguments and the types they were derived from. 2154 /// 2155 /// \param TargetDecl - If given, the decl of the function in a direct call; 2156 /// used to set attributes on the call (noreturn, etc.). 2157 RValue EmitCall(const CGFunctionInfo &FnInfo, 2158 llvm::Value *Callee, 2159 ReturnValueSlot ReturnValue, 2160 const CallArgList &Args, 2161 const Decl *TargetDecl = nullptr, 2162 llvm::Instruction **callOrInvoke = nullptr); 2163 2164 RValue EmitCall(QualType FnType, llvm::Value *Callee, 2165 SourceLocation CallLoc, 2166 ReturnValueSlot ReturnValue, 2167 CallExpr::const_arg_iterator ArgBeg, 2168 CallExpr::const_arg_iterator ArgEnd, 2169 const Decl *TargetDecl = nullptr); 2170 RValue EmitCallExpr(const CallExpr *E, 2171 ReturnValueSlot ReturnValue = ReturnValueSlot()); 2172 2173 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2174 const Twine &name = ""); 2175 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2176 ArrayRef<llvm::Value*> args, 2177 const Twine &name = ""); 2178 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2179 const Twine &name = ""); 2180 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2181 ArrayRef<llvm::Value*> args, 2182 const Twine &name = ""); 2183 2184 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2185 ArrayRef<llvm::Value *> Args, 2186 const Twine &Name = ""); 2187 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2188 const Twine &Name = ""); 2189 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2190 ArrayRef<llvm::Value*> args, 2191 const Twine &name = ""); 2192 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2193 const Twine &name = ""); 2194 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 2195 ArrayRef<llvm::Value*> args); 2196 2197 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 2198 NestedNameSpecifier *Qual, 2199 llvm::Type *Ty); 2200 2201 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 2202 CXXDtorType Type, 2203 const CXXRecordDecl *RD); 2204 2205 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 2206 SourceLocation CallLoc, 2207 llvm::Value *Callee, 2208 ReturnValueSlot ReturnValue, 2209 llvm::Value *This, 2210 llvm::Value *ImplicitParam, 2211 QualType ImplicitParamTy, 2212 CallExpr::const_arg_iterator ArgBeg, 2213 CallExpr::const_arg_iterator ArgEnd); 2214 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 2215 ReturnValueSlot ReturnValue); 2216 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 2217 ReturnValueSlot ReturnValue); 2218 2219 llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 2220 const CXXMethodDecl *MD, 2221 llvm::Value *This); 2222 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 2223 const CXXMethodDecl *MD, 2224 ReturnValueSlot ReturnValue); 2225 2226 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 2227 ReturnValueSlot ReturnValue); 2228 2229 2230 RValue EmitBuiltinExpr(const FunctionDecl *FD, 2231 unsigned BuiltinID, const CallExpr *E); 2232 2233 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 2234 2235 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 2236 /// is unhandled by the current target. 2237 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2238 2239 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 2240 const llvm::CmpInst::Predicate Fp, 2241 const llvm::CmpInst::Predicate Ip, 2242 const llvm::Twine &Name = ""); 2243 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2244 2245 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 2246 unsigned LLVMIntrinsic, 2247 unsigned AltLLVMIntrinsic, 2248 const char *NameHint, 2249 unsigned Modifier, 2250 const CallExpr *E, 2251 SmallVectorImpl<llvm::Value *> &Ops, 2252 llvm::Value *Align = nullptr); 2253 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 2254 unsigned Modifier, llvm::Type *ArgTy, 2255 const CallExpr *E); 2256 llvm::Value *EmitNeonCall(llvm::Function *F, 2257 SmallVectorImpl<llvm::Value*> &O, 2258 const char *name, 2259 unsigned shift = 0, bool rightshift = false); 2260 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 2261 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 2262 bool negateForRightShift); 2263 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 2264 llvm::Type *Ty, bool usgn, const char *name); 2265 // Helper functions for EmitAArch64BuiltinExpr. 2266 llvm::Value *vectorWrapScalar8(llvm::Value *Op); 2267 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 2268 llvm::Value *emitVectorWrappedScalar8Intrinsic( 2269 unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name); 2270 llvm::Value *emitVectorWrappedScalar16Intrinsic( 2271 unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name); 2272 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2273 llvm::Value *EmitNeon64Call(llvm::Function *F, 2274 llvm::SmallVectorImpl<llvm::Value *> &O, 2275 const char *name); 2276 2277 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 2278 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2279 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2280 llvm::Value *EmitR600BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2281 2282 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 2283 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 2284 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 2285 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 2286 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 2287 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 2288 const ObjCMethodDecl *MethodWithObjects); 2289 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 2290 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 2291 ReturnValueSlot Return = ReturnValueSlot()); 2292 2293 /// Retrieves the default cleanup kind for an ARC cleanup. 2294 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 2295 CleanupKind getARCCleanupKind() { 2296 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 2297 ? NormalAndEHCleanup : NormalCleanup; 2298 } 2299 2300 // ARC primitives. 2301 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr); 2302 void EmitARCDestroyWeak(llvm::Value *addr); 2303 llvm::Value *EmitARCLoadWeak(llvm::Value *addr); 2304 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr); 2305 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr, 2306 bool ignored); 2307 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src); 2308 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src); 2309 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 2310 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 2311 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 2312 bool resultIgnored); 2313 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value, 2314 bool resultIgnored); 2315 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 2316 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 2317 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 2318 void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise); 2319 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 2320 llvm::Value *EmitARCAutorelease(llvm::Value *value); 2321 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 2322 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 2323 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 2324 2325 std::pair<LValue,llvm::Value*> 2326 EmitARCStoreAutoreleasing(const BinaryOperator *e); 2327 std::pair<LValue,llvm::Value*> 2328 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 2329 2330 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 2331 2332 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr); 2333 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 2334 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 2335 2336 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 2337 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 2338 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 2339 2340 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 2341 2342 static Destroyer destroyARCStrongImprecise; 2343 static Destroyer destroyARCStrongPrecise; 2344 static Destroyer destroyARCWeak; 2345 2346 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 2347 llvm::Value *EmitObjCAutoreleasePoolPush(); 2348 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 2349 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 2350 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 2351 2352 /// \brief Emits a reference binding to the passed in expression. 2353 RValue EmitReferenceBindingToExpr(const Expr *E); 2354 2355 //===--------------------------------------------------------------------===// 2356 // Expression Emission 2357 //===--------------------------------------------------------------------===// 2358 2359 // Expressions are broken into three classes: scalar, complex, aggregate. 2360 2361 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 2362 /// scalar type, returning the result. 2363 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 2364 2365 /// EmitScalarConversion - Emit a conversion from the specified type to the 2366 /// specified destination type, both of which are LLVM scalar types. 2367 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 2368 QualType DstTy); 2369 2370 /// EmitComplexToScalarConversion - Emit a conversion from the specified 2371 /// complex type to the specified destination type, where the destination type 2372 /// is an LLVM scalar type. 2373 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 2374 QualType DstTy); 2375 2376 2377 /// EmitAggExpr - Emit the computation of the specified expression 2378 /// of aggregate type. The result is computed into the given slot, 2379 /// which may be null to indicate that the value is not needed. 2380 void EmitAggExpr(const Expr *E, AggValueSlot AS); 2381 2382 /// EmitAggExprToLValue - Emit the computation of the specified expression of 2383 /// aggregate type into a temporary LValue. 2384 LValue EmitAggExprToLValue(const Expr *E); 2385 2386 /// EmitGCMemmoveCollectable - Emit special API for structs with object 2387 /// pointers. 2388 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 2389 QualType Ty); 2390 2391 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2392 /// make sure it survives garbage collection until this point. 2393 void EmitExtendGCLifetime(llvm::Value *object); 2394 2395 /// EmitComplexExpr - Emit the computation of the specified expression of 2396 /// complex type, returning the result. 2397 ComplexPairTy EmitComplexExpr(const Expr *E, 2398 bool IgnoreReal = false, 2399 bool IgnoreImag = false); 2400 2401 /// EmitComplexExprIntoLValue - Emit the given expression of complex 2402 /// type and place its result into the specified l-value. 2403 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 2404 2405 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 2406 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 2407 2408 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 2409 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 2410 2411 /// CreateStaticVarDecl - Create a zero-initialized LLVM global for 2412 /// a static local variable. 2413 llvm::Constant *CreateStaticVarDecl(const VarDecl &D, 2414 const char *Separator, 2415 llvm::GlobalValue::LinkageTypes Linkage); 2416 2417 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 2418 /// global variable that has already been created for it. If the initializer 2419 /// has a different type than GV does, this may free GV and return a different 2420 /// one. Otherwise it just returns GV. 2421 llvm::GlobalVariable * 2422 AddInitializerToStaticVarDecl(const VarDecl &D, 2423 llvm::GlobalVariable *GV); 2424 2425 2426 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 2427 /// variable with global storage. 2428 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 2429 bool PerformInit); 2430 2431 /// Call atexit() with a function that passes the given argument to 2432 /// the given function. 2433 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn, 2434 llvm::Constant *addr); 2435 2436 /// Emit code in this function to perform a guarded variable 2437 /// initialization. Guarded initializations are used when it's not 2438 /// possible to prove that an initialization will be done exactly 2439 /// once, e.g. with a static local variable or a static data member 2440 /// of a class template. 2441 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 2442 bool PerformInit); 2443 2444 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 2445 /// variables. 2446 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 2447 ArrayRef<llvm::Constant *> Decls, 2448 llvm::GlobalVariable *Guard = nullptr); 2449 2450 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 2451 /// variables. 2452 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 2453 const std::vector<std::pair<llvm::WeakVH, 2454 llvm::Constant*> > &DtorsAndObjects); 2455 2456 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 2457 const VarDecl *D, 2458 llvm::GlobalVariable *Addr, 2459 bool PerformInit); 2460 2461 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 2462 2463 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src, 2464 const Expr *Exp); 2465 2466 void enterFullExpression(const ExprWithCleanups *E) { 2467 if (E->getNumObjects() == 0) return; 2468 enterNonTrivialFullExpression(E); 2469 } 2470 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 2471 2472 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 2473 2474 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 2475 2476 RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = nullptr); 2477 2478 //===--------------------------------------------------------------------===// 2479 // Annotations Emission 2480 //===--------------------------------------------------------------------===// 2481 2482 /// Emit an annotation call (intrinsic or builtin). 2483 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 2484 llvm::Value *AnnotatedVal, 2485 StringRef AnnotationStr, 2486 SourceLocation Location); 2487 2488 /// Emit local annotations for the local variable V, declared by D. 2489 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 2490 2491 /// Emit field annotations for the given field & value. Returns the 2492 /// annotation result. 2493 llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V); 2494 2495 //===--------------------------------------------------------------------===// 2496 // Internal Helpers 2497 //===--------------------------------------------------------------------===// 2498 2499 /// ContainsLabel - Return true if the statement contains a label in it. If 2500 /// this statement is not executed normally, it not containing a label means 2501 /// that we can just remove the code. 2502 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 2503 2504 /// containsBreak - Return true if the statement contains a break out of it. 2505 /// If the statement (recursively) contains a switch or loop with a break 2506 /// inside of it, this is fine. 2507 static bool containsBreak(const Stmt *S); 2508 2509 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2510 /// to a constant, or if it does but contains a label, return false. If it 2511 /// constant folds return true and set the boolean result in Result. 2512 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result); 2513 2514 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2515 /// to a constant, or if it does but contains a label, return false. If it 2516 /// constant folds return true and set the folded value. 2517 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result); 2518 2519 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 2520 /// if statement) to the specified blocks. Based on the condition, this might 2521 /// try to simplify the codegen of the conditional based on the branch. 2522 /// TrueCount should be the number of times we expect the condition to 2523 /// evaluate to true based on PGO data. 2524 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 2525 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 2526 2527 /// \brief Emit a description of a type in a format suitable for passing to 2528 /// a runtime sanitizer handler. 2529 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 2530 2531 /// \brief Convert a value into a format suitable for passing to a runtime 2532 /// sanitizer handler. 2533 llvm::Value *EmitCheckValue(llvm::Value *V); 2534 2535 /// \brief Emit a description of a source location in a format suitable for 2536 /// passing to a runtime sanitizer handler. 2537 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 2538 2539 /// \brief Specify under what conditions this check can be recovered 2540 enum CheckRecoverableKind { 2541 /// Always terminate program execution if this check fails 2542 CRK_Unrecoverable, 2543 /// Check supports recovering, allows user to specify which 2544 CRK_Recoverable, 2545 /// Runtime conditionally aborts, always need to support recovery. 2546 CRK_AlwaysRecoverable 2547 }; 2548 2549 /// \brief Create a basic block that will call a handler function in a 2550 /// sanitizer runtime with the provided arguments, and create a conditional 2551 /// branch to it. 2552 void EmitCheck(llvm::Value *Checked, StringRef CheckName, 2553 ArrayRef<llvm::Constant *> StaticArgs, 2554 ArrayRef<llvm::Value *> DynamicArgs, 2555 CheckRecoverableKind Recoverable); 2556 2557 /// \brief Create a basic block that will call the trap intrinsic, and emit a 2558 /// conditional branch to it, for the -ftrapv checks. 2559 void EmitTrapCheck(llvm::Value *Checked); 2560 2561 /// EmitCallArg - Emit a single call argument. 2562 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 2563 2564 /// EmitDelegateCallArg - We are performing a delegate call; that 2565 /// is, the current function is delegating to another one. Produce 2566 /// a r-value suitable for passing the given parameter. 2567 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 2568 SourceLocation loc); 2569 2570 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 2571 /// point operation, expressed as the maximum relative error in ulp. 2572 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 2573 2574 private: 2575 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 2576 void EmitReturnOfRValue(RValue RV, QualType Ty); 2577 2578 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 2579 2580 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 2581 DeferredReplacements; 2582 2583 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 2584 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 2585 /// 2586 /// \param AI - The first function argument of the expansion. 2587 /// \return The argument following the last expanded function 2588 /// argument. 2589 llvm::Function::arg_iterator 2590 ExpandTypeFromArgs(QualType Ty, LValue Dst, 2591 llvm::Function::arg_iterator AI); 2592 2593 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 2594 /// Ty, into individual arguments on the provided vector \arg Args. See 2595 /// ABIArgInfo::Expand. 2596 void ExpandTypeToArgs(QualType Ty, RValue Src, 2597 SmallVectorImpl<llvm::Value *> &Args, 2598 llvm::FunctionType *IRFuncTy); 2599 2600 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 2601 const Expr *InputExpr, std::string &ConstraintStr); 2602 2603 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 2604 LValue InputValue, QualType InputType, 2605 std::string &ConstraintStr, 2606 SourceLocation Loc); 2607 2608 public: 2609 /// EmitCallArgs - Emit call arguments for a function. 2610 template <typename T> 2611 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 2612 CallExpr::const_arg_iterator ArgBeg, 2613 CallExpr::const_arg_iterator ArgEnd, 2614 bool ForceColumnInfo = false) { 2615 if (CallArgTypeInfo) { 2616 EmitCallArgs(Args, CallArgTypeInfo->isVariadic(), 2617 CallArgTypeInfo->param_type_begin(), 2618 CallArgTypeInfo->param_type_end(), ArgBeg, ArgEnd, 2619 ForceColumnInfo); 2620 } else { 2621 // T::param_type_iterator might not have a default ctor. 2622 const QualType *NoIter = nullptr; 2623 EmitCallArgs(Args, /*AllowExtraArguments=*/true, NoIter, NoIter, ArgBeg, 2624 ArgEnd, ForceColumnInfo); 2625 } 2626 } 2627 2628 template<typename ArgTypeIterator> 2629 void EmitCallArgs(CallArgList& Args, 2630 bool AllowExtraArguments, 2631 ArgTypeIterator ArgTypeBeg, 2632 ArgTypeIterator ArgTypeEnd, 2633 CallExpr::const_arg_iterator ArgBeg, 2634 CallExpr::const_arg_iterator ArgEnd, 2635 bool ForceColumnInfo = false) { 2636 SmallVector<QualType, 16> ArgTypes; 2637 CallExpr::const_arg_iterator Arg = ArgBeg; 2638 2639 // First, use the argument types that the type info knows about 2640 for (ArgTypeIterator I = ArgTypeBeg, E = ArgTypeEnd; I != E; ++I, ++Arg) { 2641 assert(Arg != ArgEnd && "Running over edge of argument list!"); 2642 #ifndef NDEBUG 2643 QualType ArgType = *I; 2644 QualType ActualArgType = Arg->getType(); 2645 if (ArgType->isPointerType() && ActualArgType->isPointerType()) { 2646 QualType ActualBaseType = 2647 ActualArgType->getAs<PointerType>()->getPointeeType(); 2648 QualType ArgBaseType = 2649 ArgType->getAs<PointerType>()->getPointeeType(); 2650 if (ArgBaseType->isVariableArrayType()) { 2651 if (const VariableArrayType *VAT = 2652 getContext().getAsVariableArrayType(ActualBaseType)) { 2653 if (!VAT->getSizeExpr()) 2654 ActualArgType = ArgType; 2655 } 2656 } 2657 } 2658 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 2659 getTypePtr() == 2660 getContext().getCanonicalType(ActualArgType).getTypePtr() && 2661 "type mismatch in call argument!"); 2662 #endif 2663 ArgTypes.push_back(*I); 2664 } 2665 2666 // Either we've emitted all the call args, or we have a call to variadic 2667 // function or some other call that allows extra arguments. 2668 assert((Arg == ArgEnd || AllowExtraArguments) && 2669 "Extra arguments in non-variadic function!"); 2670 2671 // If we still have any arguments, emit them using the type of the argument. 2672 for (; Arg != ArgEnd; ++Arg) 2673 ArgTypes.push_back(Arg->getType()); 2674 2675 EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, ForceColumnInfo); 2676 } 2677 2678 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 2679 CallExpr::const_arg_iterator ArgBeg, 2680 CallExpr::const_arg_iterator ArgEnd, 2681 bool ForceColumnInfo = false); 2682 2683 private: 2684 const TargetCodeGenInfo &getTargetHooks() const { 2685 return CGM.getTargetCodeGenInfo(); 2686 } 2687 2688 void EmitDeclMetadata(); 2689 2690 CodeGenModule::ByrefHelpers * 2691 buildByrefHelpers(llvm::StructType &byrefType, 2692 const AutoVarEmission &emission); 2693 2694 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 2695 2696 /// GetPointeeAlignment - Given an expression with a pointer type, emit the 2697 /// value and compute our best estimate of the alignment of the pointee. 2698 std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr); 2699 }; 2700 2701 /// Helper class with most of the code for saving a value for a 2702 /// conditional expression cleanup. 2703 struct DominatingLLVMValue { 2704 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 2705 2706 /// Answer whether the given value needs extra work to be saved. 2707 static bool needsSaving(llvm::Value *value) { 2708 // If it's not an instruction, we don't need to save. 2709 if (!isa<llvm::Instruction>(value)) return false; 2710 2711 // If it's an instruction in the entry block, we don't need to save. 2712 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 2713 return (block != &block->getParent()->getEntryBlock()); 2714 } 2715 2716 /// Try to save the given value. 2717 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 2718 if (!needsSaving(value)) return saved_type(value, false); 2719 2720 // Otherwise we need an alloca. 2721 llvm::Value *alloca = 2722 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save"); 2723 CGF.Builder.CreateStore(value, alloca); 2724 2725 return saved_type(alloca, true); 2726 } 2727 2728 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 2729 if (!value.getInt()) return value.getPointer(); 2730 return CGF.Builder.CreateLoad(value.getPointer()); 2731 } 2732 }; 2733 2734 /// A partial specialization of DominatingValue for llvm::Values that 2735 /// might be llvm::Instructions. 2736 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 2737 typedef T *type; 2738 static type restore(CodeGenFunction &CGF, saved_type value) { 2739 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 2740 } 2741 }; 2742 2743 /// A specialization of DominatingValue for RValue. 2744 template <> struct DominatingValue<RValue> { 2745 typedef RValue type; 2746 class saved_type { 2747 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 2748 AggregateAddress, ComplexAddress }; 2749 2750 llvm::Value *Value; 2751 Kind K; 2752 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {} 2753 2754 public: 2755 static bool needsSaving(RValue value); 2756 static saved_type save(CodeGenFunction &CGF, RValue value); 2757 RValue restore(CodeGenFunction &CGF); 2758 2759 // implementations in CGExprCXX.cpp 2760 }; 2761 2762 static bool needsSaving(type value) { 2763 return saved_type::needsSaving(value); 2764 } 2765 static saved_type save(CodeGenFunction &CGF, type value) { 2766 return saved_type::save(CGF, value); 2767 } 2768 static type restore(CodeGenFunction &CGF, saved_type value) { 2769 return value.restore(CGF); 2770 } 2771 }; 2772 2773 } // end namespace CodeGen 2774 } // end namespace clang 2775 2776 #endif 2777