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