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