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