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