1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This is the internal per-function state used for llvm translation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H 14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H 15 16 #include "CGBuilder.h" 17 #include "CGDebugInfo.h" 18 #include "CGLoopInfo.h" 19 #include "CGValue.h" 20 #include "CodeGenModule.h" 21 #include "CodeGenPGO.h" 22 #include "EHScopeStack.h" 23 #include "VarBypassDetector.h" 24 #include "clang/AST/CharUnits.h" 25 #include "clang/AST/CurrentSourceLocExprScope.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/Type.h" 30 #include "clang/Basic/ABI.h" 31 #include "clang/Basic/CapturedStmt.h" 32 #include "clang/Basic/CodeGenOptions.h" 33 #include "clang/Basic/OpenMPKinds.h" 34 #include "clang/Basic/TargetInfo.h" 35 #include "llvm/ADT/ArrayRef.h" 36 #include "llvm/ADT/DenseMap.h" 37 #include "llvm/ADT/MapVector.h" 38 #include "llvm/ADT/SmallVector.h" 39 #include "llvm/IR/ValueHandle.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Transforms/Utils/SanitizerStats.h" 42 43 namespace llvm { 44 class BasicBlock; 45 class LLVMContext; 46 class MDNode; 47 class Module; 48 class SwitchInst; 49 class Twine; 50 class Value; 51 } 52 53 namespace clang { 54 class ASTContext; 55 class BlockDecl; 56 class CXXDestructorDecl; 57 class CXXForRangeStmt; 58 class CXXTryStmt; 59 class Decl; 60 class LabelDecl; 61 class EnumConstantDecl; 62 class FunctionDecl; 63 class FunctionProtoType; 64 class LabelStmt; 65 class ObjCContainerDecl; 66 class ObjCInterfaceDecl; 67 class ObjCIvarDecl; 68 class ObjCMethodDecl; 69 class ObjCImplementationDecl; 70 class ObjCPropertyImplDecl; 71 class TargetInfo; 72 class VarDecl; 73 class ObjCForCollectionStmt; 74 class ObjCAtTryStmt; 75 class ObjCAtThrowStmt; 76 class ObjCAtSynchronizedStmt; 77 class ObjCAutoreleasePoolStmt; 78 class ReturnsNonNullAttr; 79 80 namespace analyze_os_log { 81 class OSLogBufferLayout; 82 } 83 84 namespace CodeGen { 85 class CodeGenTypes; 86 class CGCallee; 87 class CGFunctionInfo; 88 class CGRecordLayout; 89 class CGBlockInfo; 90 class CGCXXABI; 91 class BlockByrefHelpers; 92 class BlockByrefInfo; 93 class BlockFlags; 94 class BlockFieldFlags; 95 class RegionCodeGenTy; 96 class TargetCodeGenInfo; 97 struct OMPTaskDataTy; 98 struct CGCoroData; 99 100 /// The kind of evaluation to perform on values of a particular 101 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 102 /// CGExprAgg? 103 /// 104 /// TODO: should vectors maybe be split out into their own thing? 105 enum TypeEvaluationKind { 106 TEK_Scalar, 107 TEK_Complex, 108 TEK_Aggregate 109 }; 110 111 #define LIST_SANITIZER_CHECKS \ 112 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \ 113 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \ 114 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \ 115 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \ 116 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \ 117 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \ 118 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 1) \ 119 SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \ 120 SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \ 121 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \ 122 SANITIZER_CHECK(MissingReturn, missing_return, 0) \ 123 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \ 124 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \ 125 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \ 126 SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \ 127 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \ 128 SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \ 129 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \ 130 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \ 131 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \ 132 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \ 133 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \ 134 SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \ 135 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0) 136 137 enum SanitizerHandler { 138 #define SANITIZER_CHECK(Enum, Name, Version) Enum, 139 LIST_SANITIZER_CHECKS 140 #undef SANITIZER_CHECK 141 }; 142 143 /// Helper class with most of the code for saving a value for a 144 /// conditional expression cleanup. 145 struct DominatingLLVMValue { 146 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 147 148 /// Answer whether the given value needs extra work to be saved. 149 static bool needsSaving(llvm::Value *value) { 150 // If it's not an instruction, we don't need to save. 151 if (!isa<llvm::Instruction>(value)) return false; 152 153 // If it's an instruction in the entry block, we don't need to save. 154 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 155 return (block != &block->getParent()->getEntryBlock()); 156 } 157 158 static saved_type save(CodeGenFunction &CGF, llvm::Value *value); 159 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value); 160 }; 161 162 /// A partial specialization of DominatingValue for llvm::Values that 163 /// might be llvm::Instructions. 164 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 165 typedef T *type; 166 static type restore(CodeGenFunction &CGF, saved_type value) { 167 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 168 } 169 }; 170 171 /// A specialization of DominatingValue for Address. 172 template <> struct DominatingValue<Address> { 173 typedef Address type; 174 175 struct saved_type { 176 DominatingLLVMValue::saved_type SavedValue; 177 CharUnits Alignment; 178 }; 179 180 static bool needsSaving(type value) { 181 return DominatingLLVMValue::needsSaving(value.getPointer()); 182 } 183 static saved_type save(CodeGenFunction &CGF, type value) { 184 return { DominatingLLVMValue::save(CGF, value.getPointer()), 185 value.getAlignment() }; 186 } 187 static type restore(CodeGenFunction &CGF, saved_type value) { 188 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue), 189 value.Alignment); 190 } 191 }; 192 193 /// A specialization of DominatingValue for RValue. 194 template <> struct DominatingValue<RValue> { 195 typedef RValue type; 196 class saved_type { 197 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 198 AggregateAddress, ComplexAddress }; 199 200 llvm::Value *Value; 201 unsigned K : 3; 202 unsigned Align : 29; 203 saved_type(llvm::Value *v, Kind k, unsigned a = 0) 204 : Value(v), K(k), Align(a) {} 205 206 public: 207 static bool needsSaving(RValue value); 208 static saved_type save(CodeGenFunction &CGF, RValue value); 209 RValue restore(CodeGenFunction &CGF); 210 211 // implementations in CGCleanup.cpp 212 }; 213 214 static bool needsSaving(type value) { 215 return saved_type::needsSaving(value); 216 } 217 static saved_type save(CodeGenFunction &CGF, type value) { 218 return saved_type::save(CGF, value); 219 } 220 static type restore(CodeGenFunction &CGF, saved_type value) { 221 return value.restore(CGF); 222 } 223 }; 224 225 /// CodeGenFunction - This class organizes the per-function state that is used 226 /// while generating LLVM code. 227 class CodeGenFunction : public CodeGenTypeCache { 228 CodeGenFunction(const CodeGenFunction &) = delete; 229 void operator=(const CodeGenFunction &) = delete; 230 231 friend class CGCXXABI; 232 public: 233 /// A jump destination is an abstract label, branching to which may 234 /// require a jump out through normal cleanups. 235 struct JumpDest { 236 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {} 237 JumpDest(llvm::BasicBlock *Block, 238 EHScopeStack::stable_iterator Depth, 239 unsigned Index) 240 : Block(Block), ScopeDepth(Depth), Index(Index) {} 241 242 bool isValid() const { return Block != nullptr; } 243 llvm::BasicBlock *getBlock() const { return Block; } 244 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 245 unsigned getDestIndex() const { return Index; } 246 247 // This should be used cautiously. 248 void setScopeDepth(EHScopeStack::stable_iterator depth) { 249 ScopeDepth = depth; 250 } 251 252 private: 253 llvm::BasicBlock *Block; 254 EHScopeStack::stable_iterator ScopeDepth; 255 unsigned Index; 256 }; 257 258 CodeGenModule &CGM; // Per-module state. 259 const TargetInfo &Target; 260 261 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 262 LoopInfoStack LoopStack; 263 CGBuilderTy Builder; 264 265 // Stores variables for which we can't generate correct lifetime markers 266 // because of jumps. 267 VarBypassDetector Bypasses; 268 269 // CodeGen lambda for loops and support for ordered clause 270 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &, 271 JumpDest)> 272 CodeGenLoopTy; 273 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation, 274 const unsigned, const bool)> 275 CodeGenOrderedTy; 276 277 // Codegen lambda for loop bounds in worksharing loop constructs 278 typedef llvm::function_ref<std::pair<LValue, LValue>( 279 CodeGenFunction &, const OMPExecutableDirective &S)> 280 CodeGenLoopBoundsTy; 281 282 // Codegen lambda for loop bounds in dispatch-based loop implementation 283 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>( 284 CodeGenFunction &, const OMPExecutableDirective &S, Address LB, 285 Address UB)> 286 CodeGenDispatchBoundsTy; 287 288 /// CGBuilder insert helper. This function is called after an 289 /// instruction is created using Builder. 290 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, 291 llvm::BasicBlock *BB, 292 llvm::BasicBlock::iterator InsertPt) const; 293 294 /// CurFuncDecl - Holds the Decl for the current outermost 295 /// non-closure context. 296 const Decl *CurFuncDecl; 297 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 298 const Decl *CurCodeDecl; 299 const CGFunctionInfo *CurFnInfo; 300 QualType FnRetTy; 301 llvm::Function *CurFn = nullptr; 302 303 // Holds coroutine data if the current function is a coroutine. We use a 304 // wrapper to manage its lifetime, so that we don't have to define CGCoroData 305 // in this header. 306 struct CGCoroInfo { 307 std::unique_ptr<CGCoroData> Data; 308 CGCoroInfo(); 309 ~CGCoroInfo(); 310 }; 311 CGCoroInfo CurCoro; 312 313 bool isCoroutine() const { 314 return CurCoro.Data != nullptr; 315 } 316 317 /// CurGD - The GlobalDecl for the current function being compiled. 318 GlobalDecl CurGD; 319 320 /// PrologueCleanupDepth - The cleanup depth enclosing all the 321 /// cleanups associated with the parameters. 322 EHScopeStack::stable_iterator PrologueCleanupDepth; 323 324 /// ReturnBlock - Unified return block. 325 JumpDest ReturnBlock; 326 327 /// ReturnValue - The temporary alloca to hold the return 328 /// value. This is invalid iff the function has no return value. 329 Address ReturnValue = Address::invalid(); 330 331 /// ReturnValuePointer - The temporary alloca to hold a pointer to sret. 332 /// This is invalid if sret is not in use. 333 Address ReturnValuePointer = Address::invalid(); 334 335 /// Return true if a label was seen in the current scope. 336 bool hasLabelBeenSeenInCurrentScope() const { 337 if (CurLexicalScope) 338 return CurLexicalScope->hasLabels(); 339 return !LabelMap.empty(); 340 } 341 342 /// AllocaInsertPoint - This is an instruction in the entry block before which 343 /// we prefer to insert allocas. 344 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 345 346 /// API for captured statement code generation. 347 class CGCapturedStmtInfo { 348 public: 349 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default) 350 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {} 351 explicit CGCapturedStmtInfo(const CapturedStmt &S, 352 CapturedRegionKind K = CR_Default) 353 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) { 354 355 RecordDecl::field_iterator Field = 356 S.getCapturedRecordDecl()->field_begin(); 357 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 358 E = S.capture_end(); 359 I != E; ++I, ++Field) { 360 if (I->capturesThis()) 361 CXXThisFieldDecl = *Field; 362 else if (I->capturesVariable()) 363 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field; 364 else if (I->capturesVariableByCopy()) 365 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field; 366 } 367 } 368 369 virtual ~CGCapturedStmtInfo(); 370 371 CapturedRegionKind getKind() const { return Kind; } 372 373 virtual void setContextValue(llvm::Value *V) { ThisValue = V; } 374 // Retrieve the value of the context parameter. 375 virtual llvm::Value *getContextValue() const { return ThisValue; } 376 377 /// Lookup the captured field decl for a variable. 378 virtual const FieldDecl *lookup(const VarDecl *VD) const { 379 return CaptureFields.lookup(VD->getCanonicalDecl()); 380 } 381 382 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; } 383 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 384 385 static bool classof(const CGCapturedStmtInfo *) { 386 return true; 387 } 388 389 /// Emit the captured statement body. 390 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) { 391 CGF.incrementProfileCounter(S); 392 CGF.EmitStmt(S); 393 } 394 395 /// Get the name of the capture helper. 396 virtual StringRef getHelperName() const { return "__captured_stmt"; } 397 398 private: 399 /// The kind of captured statement being generated. 400 CapturedRegionKind Kind; 401 402 /// Keep the map between VarDecl and FieldDecl. 403 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 404 405 /// The base address of the captured record, passed in as the first 406 /// argument of the parallel region function. 407 llvm::Value *ThisValue; 408 409 /// Captured 'this' type. 410 FieldDecl *CXXThisFieldDecl; 411 }; 412 CGCapturedStmtInfo *CapturedStmtInfo = nullptr; 413 414 /// RAII for correct setting/restoring of CapturedStmtInfo. 415 class CGCapturedStmtRAII { 416 private: 417 CodeGenFunction &CGF; 418 CGCapturedStmtInfo *PrevCapturedStmtInfo; 419 public: 420 CGCapturedStmtRAII(CodeGenFunction &CGF, 421 CGCapturedStmtInfo *NewCapturedStmtInfo) 422 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) { 423 CGF.CapturedStmtInfo = NewCapturedStmtInfo; 424 } 425 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; } 426 }; 427 428 /// An abstract representation of regular/ObjC call/message targets. 429 class AbstractCallee { 430 /// The function declaration of the callee. 431 const Decl *CalleeDecl; 432 433 public: 434 AbstractCallee() : CalleeDecl(nullptr) {} 435 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {} 436 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {} 437 bool hasFunctionDecl() const { 438 return dyn_cast_or_null<FunctionDecl>(CalleeDecl); 439 } 440 const Decl *getDecl() const { return CalleeDecl; } 441 unsigned getNumParams() const { 442 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) 443 return FD->getNumParams(); 444 return cast<ObjCMethodDecl>(CalleeDecl)->param_size(); 445 } 446 const ParmVarDecl *getParamDecl(unsigned I) const { 447 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) 448 return FD->getParamDecl(I); 449 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I); 450 } 451 }; 452 453 /// Sanitizers enabled for this function. 454 SanitizerSet SanOpts; 455 456 /// True if CodeGen currently emits code implementing sanitizer checks. 457 bool IsSanitizerScope = false; 458 459 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope. 460 class SanitizerScope { 461 CodeGenFunction *CGF; 462 public: 463 SanitizerScope(CodeGenFunction *CGF); 464 ~SanitizerScope(); 465 }; 466 467 /// In C++, whether we are code generating a thunk. This controls whether we 468 /// should emit cleanups. 469 bool CurFuncIsThunk = false; 470 471 /// In ARC, whether we should autorelease the return value. 472 bool AutoreleaseResult = false; 473 474 /// Whether we processed a Microsoft-style asm block during CodeGen. These can 475 /// potentially set the return value. 476 bool SawAsmBlock = false; 477 478 const NamedDecl *CurSEHParent = nullptr; 479 480 /// True if the current function is an outlined SEH helper. This can be a 481 /// finally block or filter expression. 482 bool IsOutlinedSEHHelper = false; 483 484 /// True if CodeGen currently emits code inside presereved access index 485 /// region. 486 bool IsInPreservedAIRegion = false; 487 488 const CodeGen::CGBlockInfo *BlockInfo = nullptr; 489 llvm::Value *BlockPointer = nullptr; 490 491 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 492 FieldDecl *LambdaThisCaptureField = nullptr; 493 494 /// A mapping from NRVO variables to the flags used to indicate 495 /// when the NRVO has been applied to this variable. 496 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 497 498 EHScopeStack EHStack; 499 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 500 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack; 501 502 llvm::Instruction *CurrentFuncletPad = nullptr; 503 504 class CallLifetimeEnd final : public EHScopeStack::Cleanup { 505 llvm::Value *Addr; 506 llvm::Value *Size; 507 508 public: 509 CallLifetimeEnd(Address addr, llvm::Value *size) 510 : Addr(addr.getPointer()), Size(size) {} 511 512 void Emit(CodeGenFunction &CGF, Flags flags) override { 513 CGF.EmitLifetimeEnd(Size, Addr); 514 } 515 }; 516 517 /// Header for data within LifetimeExtendedCleanupStack. 518 struct LifetimeExtendedCleanupHeader { 519 /// The size of the following cleanup object. 520 unsigned Size; 521 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 522 unsigned Kind : 31; 523 /// Whether this is a conditional cleanup. 524 unsigned IsConditional : 1; 525 526 size_t getSize() const { return Size; } 527 CleanupKind getKind() const { return (CleanupKind)Kind; } 528 bool isConditional() const { return IsConditional; } 529 }; 530 531 /// i32s containing the indexes of the cleanup destinations. 532 Address NormalCleanupDest = Address::invalid(); 533 534 unsigned NextCleanupDestIndex = 1; 535 536 /// FirstBlockInfo - The head of a singly-linked-list of block layouts. 537 CGBlockInfo *FirstBlockInfo = nullptr; 538 539 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 540 llvm::BasicBlock *EHResumeBlock = nullptr; 541 542 /// The exception slot. All landing pads write the current exception pointer 543 /// into this alloca. 544 llvm::Value *ExceptionSlot = nullptr; 545 546 /// The selector slot. Under the MandatoryCleanup model, all landing pads 547 /// write the current selector value into this alloca. 548 llvm::AllocaInst *EHSelectorSlot = nullptr; 549 550 /// A stack of exception code slots. Entering an __except block pushes a slot 551 /// on the stack and leaving pops one. The __exception_code() intrinsic loads 552 /// a value from the top of the stack. 553 SmallVector<Address, 1> SEHCodeSlotStack; 554 555 /// Value returned by __exception_info intrinsic. 556 llvm::Value *SEHInfo = nullptr; 557 558 /// Emits a landing pad for the current EH stack. 559 llvm::BasicBlock *EmitLandingPad(); 560 561 llvm::BasicBlock *getInvokeDestImpl(); 562 563 template <class T> 564 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 565 return DominatingValue<T>::save(*this, value); 566 } 567 568 public: 569 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 570 /// rethrows. 571 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 572 573 /// A class controlling the emission of a finally block. 574 class FinallyInfo { 575 /// Where the catchall's edge through the cleanup should go. 576 JumpDest RethrowDest; 577 578 /// A function to call to enter the catch. 579 llvm::FunctionCallee BeginCatchFn; 580 581 /// An i1 variable indicating whether or not the @finally is 582 /// running for an exception. 583 llvm::AllocaInst *ForEHVar; 584 585 /// An i8* variable into which the exception pointer to rethrow 586 /// has been saved. 587 llvm::AllocaInst *SavedExnVar; 588 589 public: 590 void enter(CodeGenFunction &CGF, const Stmt *Finally, 591 llvm::FunctionCallee beginCatchFn, 592 llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn); 593 void exit(CodeGenFunction &CGF); 594 }; 595 596 /// Returns true inside SEH __try blocks. 597 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); } 598 599 /// Returns true while emitting a cleanuppad. 600 bool isCleanupPadScope() const { 601 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad); 602 } 603 604 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 605 /// current full-expression. Safe against the possibility that 606 /// we're currently inside a conditionally-evaluated expression. 607 template <class T, class... As> 608 void pushFullExprCleanup(CleanupKind kind, As... A) { 609 // If we're not in a conditional branch, or if none of the 610 // arguments requires saving, then use the unconditional cleanup. 611 if (!isInConditionalBranch()) 612 return EHStack.pushCleanup<T>(kind, A...); 613 614 // Stash values in a tuple so we can guarantee the order of saves. 615 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple; 616 SavedTuple Saved{saveValueInCond(A)...}; 617 618 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType; 619 EHStack.pushCleanupTuple<CleanupType>(kind, Saved); 620 initFullExprCleanup(); 621 } 622 623 /// Queue a cleanup to be pushed after finishing the current 624 /// full-expression. 625 template <class T, class... As> 626 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) { 627 if (!isInConditionalBranch()) 628 return pushCleanupAfterFullExprImpl<T>(Kind, Address::invalid(), A...); 629 630 Address ActiveFlag = createCleanupActiveFlag(); 631 assert(!DominatingValue<Address>::needsSaving(ActiveFlag) && 632 "cleanup active flag should never need saving"); 633 634 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple; 635 SavedTuple Saved{saveValueInCond(A)...}; 636 637 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType; 638 pushCleanupAfterFullExprImpl<CleanupType>(Kind, ActiveFlag, Saved); 639 } 640 641 template <class T, class... As> 642 void pushCleanupAfterFullExprImpl(CleanupKind Kind, Address ActiveFlag, 643 As... A) { 644 LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind, 645 ActiveFlag.isValid()}; 646 647 size_t OldSize = LifetimeExtendedCleanupStack.size(); 648 LifetimeExtendedCleanupStack.resize( 649 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size + 650 (Header.IsConditional ? sizeof(ActiveFlag) : 0)); 651 652 static_assert(sizeof(Header) % alignof(T) == 0, 653 "Cleanup will be allocated on misaligned address"); 654 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 655 new (Buffer) LifetimeExtendedCleanupHeader(Header); 656 new (Buffer + sizeof(Header)) T(A...); 657 if (Header.IsConditional) 658 new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag); 659 } 660 661 /// Set up the last cleanup that was pushed as a conditional 662 /// full-expression cleanup. 663 void initFullExprCleanup() { 664 initFullExprCleanupWithFlag(createCleanupActiveFlag()); 665 } 666 667 void initFullExprCleanupWithFlag(Address ActiveFlag); 668 Address createCleanupActiveFlag(); 669 670 /// PushDestructorCleanup - Push a cleanup to call the 671 /// complete-object destructor of an object of the given type at the 672 /// given address. Does nothing if T is not a C++ class type with a 673 /// non-trivial destructor. 674 void PushDestructorCleanup(QualType T, Address Addr); 675 676 /// PushDestructorCleanup - Push a cleanup to call the 677 /// complete-object variant of the given destructor on the object at 678 /// the given address. 679 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T, 680 Address Addr); 681 682 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 683 /// process all branch fixups. 684 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 685 686 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 687 /// The block cannot be reactivated. Pops it if it's the top of the 688 /// stack. 689 /// 690 /// \param DominatingIP - An instruction which is known to 691 /// dominate the current IP (if set) and which lies along 692 /// all paths of execution between the current IP and the 693 /// the point at which the cleanup comes into scope. 694 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 695 llvm::Instruction *DominatingIP); 696 697 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 698 /// Cannot be used to resurrect a deactivated cleanup. 699 /// 700 /// \param DominatingIP - An instruction which is known to 701 /// dominate the current IP (if set) and which lies along 702 /// all paths of execution between the current IP and the 703 /// the point at which the cleanup comes into scope. 704 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 705 llvm::Instruction *DominatingIP); 706 707 /// Enters a new scope for capturing cleanups, all of which 708 /// will be executed once the scope is exited. 709 class RunCleanupsScope { 710 EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth; 711 size_t LifetimeExtendedCleanupStackSize; 712 bool OldDidCallStackSave; 713 protected: 714 bool PerformCleanup; 715 private: 716 717 RunCleanupsScope(const RunCleanupsScope &) = delete; 718 void operator=(const RunCleanupsScope &) = delete; 719 720 protected: 721 CodeGenFunction& CGF; 722 723 public: 724 /// Enter a new cleanup scope. 725 explicit RunCleanupsScope(CodeGenFunction &CGF) 726 : PerformCleanup(true), CGF(CGF) 727 { 728 CleanupStackDepth = CGF.EHStack.stable_begin(); 729 LifetimeExtendedCleanupStackSize = 730 CGF.LifetimeExtendedCleanupStack.size(); 731 OldDidCallStackSave = CGF.DidCallStackSave; 732 CGF.DidCallStackSave = false; 733 OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth; 734 CGF.CurrentCleanupScopeDepth = CleanupStackDepth; 735 } 736 737 /// Exit this cleanup scope, emitting any accumulated cleanups. 738 ~RunCleanupsScope() { 739 if (PerformCleanup) 740 ForceCleanup(); 741 } 742 743 /// Determine whether this scope requires any cleanups. 744 bool requiresCleanups() const { 745 return CGF.EHStack.stable_begin() != CleanupStackDepth; 746 } 747 748 /// Force the emission of cleanups now, instead of waiting 749 /// until this object is destroyed. 750 /// \param ValuesToReload - A list of values that need to be available at 751 /// the insertion point after cleanup emission. If cleanup emission created 752 /// a shared cleanup block, these value pointers will be rewritten. 753 /// Otherwise, they not will be modified. 754 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) { 755 assert(PerformCleanup && "Already forced cleanup"); 756 CGF.DidCallStackSave = OldDidCallStackSave; 757 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize, 758 ValuesToReload); 759 PerformCleanup = false; 760 CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth; 761 } 762 }; 763 764 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently. 765 EHScopeStack::stable_iterator CurrentCleanupScopeDepth = 766 EHScopeStack::stable_end(); 767 768 class LexicalScope : public RunCleanupsScope { 769 SourceRange Range; 770 SmallVector<const LabelDecl*, 4> Labels; 771 LexicalScope *ParentScope; 772 773 LexicalScope(const LexicalScope &) = delete; 774 void operator=(const LexicalScope &) = delete; 775 776 public: 777 /// Enter a new cleanup scope. 778 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 779 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 780 CGF.CurLexicalScope = this; 781 if (CGDebugInfo *DI = CGF.getDebugInfo()) 782 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 783 } 784 785 void addLabel(const LabelDecl *label) { 786 assert(PerformCleanup && "adding label to dead scope?"); 787 Labels.push_back(label); 788 } 789 790 /// Exit this cleanup scope, emitting any accumulated 791 /// cleanups. 792 ~LexicalScope() { 793 if (CGDebugInfo *DI = CGF.getDebugInfo()) 794 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 795 796 // If we should perform a cleanup, force them now. Note that 797 // this ends the cleanup scope before rescoping any labels. 798 if (PerformCleanup) { 799 ApplyDebugLocation DL(CGF, Range.getEnd()); 800 ForceCleanup(); 801 } 802 } 803 804 /// Force the emission of cleanups now, instead of waiting 805 /// until this object is destroyed. 806 void ForceCleanup() { 807 CGF.CurLexicalScope = ParentScope; 808 RunCleanupsScope::ForceCleanup(); 809 810 if (!Labels.empty()) 811 rescopeLabels(); 812 } 813 814 bool hasLabels() const { 815 return !Labels.empty(); 816 } 817 818 void rescopeLabels(); 819 }; 820 821 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy; 822 823 /// The class used to assign some variables some temporarily addresses. 824 class OMPMapVars { 825 DeclMapTy SavedLocals; 826 DeclMapTy SavedTempAddresses; 827 OMPMapVars(const OMPMapVars &) = delete; 828 void operator=(const OMPMapVars &) = delete; 829 830 public: 831 explicit OMPMapVars() = default; 832 ~OMPMapVars() { 833 assert(SavedLocals.empty() && "Did not restored original addresses."); 834 }; 835 836 /// Sets the address of the variable \p LocalVD to be \p TempAddr in 837 /// function \p CGF. 838 /// \return true if at least one variable was set already, false otherwise. 839 bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD, 840 Address TempAddr) { 841 LocalVD = LocalVD->getCanonicalDecl(); 842 // Only save it once. 843 if (SavedLocals.count(LocalVD)) return false; 844 845 // Copy the existing local entry to SavedLocals. 846 auto it = CGF.LocalDeclMap.find(LocalVD); 847 if (it != CGF.LocalDeclMap.end()) 848 SavedLocals.try_emplace(LocalVD, it->second); 849 else 850 SavedLocals.try_emplace(LocalVD, Address::invalid()); 851 852 // Generate the private entry. 853 QualType VarTy = LocalVD->getType(); 854 if (VarTy->isReferenceType()) { 855 Address Temp = CGF.CreateMemTemp(VarTy); 856 CGF.Builder.CreateStore(TempAddr.getPointer(), Temp); 857 TempAddr = Temp; 858 } 859 SavedTempAddresses.try_emplace(LocalVD, TempAddr); 860 861 return true; 862 } 863 864 /// Applies new addresses to the list of the variables. 865 /// \return true if at least one variable is using new address, false 866 /// otherwise. 867 bool apply(CodeGenFunction &CGF) { 868 copyInto(SavedTempAddresses, CGF.LocalDeclMap); 869 SavedTempAddresses.clear(); 870 return !SavedLocals.empty(); 871 } 872 873 /// Restores original addresses of the variables. 874 void restore(CodeGenFunction &CGF) { 875 if (!SavedLocals.empty()) { 876 copyInto(SavedLocals, CGF.LocalDeclMap); 877 SavedLocals.clear(); 878 } 879 } 880 881 private: 882 /// Copy all the entries in the source map over the corresponding 883 /// entries in the destination, which must exist. 884 static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) { 885 for (auto &Pair : Src) { 886 if (!Pair.second.isValid()) { 887 Dest.erase(Pair.first); 888 continue; 889 } 890 891 auto I = Dest.find(Pair.first); 892 if (I != Dest.end()) 893 I->second = Pair.second; 894 else 895 Dest.insert(Pair); 896 } 897 } 898 }; 899 900 /// The scope used to remap some variables as private in the OpenMP loop body 901 /// (or other captured region emitted without outlining), and to restore old 902 /// vars back on exit. 903 class OMPPrivateScope : public RunCleanupsScope { 904 OMPMapVars MappedVars; 905 OMPPrivateScope(const OMPPrivateScope &) = delete; 906 void operator=(const OMPPrivateScope &) = delete; 907 908 public: 909 /// Enter a new OpenMP private scope. 910 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {} 911 912 /// Registers \p LocalVD variable as a private and apply \p PrivateGen 913 /// function for it to generate corresponding private variable. \p 914 /// PrivateGen returns an address of the generated private variable. 915 /// \return true if the variable is registered as private, false if it has 916 /// been privatized already. 917 bool addPrivate(const VarDecl *LocalVD, 918 const llvm::function_ref<Address()> PrivateGen) { 919 assert(PerformCleanup && "adding private to dead scope"); 920 return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen()); 921 } 922 923 /// Privatizes local variables previously registered as private. 924 /// Registration is separate from the actual privatization to allow 925 /// initializers use values of the original variables, not the private one. 926 /// This is important, for example, if the private variable is a class 927 /// variable initialized by a constructor that references other private 928 /// variables. But at initialization original variables must be used, not 929 /// private copies. 930 /// \return true if at least one variable was privatized, false otherwise. 931 bool Privatize() { return MappedVars.apply(CGF); } 932 933 void ForceCleanup() { 934 RunCleanupsScope::ForceCleanup(); 935 MappedVars.restore(CGF); 936 } 937 938 /// Exit scope - all the mapped variables are restored. 939 ~OMPPrivateScope() { 940 if (PerformCleanup) 941 ForceCleanup(); 942 } 943 944 /// Checks if the global variable is captured in current function. 945 bool isGlobalVarCaptured(const VarDecl *VD) const { 946 VD = VD->getCanonicalDecl(); 947 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0; 948 } 949 }; 950 951 /// Save/restore original map of previously emitted local vars in case when we 952 /// need to duplicate emission of the same code several times in the same 953 /// function for OpenMP code. 954 class OMPLocalDeclMapRAII { 955 CodeGenFunction &CGF; 956 DeclMapTy SavedMap; 957 958 public: 959 OMPLocalDeclMapRAII(CodeGenFunction &CGF) 960 : CGF(CGF), SavedMap(CGF.LocalDeclMap) {} 961 ~OMPLocalDeclMapRAII() { SavedMap.swap(CGF.LocalDeclMap); } 962 }; 963 964 /// Takes the old cleanup stack size and emits the cleanup blocks 965 /// that have been added. 966 void 967 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 968 std::initializer_list<llvm::Value **> ValuesToReload = {}); 969 970 /// Takes the old cleanup stack size and emits the cleanup blocks 971 /// that have been added, then adds all lifetime-extended cleanups from 972 /// the given position to the stack. 973 void 974 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 975 size_t OldLifetimeExtendedStackSize, 976 std::initializer_list<llvm::Value **> ValuesToReload = {}); 977 978 void ResolveBranchFixups(llvm::BasicBlock *Target); 979 980 /// The given basic block lies in the current EH scope, but may be a 981 /// target of a potentially scope-crossing jump; get a stable handle 982 /// to which we can perform this jump later. 983 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 984 return JumpDest(Target, 985 EHStack.getInnermostNormalCleanup(), 986 NextCleanupDestIndex++); 987 } 988 989 /// The given basic block lies in the current EH scope, but may be a 990 /// target of a potentially scope-crossing jump; get a stable handle 991 /// to which we can perform this jump later. 992 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 993 return getJumpDestInCurrentScope(createBasicBlock(Name)); 994 } 995 996 /// EmitBranchThroughCleanup - Emit a branch from the current insert 997 /// block through the normal cleanup handling code (if any) and then 998 /// on to \arg Dest. 999 void EmitBranchThroughCleanup(JumpDest Dest); 1000 1001 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 1002 /// specified destination obviously has no cleanups to run. 'false' is always 1003 /// a conservatively correct answer for this method. 1004 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 1005 1006 /// popCatchScope - Pops the catch scope at the top of the EHScope 1007 /// stack, emitting any required code (other than the catch handlers 1008 /// themselves). 1009 void popCatchScope(); 1010 1011 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 1012 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 1013 llvm::BasicBlock * 1014 getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope); 1015 1016 /// An object to manage conditionally-evaluated expressions. 1017 class ConditionalEvaluation { 1018 llvm::BasicBlock *StartBB; 1019 1020 public: 1021 ConditionalEvaluation(CodeGenFunction &CGF) 1022 : StartBB(CGF.Builder.GetInsertBlock()) {} 1023 1024 void begin(CodeGenFunction &CGF) { 1025 assert(CGF.OutermostConditional != this); 1026 if (!CGF.OutermostConditional) 1027 CGF.OutermostConditional = this; 1028 } 1029 1030 void end(CodeGenFunction &CGF) { 1031 assert(CGF.OutermostConditional != nullptr); 1032 if (CGF.OutermostConditional == this) 1033 CGF.OutermostConditional = nullptr; 1034 } 1035 1036 /// Returns a block which will be executed prior to each 1037 /// evaluation of the conditional code. 1038 llvm::BasicBlock *getStartingBlock() const { 1039 return StartBB; 1040 } 1041 }; 1042 1043 /// isInConditionalBranch - Return true if we're currently emitting 1044 /// one branch or the other of a conditional expression. 1045 bool isInConditionalBranch() const { return OutermostConditional != nullptr; } 1046 1047 void setBeforeOutermostConditional(llvm::Value *value, Address addr) { 1048 assert(isInConditionalBranch()); 1049 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 1050 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back()); 1051 store->setAlignment(addr.getAlignment().getAsAlign()); 1052 } 1053 1054 /// An RAII object to record that we're evaluating a statement 1055 /// expression. 1056 class StmtExprEvaluation { 1057 CodeGenFunction &CGF; 1058 1059 /// We have to save the outermost conditional: cleanups in a 1060 /// statement expression aren't conditional just because the 1061 /// StmtExpr is. 1062 ConditionalEvaluation *SavedOutermostConditional; 1063 1064 public: 1065 StmtExprEvaluation(CodeGenFunction &CGF) 1066 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 1067 CGF.OutermostConditional = nullptr; 1068 } 1069 1070 ~StmtExprEvaluation() { 1071 CGF.OutermostConditional = SavedOutermostConditional; 1072 CGF.EnsureInsertPoint(); 1073 } 1074 }; 1075 1076 /// An object which temporarily prevents a value from being 1077 /// destroyed by aggressive peephole optimizations that assume that 1078 /// all uses of a value have been realized in the IR. 1079 class PeepholeProtection { 1080 llvm::Instruction *Inst; 1081 friend class CodeGenFunction; 1082 1083 public: 1084 PeepholeProtection() : Inst(nullptr) {} 1085 }; 1086 1087 /// A non-RAII class containing all the information about a bound 1088 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 1089 /// this which makes individual mappings very simple; using this 1090 /// class directly is useful when you have a variable number of 1091 /// opaque values or don't want the RAII functionality for some 1092 /// reason. 1093 class OpaqueValueMappingData { 1094 const OpaqueValueExpr *OpaqueValue; 1095 bool BoundLValue; 1096 CodeGenFunction::PeepholeProtection Protection; 1097 1098 OpaqueValueMappingData(const OpaqueValueExpr *ov, 1099 bool boundLValue) 1100 : OpaqueValue(ov), BoundLValue(boundLValue) {} 1101 public: 1102 OpaqueValueMappingData() : OpaqueValue(nullptr) {} 1103 1104 static bool shouldBindAsLValue(const Expr *expr) { 1105 // gl-values should be bound as l-values for obvious reasons. 1106 // Records should be bound as l-values because IR generation 1107 // always keeps them in memory. Expressions of function type 1108 // act exactly like l-values but are formally required to be 1109 // r-values in C. 1110 return expr->isGLValue() || 1111 expr->getType()->isFunctionType() || 1112 hasAggregateEvaluationKind(expr->getType()); 1113 } 1114 1115 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1116 const OpaqueValueExpr *ov, 1117 const Expr *e) { 1118 if (shouldBindAsLValue(ov)) 1119 return bind(CGF, ov, CGF.EmitLValue(e)); 1120 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 1121 } 1122 1123 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1124 const OpaqueValueExpr *ov, 1125 const LValue &lv) { 1126 assert(shouldBindAsLValue(ov)); 1127 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 1128 return OpaqueValueMappingData(ov, true); 1129 } 1130 1131 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1132 const OpaqueValueExpr *ov, 1133 const RValue &rv) { 1134 assert(!shouldBindAsLValue(ov)); 1135 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 1136 1137 OpaqueValueMappingData data(ov, false); 1138 1139 // Work around an extremely aggressive peephole optimization in 1140 // EmitScalarConversion which assumes that all other uses of a 1141 // value are extant. 1142 data.Protection = CGF.protectFromPeepholes(rv); 1143 1144 return data; 1145 } 1146 1147 bool isValid() const { return OpaqueValue != nullptr; } 1148 void clear() { OpaqueValue = nullptr; } 1149 1150 void unbind(CodeGenFunction &CGF) { 1151 assert(OpaqueValue && "no data to unbind!"); 1152 1153 if (BoundLValue) { 1154 CGF.OpaqueLValues.erase(OpaqueValue); 1155 } else { 1156 CGF.OpaqueRValues.erase(OpaqueValue); 1157 CGF.unprotectFromPeepholes(Protection); 1158 } 1159 } 1160 }; 1161 1162 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 1163 class OpaqueValueMapping { 1164 CodeGenFunction &CGF; 1165 OpaqueValueMappingData Data; 1166 1167 public: 1168 static bool shouldBindAsLValue(const Expr *expr) { 1169 return OpaqueValueMappingData::shouldBindAsLValue(expr); 1170 } 1171 1172 /// Build the opaque value mapping for the given conditional 1173 /// operator if it's the GNU ?: extension. This is a common 1174 /// enough pattern that the convenience operator is really 1175 /// helpful. 1176 /// 1177 OpaqueValueMapping(CodeGenFunction &CGF, 1178 const AbstractConditionalOperator *op) : CGF(CGF) { 1179 if (isa<ConditionalOperator>(op)) 1180 // Leave Data empty. 1181 return; 1182 1183 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 1184 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 1185 e->getCommon()); 1186 } 1187 1188 /// Build the opaque value mapping for an OpaqueValueExpr whose source 1189 /// expression is set to the expression the OVE represents. 1190 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV) 1191 : CGF(CGF) { 1192 if (OV) { 1193 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used " 1194 "for OVE with no source expression"); 1195 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr()); 1196 } 1197 } 1198 1199 OpaqueValueMapping(CodeGenFunction &CGF, 1200 const OpaqueValueExpr *opaqueValue, 1201 LValue lvalue) 1202 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 1203 } 1204 1205 OpaqueValueMapping(CodeGenFunction &CGF, 1206 const OpaqueValueExpr *opaqueValue, 1207 RValue rvalue) 1208 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 1209 } 1210 1211 void pop() { 1212 Data.unbind(CGF); 1213 Data.clear(); 1214 } 1215 1216 ~OpaqueValueMapping() { 1217 if (Data.isValid()) Data.unbind(CGF); 1218 } 1219 }; 1220 1221 private: 1222 CGDebugInfo *DebugInfo; 1223 /// Used to create unique names for artificial VLA size debug info variables. 1224 unsigned VLAExprCounter = 0; 1225 bool DisableDebugInfo = false; 1226 1227 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 1228 /// calling llvm.stacksave for multiple VLAs in the same scope. 1229 bool DidCallStackSave = false; 1230 1231 /// IndirectBranch - The first time an indirect goto is seen we create a block 1232 /// with an indirect branch. Every time we see the address of a label taken, 1233 /// we add the label to the indirect goto. Every subsequent indirect goto is 1234 /// codegen'd as a jump to the IndirectBranch's basic block. 1235 llvm::IndirectBrInst *IndirectBranch = nullptr; 1236 1237 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 1238 /// decls. 1239 DeclMapTy LocalDeclMap; 1240 1241 // Keep track of the cleanups for callee-destructed parameters pushed to the 1242 // cleanup stack so that they can be deactivated later. 1243 llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator> 1244 CalleeDestructedParamCleanups; 1245 1246 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this 1247 /// will contain a mapping from said ParmVarDecl to its implicit "object_size" 1248 /// parameter. 1249 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2> 1250 SizeArguments; 1251 1252 /// Track escaped local variables with auto storage. Used during SEH 1253 /// outlining to produce a call to llvm.localescape. 1254 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals; 1255 1256 /// LabelMap - This keeps track of the LLVM basic block for each C label. 1257 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 1258 1259 // BreakContinueStack - This keeps track of where break and continue 1260 // statements should jump to. 1261 struct BreakContinue { 1262 BreakContinue(JumpDest Break, JumpDest Continue) 1263 : BreakBlock(Break), ContinueBlock(Continue) {} 1264 1265 JumpDest BreakBlock; 1266 JumpDest ContinueBlock; 1267 }; 1268 SmallVector<BreakContinue, 8> BreakContinueStack; 1269 1270 /// Handles cancellation exit points in OpenMP-related constructs. 1271 class OpenMPCancelExitStack { 1272 /// Tracks cancellation exit point and join point for cancel-related exit 1273 /// and normal exit. 1274 struct CancelExit { 1275 CancelExit() = default; 1276 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock, 1277 JumpDest ContBlock) 1278 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {} 1279 OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown; 1280 /// true if the exit block has been emitted already by the special 1281 /// emitExit() call, false if the default codegen is used. 1282 bool HasBeenEmitted = false; 1283 JumpDest ExitBlock; 1284 JumpDest ContBlock; 1285 }; 1286 1287 SmallVector<CancelExit, 8> Stack; 1288 1289 public: 1290 OpenMPCancelExitStack() : Stack(1) {} 1291 ~OpenMPCancelExitStack() = default; 1292 /// Fetches the exit block for the current OpenMP construct. 1293 JumpDest getExitBlock() const { return Stack.back().ExitBlock; } 1294 /// Emits exit block with special codegen procedure specific for the related 1295 /// OpenMP construct + emits code for normal construct cleanup. 1296 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 1297 const llvm::function_ref<void(CodeGenFunction &)> CodeGen) { 1298 if (Stack.back().Kind == Kind && getExitBlock().isValid()) { 1299 assert(CGF.getOMPCancelDestination(Kind).isValid()); 1300 assert(CGF.HaveInsertPoint()); 1301 assert(!Stack.back().HasBeenEmitted); 1302 auto IP = CGF.Builder.saveAndClearIP(); 1303 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1304 CodeGen(CGF); 1305 CGF.EmitBranch(Stack.back().ContBlock.getBlock()); 1306 CGF.Builder.restoreIP(IP); 1307 Stack.back().HasBeenEmitted = true; 1308 } 1309 CodeGen(CGF); 1310 } 1311 /// Enter the cancel supporting \a Kind construct. 1312 /// \param Kind OpenMP directive that supports cancel constructs. 1313 /// \param HasCancel true, if the construct has inner cancel directive, 1314 /// false otherwise. 1315 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) { 1316 Stack.push_back({Kind, 1317 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit") 1318 : JumpDest(), 1319 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont") 1320 : JumpDest()}); 1321 } 1322 /// Emits default exit point for the cancel construct (if the special one 1323 /// has not be used) + join point for cancel/normal exits. 1324 void exit(CodeGenFunction &CGF) { 1325 if (getExitBlock().isValid()) { 1326 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid()); 1327 bool HaveIP = CGF.HaveInsertPoint(); 1328 if (!Stack.back().HasBeenEmitted) { 1329 if (HaveIP) 1330 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1331 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1332 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1333 } 1334 CGF.EmitBlock(Stack.back().ContBlock.getBlock()); 1335 if (!HaveIP) { 1336 CGF.Builder.CreateUnreachable(); 1337 CGF.Builder.ClearInsertionPoint(); 1338 } 1339 } 1340 Stack.pop_back(); 1341 } 1342 }; 1343 OpenMPCancelExitStack OMPCancelStack; 1344 1345 CodeGenPGO PGO; 1346 1347 /// Calculate branch weights appropriate for PGO data 1348 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount); 1349 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights); 1350 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond, 1351 uint64_t LoopCount); 1352 1353 public: 1354 /// Increment the profiler's counter for the given statement by \p StepV. 1355 /// If \p StepV is null, the default increment is 1. 1356 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) { 1357 if (CGM.getCodeGenOpts().hasProfileClangInstr()) 1358 PGO.emitCounterIncrement(Builder, S, StepV); 1359 PGO.setCurrentStmt(S); 1360 } 1361 1362 /// Get the profiler's count for the given statement. 1363 uint64_t getProfileCount(const Stmt *S) { 1364 Optional<uint64_t> Count = PGO.getStmtCount(S); 1365 if (!Count.hasValue()) 1366 return 0; 1367 return *Count; 1368 } 1369 1370 /// Set the profiler's current count. 1371 void setCurrentProfileCount(uint64_t Count) { 1372 PGO.setCurrentRegionCount(Count); 1373 } 1374 1375 /// Get the profiler's current count. This is generally the count for the most 1376 /// recently incremented counter. 1377 uint64_t getCurrentProfileCount() { 1378 return PGO.getCurrentRegionCount(); 1379 } 1380 1381 private: 1382 1383 /// SwitchInsn - This is nearest current switch instruction. It is null if 1384 /// current context is not in a switch. 1385 llvm::SwitchInst *SwitchInsn = nullptr; 1386 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 1387 SmallVector<uint64_t, 16> *SwitchWeights = nullptr; 1388 1389 /// CaseRangeBlock - This block holds if condition check for last case 1390 /// statement range in current switch instruction. 1391 llvm::BasicBlock *CaseRangeBlock = nullptr; 1392 1393 /// OpaqueLValues - Keeps track of the current set of opaque value 1394 /// expressions. 1395 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 1396 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 1397 1398 // VLASizeMap - This keeps track of the associated size for each VLA type. 1399 // We track this by the size expression rather than the type itself because 1400 // in certain situations, like a const qualifier applied to an VLA typedef, 1401 // multiple VLA types can share the same size expression. 1402 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 1403 // enter/leave scopes. 1404 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 1405 1406 /// A block containing a single 'unreachable' instruction. Created 1407 /// lazily by getUnreachableBlock(). 1408 llvm::BasicBlock *UnreachableBlock = nullptr; 1409 1410 /// Counts of the number return expressions in the function. 1411 unsigned NumReturnExprs = 0; 1412 1413 /// Count the number of simple (constant) return expressions in the function. 1414 unsigned NumSimpleReturnExprs = 0; 1415 1416 /// The last regular (non-return) debug location (breakpoint) in the function. 1417 SourceLocation LastStopPoint; 1418 1419 public: 1420 /// Source location information about the default argument or member 1421 /// initializer expression we're evaluating, if any. 1422 CurrentSourceLocExprScope CurSourceLocExprScope; 1423 using SourceLocExprScopeGuard = 1424 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 1425 1426 /// A scope within which we are constructing the fields of an object which 1427 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 1428 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 1429 class FieldConstructionScope { 1430 public: 1431 FieldConstructionScope(CodeGenFunction &CGF, Address This) 1432 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 1433 CGF.CXXDefaultInitExprThis = This; 1434 } 1435 ~FieldConstructionScope() { 1436 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 1437 } 1438 1439 private: 1440 CodeGenFunction &CGF; 1441 Address OldCXXDefaultInitExprThis; 1442 }; 1443 1444 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 1445 /// is overridden to be the object under construction. 1446 class CXXDefaultInitExprScope { 1447 public: 1448 CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E) 1449 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue), 1450 OldCXXThisAlignment(CGF.CXXThisAlignment), 1451 SourceLocScope(E, CGF.CurSourceLocExprScope) { 1452 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer(); 1453 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment(); 1454 } 1455 ~CXXDefaultInitExprScope() { 1456 CGF.CXXThisValue = OldCXXThisValue; 1457 CGF.CXXThisAlignment = OldCXXThisAlignment; 1458 } 1459 1460 public: 1461 CodeGenFunction &CGF; 1462 llvm::Value *OldCXXThisValue; 1463 CharUnits OldCXXThisAlignment; 1464 SourceLocExprScopeGuard SourceLocScope; 1465 }; 1466 1467 struct CXXDefaultArgExprScope : SourceLocExprScopeGuard { 1468 CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E) 1469 : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {} 1470 }; 1471 1472 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the 1473 /// current loop index is overridden. 1474 class ArrayInitLoopExprScope { 1475 public: 1476 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index) 1477 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) { 1478 CGF.ArrayInitIndex = Index; 1479 } 1480 ~ArrayInitLoopExprScope() { 1481 CGF.ArrayInitIndex = OldArrayInitIndex; 1482 } 1483 1484 private: 1485 CodeGenFunction &CGF; 1486 llvm::Value *OldArrayInitIndex; 1487 }; 1488 1489 class InlinedInheritingConstructorScope { 1490 public: 1491 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD) 1492 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl), 1493 OldCurCodeDecl(CGF.CurCodeDecl), 1494 OldCXXABIThisDecl(CGF.CXXABIThisDecl), 1495 OldCXXABIThisValue(CGF.CXXABIThisValue), 1496 OldCXXThisValue(CGF.CXXThisValue), 1497 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment), 1498 OldCXXThisAlignment(CGF.CXXThisAlignment), 1499 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy), 1500 OldCXXInheritedCtorInitExprArgs( 1501 std::move(CGF.CXXInheritedCtorInitExprArgs)) { 1502 CGF.CurGD = GD; 1503 CGF.CurFuncDecl = CGF.CurCodeDecl = 1504 cast<CXXConstructorDecl>(GD.getDecl()); 1505 CGF.CXXABIThisDecl = nullptr; 1506 CGF.CXXABIThisValue = nullptr; 1507 CGF.CXXThisValue = nullptr; 1508 CGF.CXXABIThisAlignment = CharUnits(); 1509 CGF.CXXThisAlignment = CharUnits(); 1510 CGF.ReturnValue = Address::invalid(); 1511 CGF.FnRetTy = QualType(); 1512 CGF.CXXInheritedCtorInitExprArgs.clear(); 1513 } 1514 ~InlinedInheritingConstructorScope() { 1515 CGF.CurGD = OldCurGD; 1516 CGF.CurFuncDecl = OldCurFuncDecl; 1517 CGF.CurCodeDecl = OldCurCodeDecl; 1518 CGF.CXXABIThisDecl = OldCXXABIThisDecl; 1519 CGF.CXXABIThisValue = OldCXXABIThisValue; 1520 CGF.CXXThisValue = OldCXXThisValue; 1521 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment; 1522 CGF.CXXThisAlignment = OldCXXThisAlignment; 1523 CGF.ReturnValue = OldReturnValue; 1524 CGF.FnRetTy = OldFnRetTy; 1525 CGF.CXXInheritedCtorInitExprArgs = 1526 std::move(OldCXXInheritedCtorInitExprArgs); 1527 } 1528 1529 private: 1530 CodeGenFunction &CGF; 1531 GlobalDecl OldCurGD; 1532 const Decl *OldCurFuncDecl; 1533 const Decl *OldCurCodeDecl; 1534 ImplicitParamDecl *OldCXXABIThisDecl; 1535 llvm::Value *OldCXXABIThisValue; 1536 llvm::Value *OldCXXThisValue; 1537 CharUnits OldCXXABIThisAlignment; 1538 CharUnits OldCXXThisAlignment; 1539 Address OldReturnValue; 1540 QualType OldFnRetTy; 1541 CallArgList OldCXXInheritedCtorInitExprArgs; 1542 }; 1543 1544 private: 1545 /// CXXThisDecl - When generating code for a C++ member function, 1546 /// this will hold the implicit 'this' declaration. 1547 ImplicitParamDecl *CXXABIThisDecl = nullptr; 1548 llvm::Value *CXXABIThisValue = nullptr; 1549 llvm::Value *CXXThisValue = nullptr; 1550 CharUnits CXXABIThisAlignment; 1551 CharUnits CXXThisAlignment; 1552 1553 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 1554 /// this expression. 1555 Address CXXDefaultInitExprThis = Address::invalid(); 1556 1557 /// The current array initialization index when evaluating an 1558 /// ArrayInitIndexExpr within an ArrayInitLoopExpr. 1559 llvm::Value *ArrayInitIndex = nullptr; 1560 1561 /// The values of function arguments to use when evaluating 1562 /// CXXInheritedCtorInitExprs within this context. 1563 CallArgList CXXInheritedCtorInitExprArgs; 1564 1565 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 1566 /// destructor, this will hold the implicit argument (e.g. VTT). 1567 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr; 1568 llvm::Value *CXXStructorImplicitParamValue = nullptr; 1569 1570 /// OutermostConditional - Points to the outermost active 1571 /// conditional control. This is used so that we know if a 1572 /// temporary should be destroyed conditionally. 1573 ConditionalEvaluation *OutermostConditional = nullptr; 1574 1575 /// The current lexical scope. 1576 LexicalScope *CurLexicalScope = nullptr; 1577 1578 /// The current source location that should be used for exception 1579 /// handling code. 1580 SourceLocation CurEHLocation; 1581 1582 /// BlockByrefInfos - For each __block variable, contains 1583 /// information about the layout of the variable. 1584 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos; 1585 1586 /// Used by -fsanitize=nullability-return to determine whether the return 1587 /// value can be checked. 1588 llvm::Value *RetValNullabilityPrecondition = nullptr; 1589 1590 /// Check if -fsanitize=nullability-return instrumentation is required for 1591 /// this function. 1592 bool requiresReturnValueNullabilityCheck() const { 1593 return RetValNullabilityPrecondition; 1594 } 1595 1596 /// Used to store precise source locations for return statements by the 1597 /// runtime return value checks. 1598 Address ReturnLocation = Address::invalid(); 1599 1600 /// Check if the return value of this function requires sanitization. 1601 bool requiresReturnValueCheck() const; 1602 1603 llvm::BasicBlock *TerminateLandingPad = nullptr; 1604 llvm::BasicBlock *TerminateHandler = nullptr; 1605 llvm::BasicBlock *TrapBB = nullptr; 1606 1607 /// Terminate funclets keyed by parent funclet pad. 1608 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets; 1609 1610 /// Largest vector width used in ths function. Will be used to create a 1611 /// function attribute. 1612 unsigned LargestVectorWidth = 0; 1613 1614 /// True if we need emit the life-time markers. 1615 const bool ShouldEmitLifetimeMarkers; 1616 1617 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to 1618 /// the function metadata. 1619 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 1620 llvm::Function *Fn); 1621 1622 public: 1623 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 1624 ~CodeGenFunction(); 1625 1626 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 1627 ASTContext &getContext() const { return CGM.getContext(); } 1628 CGDebugInfo *getDebugInfo() { 1629 if (DisableDebugInfo) 1630 return nullptr; 1631 return DebugInfo; 1632 } 1633 void disableDebugInfo() { DisableDebugInfo = true; } 1634 void enableDebugInfo() { DisableDebugInfo = false; } 1635 1636 bool shouldUseFusedARCCalls() { 1637 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1638 } 1639 1640 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 1641 1642 /// Returns a pointer to the function's exception object and selector slot, 1643 /// which is assigned in every landing pad. 1644 Address getExceptionSlot(); 1645 Address getEHSelectorSlot(); 1646 1647 /// Returns the contents of the function's exception object and selector 1648 /// slots. 1649 llvm::Value *getExceptionFromSlot(); 1650 llvm::Value *getSelectorFromSlot(); 1651 1652 Address getNormalCleanupDestSlot(); 1653 1654 llvm::BasicBlock *getUnreachableBlock() { 1655 if (!UnreachableBlock) { 1656 UnreachableBlock = createBasicBlock("unreachable"); 1657 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 1658 } 1659 return UnreachableBlock; 1660 } 1661 1662 llvm::BasicBlock *getInvokeDest() { 1663 if (!EHStack.requiresLandingPad()) return nullptr; 1664 return getInvokeDestImpl(); 1665 } 1666 1667 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; } 1668 1669 const TargetInfo &getTarget() const { return Target; } 1670 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1671 const TargetCodeGenInfo &getTargetHooks() const { 1672 return CGM.getTargetCodeGenInfo(); 1673 } 1674 1675 //===--------------------------------------------------------------------===// 1676 // Cleanups 1677 //===--------------------------------------------------------------------===// 1678 1679 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty); 1680 1681 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1682 Address arrayEndPointer, 1683 QualType elementType, 1684 CharUnits elementAlignment, 1685 Destroyer *destroyer); 1686 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1687 llvm::Value *arrayEnd, 1688 QualType elementType, 1689 CharUnits elementAlignment, 1690 Destroyer *destroyer); 1691 1692 void pushDestroy(QualType::DestructionKind dtorKind, 1693 Address addr, QualType type); 1694 void pushEHDestroy(QualType::DestructionKind dtorKind, 1695 Address addr, QualType type); 1696 void pushDestroy(CleanupKind kind, Address addr, QualType type, 1697 Destroyer *destroyer, bool useEHCleanupForArray); 1698 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, 1699 QualType type, Destroyer *destroyer, 1700 bool useEHCleanupForArray); 1701 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 1702 llvm::Value *CompletePtr, 1703 QualType ElementType); 1704 void pushStackRestore(CleanupKind kind, Address SPMem); 1705 void emitDestroy(Address addr, QualType type, Destroyer *destroyer, 1706 bool useEHCleanupForArray); 1707 llvm::Function *generateDestroyHelper(Address addr, QualType type, 1708 Destroyer *destroyer, 1709 bool useEHCleanupForArray, 1710 const VarDecl *VD); 1711 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1712 QualType elementType, CharUnits elementAlign, 1713 Destroyer *destroyer, 1714 bool checkZeroLength, bool useEHCleanup); 1715 1716 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1717 1718 /// Determines whether an EH cleanup is required to destroy a type 1719 /// with the given destruction kind. 1720 bool needsEHCleanup(QualType::DestructionKind kind) { 1721 switch (kind) { 1722 case QualType::DK_none: 1723 return false; 1724 case QualType::DK_cxx_destructor: 1725 case QualType::DK_objc_weak_lifetime: 1726 case QualType::DK_nontrivial_c_struct: 1727 return getLangOpts().Exceptions; 1728 case QualType::DK_objc_strong_lifetime: 1729 return getLangOpts().Exceptions && 1730 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1731 } 1732 llvm_unreachable("bad destruction kind"); 1733 } 1734 1735 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1736 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1737 } 1738 1739 //===--------------------------------------------------------------------===// 1740 // Objective-C 1741 //===--------------------------------------------------------------------===// 1742 1743 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1744 1745 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD); 1746 1747 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1748 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1749 const ObjCPropertyImplDecl *PID); 1750 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1751 const ObjCPropertyImplDecl *propImpl, 1752 const ObjCMethodDecl *GetterMothodDecl, 1753 llvm::Constant *AtomicHelperFn); 1754 1755 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1756 ObjCMethodDecl *MD, bool ctor); 1757 1758 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1759 /// for the given property. 1760 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1761 const ObjCPropertyImplDecl *PID); 1762 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1763 const ObjCPropertyImplDecl *propImpl, 1764 llvm::Constant *AtomicHelperFn); 1765 1766 //===--------------------------------------------------------------------===// 1767 // Block Bits 1768 //===--------------------------------------------------------------------===// 1769 1770 /// Emit block literal. 1771 /// \return an LLVM value which is a pointer to a struct which contains 1772 /// information about the block, including the block invoke function, the 1773 /// captured variables, etc. 1774 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1775 static void destroyBlockInfos(CGBlockInfo *info); 1776 1777 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1778 const CGBlockInfo &Info, 1779 const DeclMapTy &ldm, 1780 bool IsLambdaConversionToBlock, 1781 bool BuildGlobalBlock); 1782 1783 /// Check if \p T is a C++ class that has a destructor that can throw. 1784 static bool cxxDestructorCanThrow(QualType T); 1785 1786 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1787 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1788 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1789 const ObjCPropertyImplDecl *PID); 1790 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 1791 const ObjCPropertyImplDecl *PID); 1792 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 1793 1794 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags, 1795 bool CanThrow); 1796 1797 class AutoVarEmission; 1798 1799 void emitByrefStructureInit(const AutoVarEmission &emission); 1800 1801 /// Enter a cleanup to destroy a __block variable. Note that this 1802 /// cleanup should be a no-op if the variable hasn't left the stack 1803 /// yet; if a cleanup is required for the variable itself, that needs 1804 /// to be done externally. 1805 /// 1806 /// \param Kind Cleanup kind. 1807 /// 1808 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block 1809 /// structure that will be passed to _Block_object_dispose. When 1810 /// \p LoadBlockVarAddr is true, the address of the field of the block 1811 /// structure that holds the address of the __block structure. 1812 /// 1813 /// \param Flags The flag that will be passed to _Block_object_dispose. 1814 /// 1815 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from 1816 /// \p Addr to get the address of the __block structure. 1817 void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags, 1818 bool LoadBlockVarAddr, bool CanThrow); 1819 1820 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, 1821 llvm::Value *ptr); 1822 1823 Address LoadBlockStruct(); 1824 Address GetAddrOfBlockDecl(const VarDecl *var); 1825 1826 /// BuildBlockByrefAddress - Computes the location of the 1827 /// data in a variable which is declared as __block. 1828 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, 1829 bool followForward = true); 1830 Address emitBlockByrefAddress(Address baseAddr, 1831 const BlockByrefInfo &info, 1832 bool followForward, 1833 const llvm::Twine &name); 1834 1835 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var); 1836 1837 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args); 1838 1839 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1840 const CGFunctionInfo &FnInfo); 1841 1842 /// Annotate the function with an attribute that disables TSan checking at 1843 /// runtime. 1844 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn); 1845 1846 /// Emit code for the start of a function. 1847 /// \param Loc The location to be associated with the function. 1848 /// \param StartLoc The location of the function body. 1849 void StartFunction(GlobalDecl GD, 1850 QualType RetTy, 1851 llvm::Function *Fn, 1852 const CGFunctionInfo &FnInfo, 1853 const FunctionArgList &Args, 1854 SourceLocation Loc = SourceLocation(), 1855 SourceLocation StartLoc = SourceLocation()); 1856 1857 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor); 1858 1859 void EmitConstructorBody(FunctionArgList &Args); 1860 void EmitDestructorBody(FunctionArgList &Args); 1861 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 1862 void EmitFunctionBody(const Stmt *Body); 1863 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S); 1864 1865 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 1866 CallArgList &CallArgs); 1867 void EmitLambdaBlockInvokeBody(); 1868 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 1869 void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD); 1870 void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) { 1871 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 1872 } 1873 void EmitAsanPrologueOrEpilogue(bool Prologue); 1874 1875 /// Emit the unified return block, trying to avoid its emission when 1876 /// possible. 1877 /// \return The debug location of the user written return statement if the 1878 /// return block is is avoided. 1879 llvm::DebugLoc EmitReturnBlock(); 1880 1881 /// FinishFunction - Complete IR generation of the current function. It is 1882 /// legal to call this function even if there is no current insertion point. 1883 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1884 1885 void StartThunk(llvm::Function *Fn, GlobalDecl GD, 1886 const CGFunctionInfo &FnInfo, bool IsUnprototyped); 1887 1888 void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, 1889 const ThunkInfo *Thunk, bool IsUnprototyped); 1890 1891 void FinishThunk(); 1892 1893 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 1894 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, 1895 llvm::FunctionCallee Callee); 1896 1897 /// Generate a thunk for the given method. 1898 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1899 GlobalDecl GD, const ThunkInfo &Thunk, 1900 bool IsUnprototyped); 1901 1902 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn, 1903 const CGFunctionInfo &FnInfo, 1904 GlobalDecl GD, const ThunkInfo &Thunk); 1905 1906 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1907 FunctionArgList &Args); 1908 1909 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init); 1910 1911 /// Struct with all information about dynamic [sub]class needed to set vptr. 1912 struct VPtr { 1913 BaseSubobject Base; 1914 const CXXRecordDecl *NearestVBase; 1915 CharUnits OffsetFromNearestVBase; 1916 const CXXRecordDecl *VTableClass; 1917 }; 1918 1919 /// Initialize the vtable pointer of the given subobject. 1920 void InitializeVTablePointer(const VPtr &vptr); 1921 1922 typedef llvm::SmallVector<VPtr, 4> VPtrsVector; 1923 1924 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1925 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass); 1926 1927 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase, 1928 CharUnits OffsetFromNearestVBase, 1929 bool BaseIsNonVirtualPrimaryBase, 1930 const CXXRecordDecl *VTableClass, 1931 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs); 1932 1933 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1934 1935 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1936 /// to by This. 1937 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy, 1938 const CXXRecordDecl *VTableClass); 1939 1940 enum CFITypeCheckKind { 1941 CFITCK_VCall, 1942 CFITCK_NVCall, 1943 CFITCK_DerivedCast, 1944 CFITCK_UnrelatedCast, 1945 CFITCK_ICall, 1946 CFITCK_NVMFCall, 1947 CFITCK_VMFCall, 1948 }; 1949 1950 /// Derived is the presumed address of an object of type T after a 1951 /// cast. If T is a polymorphic class type, emit a check that the virtual 1952 /// table for Derived belongs to a class derived from T. 1953 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, 1954 bool MayBeNull, CFITypeCheckKind TCK, 1955 SourceLocation Loc); 1956 1957 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable. 1958 /// If vptr CFI is enabled, emit a check that VTable is valid. 1959 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, 1960 CFITypeCheckKind TCK, SourceLocation Loc); 1961 1962 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for 1963 /// RD using llvm.type.test. 1964 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable, 1965 CFITypeCheckKind TCK, SourceLocation Loc); 1966 1967 /// If whole-program virtual table optimization is enabled, emit an assumption 1968 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is 1969 /// enabled, emit a check that VTable is a member of RD's type identifier. 1970 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 1971 llvm::Value *VTable, SourceLocation Loc); 1972 1973 /// Returns whether we should perform a type checked load when loading a 1974 /// virtual function for virtual calls to members of RD. This is generally 1975 /// true when both vcall CFI and whole-program-vtables are enabled. 1976 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD); 1977 1978 /// Emit a type checked load from the given vtable. 1979 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, 1980 uint64_t VTableByteOffset); 1981 1982 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1983 /// given phase of destruction for a destructor. The end result 1984 /// should call destructors on members and base classes in reverse 1985 /// order of their construction. 1986 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1987 1988 /// ShouldInstrumentFunction - Return true if the current function should be 1989 /// instrumented with __cyg_profile_func_* calls 1990 bool ShouldInstrumentFunction(); 1991 1992 /// ShouldXRayInstrument - Return true if the current function should be 1993 /// instrumented with XRay nop sleds. 1994 bool ShouldXRayInstrumentFunction() const; 1995 1996 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit 1997 /// XRay custom event handling calls. 1998 bool AlwaysEmitXRayCustomEvents() const; 1999 2000 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit 2001 /// XRay typed event handling calls. 2002 bool AlwaysEmitXRayTypedEvents() const; 2003 2004 /// Encode an address into a form suitable for use in a function prologue. 2005 llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F, 2006 llvm::Constant *Addr); 2007 2008 /// Decode an address used in a function prologue, encoded by \c 2009 /// EncodeAddrForUseInPrologue. 2010 llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F, 2011 llvm::Value *EncodedAddr); 2012 2013 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 2014 /// arguments for the given function. This is also responsible for naming the 2015 /// LLVM function arguments. 2016 void EmitFunctionProlog(const CGFunctionInfo &FI, 2017 llvm::Function *Fn, 2018 const FunctionArgList &Args); 2019 2020 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 2021 /// given temporary. 2022 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 2023 SourceLocation EndLoc); 2024 2025 /// Emit a test that checks if the return value \p RV is nonnull. 2026 void EmitReturnValueCheck(llvm::Value *RV); 2027 2028 /// EmitStartEHSpec - Emit the start of the exception spec. 2029 void EmitStartEHSpec(const Decl *D); 2030 2031 /// EmitEndEHSpec - Emit the end of the exception spec. 2032 void EmitEndEHSpec(const Decl *D); 2033 2034 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 2035 llvm::BasicBlock *getTerminateLandingPad(); 2036 2037 /// getTerminateLandingPad - Return a cleanup funclet that just calls 2038 /// terminate. 2039 llvm::BasicBlock *getTerminateFunclet(); 2040 2041 /// getTerminateHandler - Return a handler (not a landing pad, just 2042 /// a catch handler) that just calls terminate. This is used when 2043 /// a terminate scope encloses a try. 2044 llvm::BasicBlock *getTerminateHandler(); 2045 2046 llvm::Type *ConvertTypeForMem(QualType T); 2047 llvm::Type *ConvertType(QualType T); 2048 llvm::Type *ConvertType(const TypeDecl *T) { 2049 return ConvertType(getContext().getTypeDeclType(T)); 2050 } 2051 2052 /// LoadObjCSelf - Load the value of self. This function is only valid while 2053 /// generating code for an Objective-C method. 2054 llvm::Value *LoadObjCSelf(); 2055 2056 /// TypeOfSelfObject - Return type of object that this self represents. 2057 QualType TypeOfSelfObject(); 2058 2059 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T. 2060 static TypeEvaluationKind getEvaluationKind(QualType T); 2061 2062 static bool hasScalarEvaluationKind(QualType T) { 2063 return getEvaluationKind(T) == TEK_Scalar; 2064 } 2065 2066 static bool hasAggregateEvaluationKind(QualType T) { 2067 return getEvaluationKind(T) == TEK_Aggregate; 2068 } 2069 2070 /// createBasicBlock - Create an LLVM basic block. 2071 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 2072 llvm::Function *parent = nullptr, 2073 llvm::BasicBlock *before = nullptr) { 2074 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 2075 } 2076 2077 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 2078 /// label maps to. 2079 JumpDest getJumpDestForLabel(const LabelDecl *S); 2080 2081 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 2082 /// another basic block, simplify it. This assumes that no other code could 2083 /// potentially reference the basic block. 2084 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 2085 2086 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 2087 /// adding a fall-through branch from the current insert block if 2088 /// necessary. It is legal to call this function even if there is no current 2089 /// insertion point. 2090 /// 2091 /// IsFinished - If true, indicates that the caller has finished emitting 2092 /// branches to the given block and does not expect to emit code into it. This 2093 /// means the block can be ignored if it is unreachable. 2094 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 2095 2096 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 2097 /// near its uses, and leave the insertion point in it. 2098 void EmitBlockAfterUses(llvm::BasicBlock *BB); 2099 2100 /// EmitBranch - Emit a branch to the specified basic block from the current 2101 /// insert block, taking care to avoid creation of branches from dummy 2102 /// blocks. It is legal to call this function even if there is no current 2103 /// insertion point. 2104 /// 2105 /// This function clears the current insertion point. The caller should follow 2106 /// calls to this function with calls to Emit*Block prior to generation new 2107 /// code. 2108 void EmitBranch(llvm::BasicBlock *Block); 2109 2110 /// HaveInsertPoint - True if an insertion point is defined. If not, this 2111 /// indicates that the current code being emitted is unreachable. 2112 bool HaveInsertPoint() const { 2113 return Builder.GetInsertBlock() != nullptr; 2114 } 2115 2116 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 2117 /// emitted IR has a place to go. Note that by definition, if this function 2118 /// creates a block then that block is unreachable; callers may do better to 2119 /// detect when no insertion point is defined and simply skip IR generation. 2120 void EnsureInsertPoint() { 2121 if (!HaveInsertPoint()) 2122 EmitBlock(createBasicBlock()); 2123 } 2124 2125 /// ErrorUnsupported - Print out an error that codegen doesn't support the 2126 /// specified stmt yet. 2127 void ErrorUnsupported(const Stmt *S, const char *Type); 2128 2129 //===--------------------------------------------------------------------===// 2130 // Helpers 2131 //===--------------------------------------------------------------------===// 2132 2133 LValue MakeAddrLValue(Address Addr, QualType T, 2134 AlignmentSource Source = AlignmentSource::Type) { 2135 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source), 2136 CGM.getTBAAAccessInfo(T)); 2137 } 2138 2139 LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo, 2140 TBAAAccessInfo TBAAInfo) { 2141 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo); 2142 } 2143 2144 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 2145 AlignmentSource Source = AlignmentSource::Type) { 2146 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), 2147 LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T)); 2148 } 2149 2150 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 2151 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) { 2152 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), 2153 BaseInfo, TBAAInfo); 2154 } 2155 2156 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T); 2157 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 2158 CharUnits getNaturalTypeAlignment(QualType T, 2159 LValueBaseInfo *BaseInfo = nullptr, 2160 TBAAAccessInfo *TBAAInfo = nullptr, 2161 bool forPointeeType = false); 2162 CharUnits getNaturalPointeeTypeAlignment(QualType T, 2163 LValueBaseInfo *BaseInfo = nullptr, 2164 TBAAAccessInfo *TBAAInfo = nullptr); 2165 2166 Address EmitLoadOfReference(LValue RefLVal, 2167 LValueBaseInfo *PointeeBaseInfo = nullptr, 2168 TBAAAccessInfo *PointeeTBAAInfo = nullptr); 2169 LValue EmitLoadOfReferenceLValue(LValue RefLVal); 2170 LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy, 2171 AlignmentSource Source = 2172 AlignmentSource::Type) { 2173 LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source), 2174 CGM.getTBAAAccessInfo(RefTy)); 2175 return EmitLoadOfReferenceLValue(RefLVal); 2176 } 2177 2178 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, 2179 LValueBaseInfo *BaseInfo = nullptr, 2180 TBAAAccessInfo *TBAAInfo = nullptr); 2181 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy); 2182 2183 /// CreateTempAlloca - This creates an alloca and inserts it into the entry 2184 /// block if \p ArraySize is nullptr, otherwise inserts it at the current 2185 /// insertion point of the builder. The caller is responsible for setting an 2186 /// appropriate alignment on 2187 /// the alloca. 2188 /// 2189 /// \p ArraySize is the number of array elements to be allocated if it 2190 /// is not nullptr. 2191 /// 2192 /// LangAS::Default is the address space of pointers to local variables and 2193 /// temporaries, as exposed in the source language. In certain 2194 /// configurations, this is not the same as the alloca address space, and a 2195 /// cast is needed to lift the pointer from the alloca AS into 2196 /// LangAS::Default. This can happen when the target uses a restricted 2197 /// address space for the stack but the source language requires 2198 /// LangAS::Default to be a generic address space. The latter condition is 2199 /// common for most programming languages; OpenCL is an exception in that 2200 /// LangAS::Default is the private address space, which naturally maps 2201 /// to the stack. 2202 /// 2203 /// Because the address of a temporary is often exposed to the program in 2204 /// various ways, this function will perform the cast. The original alloca 2205 /// instruction is returned through \p Alloca if it is not nullptr. 2206 /// 2207 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is 2208 /// more efficient if the caller knows that the address will not be exposed. 2209 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp", 2210 llvm::Value *ArraySize = nullptr); 2211 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align, 2212 const Twine &Name = "tmp", 2213 llvm::Value *ArraySize = nullptr, 2214 Address *Alloca = nullptr); 2215 Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, 2216 const Twine &Name = "tmp", 2217 llvm::Value *ArraySize = nullptr); 2218 2219 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the 2220 /// default ABI alignment of the given LLVM type. 2221 /// 2222 /// IMPORTANT NOTE: This is *not* generally the right alignment for 2223 /// any given AST type that happens to have been lowered to the 2224 /// given IR type. This should only ever be used for function-local, 2225 /// IR-driven manipulations like saving and restoring a value. Do 2226 /// not hand this address off to arbitrary IRGen routines, and especially 2227 /// do not pass it as an argument to a function that might expect a 2228 /// properly ABI-aligned value. 2229 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, 2230 const Twine &Name = "tmp"); 2231 2232 /// InitTempAlloca - Provide an initial value for the given alloca which 2233 /// will be observable at all locations in the function. 2234 /// 2235 /// The address should be something that was returned from one of 2236 /// the CreateTempAlloca or CreateMemTemp routines, and the 2237 /// initializer must be valid in the entry block (i.e. it must 2238 /// either be a constant or an argument value). 2239 void InitTempAlloca(Address Alloca, llvm::Value *Value); 2240 2241 /// CreateIRTemp - Create a temporary IR object of the given type, with 2242 /// appropriate alignment. This routine should only be used when an temporary 2243 /// value needs to be stored into an alloca (for example, to avoid explicit 2244 /// PHI construction), but the type is the IR type, not the type appropriate 2245 /// for storing in memory. 2246 /// 2247 /// That is, this is exactly equivalent to CreateMemTemp, but calling 2248 /// ConvertType instead of ConvertTypeForMem. 2249 Address CreateIRTemp(QualType T, const Twine &Name = "tmp"); 2250 2251 /// CreateMemTemp - Create a temporary memory object of the given type, with 2252 /// appropriate alignmen and cast it to the default address space. Returns 2253 /// the original alloca instruction by \p Alloca if it is not nullptr. 2254 Address CreateMemTemp(QualType T, const Twine &Name = "tmp", 2255 Address *Alloca = nullptr); 2256 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp", 2257 Address *Alloca = nullptr); 2258 2259 /// CreateMemTemp - Create a temporary memory object of the given type, with 2260 /// appropriate alignmen without casting it to the default address space. 2261 Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp"); 2262 Address CreateMemTempWithoutCast(QualType T, CharUnits Align, 2263 const Twine &Name = "tmp"); 2264 2265 /// CreateAggTemp - Create a temporary memory object for the given 2266 /// aggregate type. 2267 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp", 2268 Address *Alloca = nullptr) { 2269 return AggValueSlot::forAddr(CreateMemTemp(T, Name, Alloca), 2270 T.getQualifiers(), 2271 AggValueSlot::IsNotDestructed, 2272 AggValueSlot::DoesNotNeedGCBarriers, 2273 AggValueSlot::IsNotAliased, 2274 AggValueSlot::DoesNotOverlap); 2275 } 2276 2277 /// Emit a cast to void* in the appropriate address space. 2278 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 2279 2280 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 2281 /// expression and compare the result against zero, returning an Int1Ty value. 2282 llvm::Value *EvaluateExprAsBool(const Expr *E); 2283 2284 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 2285 void EmitIgnoredExpr(const Expr *E); 2286 2287 /// EmitAnyExpr - Emit code to compute the specified expression which can have 2288 /// any type. The result is returned as an RValue struct. If this is an 2289 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 2290 /// the result should be returned. 2291 /// 2292 /// \param ignoreResult True if the resulting value isn't used. 2293 RValue EmitAnyExpr(const Expr *E, 2294 AggValueSlot aggSlot = AggValueSlot::ignored(), 2295 bool ignoreResult = false); 2296 2297 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 2298 // or the value of the expression, depending on how va_list is defined. 2299 Address EmitVAListRef(const Expr *E); 2300 2301 /// Emit a "reference" to a __builtin_ms_va_list; this is 2302 /// always the value of the expression, because a __builtin_ms_va_list is a 2303 /// pointer to a char. 2304 Address EmitMSVAListRef(const Expr *E); 2305 2306 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will 2307 /// always be accessible even if no aggregate location is provided. 2308 RValue EmitAnyExprToTemp(const Expr *E); 2309 2310 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 2311 /// arbitrary expression into the given memory location. 2312 void EmitAnyExprToMem(const Expr *E, Address Location, 2313 Qualifiers Quals, bool IsInitializer); 2314 2315 void EmitAnyExprToExn(const Expr *E, Address Addr); 2316 2317 /// EmitExprAsInit - Emits the code necessary to initialize a 2318 /// location in memory with the given initializer. 2319 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2320 bool capturedByInit); 2321 2322 /// hasVolatileMember - returns true if aggregate type has a volatile 2323 /// member. 2324 bool hasVolatileMember(QualType T) { 2325 if (const RecordType *RT = T->getAs<RecordType>()) { 2326 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2327 return RD->hasVolatileMember(); 2328 } 2329 return false; 2330 } 2331 2332 /// Determine whether a return value slot may overlap some other object. 2333 AggValueSlot::Overlap_t getOverlapForReturnValue() { 2334 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base 2335 // class subobjects. These cases may need to be revisited depending on the 2336 // resolution of the relevant core issue. 2337 return AggValueSlot::DoesNotOverlap; 2338 } 2339 2340 /// Determine whether a field initialization may overlap some other object. 2341 AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD); 2342 2343 /// Determine whether a base class initialization may overlap some other 2344 /// object. 2345 AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD, 2346 const CXXRecordDecl *BaseRD, 2347 bool IsVirtual); 2348 2349 /// Emit an aggregate assignment. 2350 void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) { 2351 bool IsVolatile = hasVolatileMember(EltTy); 2352 EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile); 2353 } 2354 2355 void EmitAggregateCopyCtor(LValue Dest, LValue Src, 2356 AggValueSlot::Overlap_t MayOverlap) { 2357 EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap); 2358 } 2359 2360 /// EmitAggregateCopy - Emit an aggregate copy. 2361 /// 2362 /// \param isVolatile \c true iff either the source or the destination is 2363 /// volatile. 2364 /// \param MayOverlap Whether the tail padding of the destination might be 2365 /// occupied by some other object. More efficient code can often be 2366 /// generated if not. 2367 void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, 2368 AggValueSlot::Overlap_t MayOverlap, 2369 bool isVolatile = false); 2370 2371 /// GetAddrOfLocalVar - Return the address of a local variable. 2372 Address GetAddrOfLocalVar(const VarDecl *VD) { 2373 auto it = LocalDeclMap.find(VD); 2374 assert(it != LocalDeclMap.end() && 2375 "Invalid argument to GetAddrOfLocalVar(), no decl!"); 2376 return it->second; 2377 } 2378 2379 /// Given an opaque value expression, return its LValue mapping if it exists, 2380 /// otherwise create one. 2381 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e); 2382 2383 /// Given an opaque value expression, return its RValue mapping if it exists, 2384 /// otherwise create one. 2385 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e); 2386 2387 /// Get the index of the current ArrayInitLoopExpr, if any. 2388 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; } 2389 2390 /// getAccessedFieldNo - Given an encoded value and a result number, return 2391 /// the input field number being accessed. 2392 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 2393 2394 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 2395 llvm::BasicBlock *GetIndirectGotoBlock(); 2396 2397 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts. 2398 static bool IsWrappedCXXThis(const Expr *E); 2399 2400 /// EmitNullInitialization - Generate code to set a value of the given type to 2401 /// null, If the type contains data member pointers, they will be initialized 2402 /// to -1 in accordance with the Itanium C++ ABI. 2403 void EmitNullInitialization(Address DestPtr, QualType Ty); 2404 2405 /// Emits a call to an LLVM variable-argument intrinsic, either 2406 /// \c llvm.va_start or \c llvm.va_end. 2407 /// \param ArgValue A reference to the \c va_list as emitted by either 2408 /// \c EmitVAListRef or \c EmitMSVAListRef. 2409 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise, 2410 /// calls \c llvm.va_end. 2411 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart); 2412 2413 /// Generate code to get an argument from the passed in pointer 2414 /// and update it accordingly. 2415 /// \param VE The \c VAArgExpr for which to generate code. 2416 /// \param VAListAddr Receives a reference to the \c va_list as emitted by 2417 /// either \c EmitVAListRef or \c EmitMSVAListRef. 2418 /// \returns A pointer to the argument. 2419 // FIXME: We should be able to get rid of this method and use the va_arg 2420 // instruction in LLVM instead once it works well enough. 2421 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr); 2422 2423 /// emitArrayLength - Compute the length of an array, even if it's a 2424 /// VLA, and drill down to the base element type. 2425 llvm::Value *emitArrayLength(const ArrayType *arrayType, 2426 QualType &baseType, 2427 Address &addr); 2428 2429 /// EmitVLASize - Capture all the sizes for the VLA expressions in 2430 /// the given variably-modified type and store them in the VLASizeMap. 2431 /// 2432 /// This function can be called with a null (unreachable) insert point. 2433 void EmitVariablyModifiedType(QualType Ty); 2434 2435 struct VlaSizePair { 2436 llvm::Value *NumElts; 2437 QualType Type; 2438 2439 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {} 2440 }; 2441 2442 /// Return the number of elements for a single dimension 2443 /// for the given array type. 2444 VlaSizePair getVLAElements1D(const VariableArrayType *vla); 2445 VlaSizePair getVLAElements1D(QualType vla); 2446 2447 /// Returns an LLVM value that corresponds to the size, 2448 /// in non-variably-sized elements, of a variable length array type, 2449 /// plus that largest non-variably-sized element type. Assumes that 2450 /// the type has already been emitted with EmitVariablyModifiedType. 2451 VlaSizePair getVLASize(const VariableArrayType *vla); 2452 VlaSizePair getVLASize(QualType vla); 2453 2454 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 2455 /// generating code for an C++ member function. 2456 llvm::Value *LoadCXXThis() { 2457 assert(CXXThisValue && "no 'this' value for this function"); 2458 return CXXThisValue; 2459 } 2460 Address LoadCXXThisAddress(); 2461 2462 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 2463 /// virtual bases. 2464 // FIXME: Every place that calls LoadCXXVTT is something 2465 // that needs to be abstracted properly. 2466 llvm::Value *LoadCXXVTT() { 2467 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 2468 return CXXStructorImplicitParamValue; 2469 } 2470 2471 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 2472 /// complete class to the given direct base. 2473 Address 2474 GetAddressOfDirectBaseInCompleteClass(Address Value, 2475 const CXXRecordDecl *Derived, 2476 const CXXRecordDecl *Base, 2477 bool BaseIsVirtual); 2478 2479 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast); 2480 2481 /// GetAddressOfBaseClass - This function will add the necessary delta to the 2482 /// load of 'this' and returns address of the base class. 2483 Address GetAddressOfBaseClass(Address Value, 2484 const CXXRecordDecl *Derived, 2485 CastExpr::path_const_iterator PathBegin, 2486 CastExpr::path_const_iterator PathEnd, 2487 bool NullCheckValue, SourceLocation Loc); 2488 2489 Address GetAddressOfDerivedClass(Address Value, 2490 const CXXRecordDecl *Derived, 2491 CastExpr::path_const_iterator PathBegin, 2492 CastExpr::path_const_iterator PathEnd, 2493 bool NullCheckValue); 2494 2495 /// GetVTTParameter - Return the VTT parameter that should be passed to a 2496 /// base constructor/destructor with virtual bases. 2497 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 2498 /// to ItaniumCXXABI.cpp together with all the references to VTT. 2499 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 2500 bool Delegating); 2501 2502 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2503 CXXCtorType CtorType, 2504 const FunctionArgList &Args, 2505 SourceLocation Loc); 2506 // It's important not to confuse this and the previous function. Delegating 2507 // constructors are the C++0x feature. The constructor delegate optimization 2508 // is used to reduce duplication in the base and complete consturctors where 2509 // they are substantially the same. 2510 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2511 const FunctionArgList &Args); 2512 2513 /// Emit a call to an inheriting constructor (that is, one that invokes a 2514 /// constructor inherited from a base class) by inlining its definition. This 2515 /// is necessary if the ABI does not support forwarding the arguments to the 2516 /// base class constructor (because they're variadic or similar). 2517 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2518 CXXCtorType CtorType, 2519 bool ForVirtualBase, 2520 bool Delegating, 2521 CallArgList &Args); 2522 2523 /// Emit a call to a constructor inherited from a base class, passing the 2524 /// current constructor's arguments along unmodified (without even making 2525 /// a copy). 2526 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, 2527 bool ForVirtualBase, Address This, 2528 bool InheritedFromVBase, 2529 const CXXInheritedCtorInitExpr *E); 2530 2531 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2532 bool ForVirtualBase, bool Delegating, 2533 AggValueSlot ThisAVS, const CXXConstructExpr *E); 2534 2535 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2536 bool ForVirtualBase, bool Delegating, 2537 Address This, CallArgList &Args, 2538 AggValueSlot::Overlap_t Overlap, 2539 SourceLocation Loc, bool NewPointerIsChecked); 2540 2541 /// Emit assumption load for all bases. Requires to be be called only on 2542 /// most-derived class and not under construction of the object. 2543 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This); 2544 2545 /// Emit assumption that vptr load == global vtable. 2546 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This); 2547 2548 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2549 Address This, Address Src, 2550 const CXXConstructExpr *E); 2551 2552 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2553 const ArrayType *ArrayTy, 2554 Address ArrayPtr, 2555 const CXXConstructExpr *E, 2556 bool NewPointerIsChecked, 2557 bool ZeroInitialization = false); 2558 2559 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2560 llvm::Value *NumElements, 2561 Address ArrayPtr, 2562 const CXXConstructExpr *E, 2563 bool NewPointerIsChecked, 2564 bool ZeroInitialization = false); 2565 2566 static Destroyer destroyCXXObject; 2567 2568 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 2569 bool ForVirtualBase, bool Delegating, Address This, 2570 QualType ThisTy); 2571 2572 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 2573 llvm::Type *ElementTy, Address NewPtr, 2574 llvm::Value *NumElements, 2575 llvm::Value *AllocSizeWithoutCookie); 2576 2577 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 2578 Address Ptr); 2579 2580 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr); 2581 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr); 2582 2583 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 2584 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 2585 2586 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 2587 QualType DeleteTy, llvm::Value *NumElements = nullptr, 2588 CharUnits CookieSize = CharUnits()); 2589 2590 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 2591 const CallExpr *TheCallExpr, bool IsDelete); 2592 2593 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E); 2594 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE); 2595 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E); 2596 2597 /// Situations in which we might emit a check for the suitability of a 2598 /// pointer or glvalue. 2599 enum TypeCheckKind { 2600 /// Checking the operand of a load. Must be suitably sized and aligned. 2601 TCK_Load, 2602 /// Checking the destination of a store. Must be suitably sized and aligned. 2603 TCK_Store, 2604 /// Checking the bound value in a reference binding. Must be suitably sized 2605 /// and aligned, but is not required to refer to an object (until the 2606 /// reference is used), per core issue 453. 2607 TCK_ReferenceBinding, 2608 /// Checking the object expression in a non-static data member access. Must 2609 /// be an object within its lifetime. 2610 TCK_MemberAccess, 2611 /// Checking the 'this' pointer for a call to a non-static member function. 2612 /// Must be an object within its lifetime. 2613 TCK_MemberCall, 2614 /// Checking the 'this' pointer for a constructor call. 2615 TCK_ConstructorCall, 2616 /// Checking the operand of a static_cast to a derived pointer type. Must be 2617 /// null or an object within its lifetime. 2618 TCK_DowncastPointer, 2619 /// Checking the operand of a static_cast to a derived reference type. Must 2620 /// be an object within its lifetime. 2621 TCK_DowncastReference, 2622 /// Checking the operand of a cast to a base object. Must be suitably sized 2623 /// and aligned. 2624 TCK_Upcast, 2625 /// Checking the operand of a cast to a virtual base object. Must be an 2626 /// object within its lifetime. 2627 TCK_UpcastToVirtualBase, 2628 /// Checking the value assigned to a _Nonnull pointer. Must not be null. 2629 TCK_NonnullAssign, 2630 /// Checking the operand of a dynamic_cast or a typeid expression. Must be 2631 /// null or an object within its lifetime. 2632 TCK_DynamicOperation 2633 }; 2634 2635 /// Determine whether the pointer type check \p TCK permits null pointers. 2636 static bool isNullPointerAllowed(TypeCheckKind TCK); 2637 2638 /// Determine whether the pointer type check \p TCK requires a vptr check. 2639 static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty); 2640 2641 /// Whether any type-checking sanitizers are enabled. If \c false, 2642 /// calls to EmitTypeCheck can be skipped. 2643 bool sanitizePerformTypeCheck() const; 2644 2645 /// Emit a check that \p V is the address of storage of the 2646 /// appropriate size and alignment for an object of type \p Type 2647 /// (or if ArraySize is provided, for an array of that bound). 2648 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 2649 QualType Type, CharUnits Alignment = CharUnits::Zero(), 2650 SanitizerSet SkippedChecks = SanitizerSet(), 2651 llvm::Value *ArraySize = nullptr); 2652 2653 /// Emit a check that \p Base points into an array object, which 2654 /// we can access at index \p Index. \p Accessed should be \c false if we 2655 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 2656 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 2657 QualType IndexType, bool Accessed); 2658 2659 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2660 bool isInc, bool isPre); 2661 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 2662 bool isInc, bool isPre); 2663 2664 /// Converts Location to a DebugLoc, if debug information is enabled. 2665 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location); 2666 2667 /// Get the record field index as represented in debug info. 2668 unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex); 2669 2670 2671 //===--------------------------------------------------------------------===// 2672 // Declaration Emission 2673 //===--------------------------------------------------------------------===// 2674 2675 /// EmitDecl - Emit a declaration. 2676 /// 2677 /// This function can be called with a null (unreachable) insert point. 2678 void EmitDecl(const Decl &D); 2679 2680 /// EmitVarDecl - Emit a local variable declaration. 2681 /// 2682 /// This function can be called with a null (unreachable) insert point. 2683 void EmitVarDecl(const VarDecl &D); 2684 2685 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2686 bool capturedByInit); 2687 2688 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 2689 llvm::Value *Address); 2690 2691 /// Determine whether the given initializer is trivial in the sense 2692 /// that it requires no code to be generated. 2693 bool isTrivialInitializer(const Expr *Init); 2694 2695 /// EmitAutoVarDecl - Emit an auto variable declaration. 2696 /// 2697 /// This function can be called with a null (unreachable) insert point. 2698 void EmitAutoVarDecl(const VarDecl &D); 2699 2700 class AutoVarEmission { 2701 friend class CodeGenFunction; 2702 2703 const VarDecl *Variable; 2704 2705 /// The address of the alloca for languages with explicit address space 2706 /// (e.g. OpenCL) or alloca casted to generic pointer for address space 2707 /// agnostic languages (e.g. C++). Invalid if the variable was emitted 2708 /// as a global constant. 2709 Address Addr; 2710 2711 llvm::Value *NRVOFlag; 2712 2713 /// True if the variable is a __block variable that is captured by an 2714 /// escaping block. 2715 bool IsEscapingByRef; 2716 2717 /// True if the variable is of aggregate type and has a constant 2718 /// initializer. 2719 bool IsConstantAggregate; 2720 2721 /// Non-null if we should use lifetime annotations. 2722 llvm::Value *SizeForLifetimeMarkers; 2723 2724 /// Address with original alloca instruction. Invalid if the variable was 2725 /// emitted as a global constant. 2726 Address AllocaAddr; 2727 2728 struct Invalid {}; 2729 AutoVarEmission(Invalid) 2730 : Variable(nullptr), Addr(Address::invalid()), 2731 AllocaAddr(Address::invalid()) {} 2732 2733 AutoVarEmission(const VarDecl &variable) 2734 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr), 2735 IsEscapingByRef(false), IsConstantAggregate(false), 2736 SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {} 2737 2738 bool wasEmittedAsGlobal() const { return !Addr.isValid(); } 2739 2740 public: 2741 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 2742 2743 bool useLifetimeMarkers() const { 2744 return SizeForLifetimeMarkers != nullptr; 2745 } 2746 llvm::Value *getSizeForLifetimeMarkers() const { 2747 assert(useLifetimeMarkers()); 2748 return SizeForLifetimeMarkers; 2749 } 2750 2751 /// Returns the raw, allocated address, which is not necessarily 2752 /// the address of the object itself. It is casted to default 2753 /// address space for address space agnostic languages. 2754 Address getAllocatedAddress() const { 2755 return Addr; 2756 } 2757 2758 /// Returns the address for the original alloca instruction. 2759 Address getOriginalAllocatedAddress() const { return AllocaAddr; } 2760 2761 /// Returns the address of the object within this declaration. 2762 /// Note that this does not chase the forwarding pointer for 2763 /// __block decls. 2764 Address getObjectAddress(CodeGenFunction &CGF) const { 2765 if (!IsEscapingByRef) return Addr; 2766 2767 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false); 2768 } 2769 }; 2770 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 2771 void EmitAutoVarInit(const AutoVarEmission &emission); 2772 void EmitAutoVarCleanups(const AutoVarEmission &emission); 2773 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 2774 QualType::DestructionKind dtorKind); 2775 2776 /// Emits the alloca and debug information for the size expressions for each 2777 /// dimension of an array. It registers the association of its (1-dimensional) 2778 /// QualTypes and size expression's debug node, so that CGDebugInfo can 2779 /// reference this node when creating the DISubrange object to describe the 2780 /// array types. 2781 void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI, 2782 const VarDecl &D, 2783 bool EmitDebugInfo); 2784 2785 void EmitStaticVarDecl(const VarDecl &D, 2786 llvm::GlobalValue::LinkageTypes Linkage); 2787 2788 class ParamValue { 2789 llvm::Value *Value; 2790 unsigned Alignment; 2791 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {} 2792 public: 2793 static ParamValue forDirect(llvm::Value *value) { 2794 return ParamValue(value, 0); 2795 } 2796 static ParamValue forIndirect(Address addr) { 2797 assert(!addr.getAlignment().isZero()); 2798 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity()); 2799 } 2800 2801 bool isIndirect() const { return Alignment != 0; } 2802 llvm::Value *getAnyValue() const { return Value; } 2803 2804 llvm::Value *getDirectValue() const { 2805 assert(!isIndirect()); 2806 return Value; 2807 } 2808 2809 Address getIndirectAddress() const { 2810 assert(isIndirect()); 2811 return Address(Value, CharUnits::fromQuantity(Alignment)); 2812 } 2813 }; 2814 2815 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 2816 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo); 2817 2818 /// protectFromPeepholes - Protect a value that we're intending to 2819 /// store to the side, but which will probably be used later, from 2820 /// aggressive peepholing optimizations that might delete it. 2821 /// 2822 /// Pass the result to unprotectFromPeepholes to declare that 2823 /// protection is no longer required. 2824 /// 2825 /// There's no particular reason why this shouldn't apply to 2826 /// l-values, it's just that no existing peepholes work on pointers. 2827 PeepholeProtection protectFromPeepholes(RValue rvalue); 2828 void unprotectFromPeepholes(PeepholeProtection protection); 2829 2830 void EmitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, 2831 SourceLocation Loc, 2832 SourceLocation AssumptionLoc, 2833 llvm::Value *Alignment, 2834 llvm::Value *OffsetValue, 2835 llvm::Value *TheCheck, 2836 llvm::Instruction *Assumption); 2837 2838 void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, 2839 SourceLocation Loc, SourceLocation AssumptionLoc, 2840 llvm::Value *Alignment, 2841 llvm::Value *OffsetValue = nullptr); 2842 2843 void EmitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E, 2844 SourceLocation AssumptionLoc, llvm::Value *Alignment, 2845 llvm::Value *OffsetValue = nullptr); 2846 2847 //===--------------------------------------------------------------------===// 2848 // Statement Emission 2849 //===--------------------------------------------------------------------===// 2850 2851 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 2852 void EmitStopPoint(const Stmt *S); 2853 2854 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 2855 /// this function even if there is no current insertion point. 2856 /// 2857 /// This function may clear the current insertion point; callers should use 2858 /// EnsureInsertPoint if they wish to subsequently generate code without first 2859 /// calling EmitBlock, EmitBranch, or EmitStmt. 2860 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None); 2861 2862 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 2863 /// necessarily require an insertion point or debug information; typically 2864 /// because the statement amounts to a jump or a container of other 2865 /// statements. 2866 /// 2867 /// \return True if the statement was handled. 2868 bool EmitSimpleStmt(const Stmt *S); 2869 2870 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 2871 AggValueSlot AVS = AggValueSlot::ignored()); 2872 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, 2873 bool GetLast = false, 2874 AggValueSlot AVS = 2875 AggValueSlot::ignored()); 2876 2877 /// EmitLabel - Emit the block for the given label. It is legal to call this 2878 /// function even if there is no current insertion point. 2879 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 2880 2881 void EmitLabelStmt(const LabelStmt &S); 2882 void EmitAttributedStmt(const AttributedStmt &S); 2883 void EmitGotoStmt(const GotoStmt &S); 2884 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 2885 void EmitIfStmt(const IfStmt &S); 2886 2887 void EmitWhileStmt(const WhileStmt &S, 2888 ArrayRef<const Attr *> Attrs = None); 2889 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 2890 void EmitForStmt(const ForStmt &S, 2891 ArrayRef<const Attr *> Attrs = None); 2892 void EmitReturnStmt(const ReturnStmt &S); 2893 void EmitDeclStmt(const DeclStmt &S); 2894 void EmitBreakStmt(const BreakStmt &S); 2895 void EmitContinueStmt(const ContinueStmt &S); 2896 void EmitSwitchStmt(const SwitchStmt &S); 2897 void EmitDefaultStmt(const DefaultStmt &S); 2898 void EmitCaseStmt(const CaseStmt &S); 2899 void EmitCaseStmtRange(const CaseStmt &S); 2900 void EmitAsmStmt(const AsmStmt &S); 2901 2902 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 2903 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 2904 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 2905 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 2906 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 2907 2908 void EmitCoroutineBody(const CoroutineBodyStmt &S); 2909 void EmitCoreturnStmt(const CoreturnStmt &S); 2910 RValue EmitCoawaitExpr(const CoawaitExpr &E, 2911 AggValueSlot aggSlot = AggValueSlot::ignored(), 2912 bool ignoreResult = false); 2913 LValue EmitCoawaitLValue(const CoawaitExpr *E); 2914 RValue EmitCoyieldExpr(const CoyieldExpr &E, 2915 AggValueSlot aggSlot = AggValueSlot::ignored(), 2916 bool ignoreResult = false); 2917 LValue EmitCoyieldLValue(const CoyieldExpr *E); 2918 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID); 2919 2920 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 2921 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 2922 2923 void EmitCXXTryStmt(const CXXTryStmt &S); 2924 void EmitSEHTryStmt(const SEHTryStmt &S); 2925 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 2926 void EnterSEHTryStmt(const SEHTryStmt &S); 2927 void ExitSEHTryStmt(const SEHTryStmt &S); 2928 2929 void pushSEHCleanup(CleanupKind kind, 2930 llvm::Function *FinallyFunc); 2931 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, 2932 const Stmt *OutlinedStmt); 2933 2934 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, 2935 const SEHExceptStmt &Except); 2936 2937 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, 2938 const SEHFinallyStmt &Finally); 2939 2940 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, 2941 llvm::Value *ParentFP, 2942 llvm::Value *EntryEBP); 2943 llvm::Value *EmitSEHExceptionCode(); 2944 llvm::Value *EmitSEHExceptionInfo(); 2945 llvm::Value *EmitSEHAbnormalTermination(); 2946 2947 /// Emit simple code for OpenMP directives in Simd-only mode. 2948 void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D); 2949 2950 /// Scan the outlined statement for captures from the parent function. For 2951 /// each capture, mark the capture as escaped and emit a call to 2952 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap. 2953 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, 2954 bool IsFilter); 2955 2956 /// Recovers the address of a local in a parent function. ParentVar is the 2957 /// address of the variable used in the immediate parent function. It can 2958 /// either be an alloca or a call to llvm.localrecover if there are nested 2959 /// outlined functions. ParentFP is the frame pointer of the outermost parent 2960 /// frame. 2961 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, 2962 Address ParentVar, 2963 llvm::Value *ParentFP); 2964 2965 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 2966 ArrayRef<const Attr *> Attrs = None); 2967 2968 /// Controls insertion of cancellation exit blocks in worksharing constructs. 2969 class OMPCancelStackRAII { 2970 CodeGenFunction &CGF; 2971 2972 public: 2973 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 2974 bool HasCancel) 2975 : CGF(CGF) { 2976 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel); 2977 } 2978 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); } 2979 }; 2980 2981 /// Returns calculated size of the specified type. 2982 llvm::Value *getTypeSize(QualType Ty); 2983 LValue InitCapturedStruct(const CapturedStmt &S); 2984 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 2985 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 2986 Address GenerateCapturedStmtArgument(const CapturedStmt &S); 2987 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, 2988 SourceLocation Loc); 2989 void GenerateOpenMPCapturedVars(const CapturedStmt &S, 2990 SmallVectorImpl<llvm::Value *> &CapturedVars); 2991 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, 2992 SourceLocation Loc); 2993 /// Perform element by element copying of arrays with type \a 2994 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure 2995 /// generated by \a CopyGen. 2996 /// 2997 /// \param DestAddr Address of the destination array. 2998 /// \param SrcAddr Address of the source array. 2999 /// \param OriginalType Type of destination and source arrays. 3000 /// \param CopyGen Copying procedure that copies value of single array element 3001 /// to another single array element. 3002 void EmitOMPAggregateAssign( 3003 Address DestAddr, Address SrcAddr, QualType OriginalType, 3004 const llvm::function_ref<void(Address, Address)> CopyGen); 3005 /// Emit proper copying of data from one variable to another. 3006 /// 3007 /// \param OriginalType Original type of the copied variables. 3008 /// \param DestAddr Destination address. 3009 /// \param SrcAddr Source address. 3010 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has 3011 /// type of the base array element). 3012 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of 3013 /// the base array element). 3014 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a 3015 /// DestVD. 3016 void EmitOMPCopy(QualType OriginalType, 3017 Address DestAddr, Address SrcAddr, 3018 const VarDecl *DestVD, const VarDecl *SrcVD, 3019 const Expr *Copy); 3020 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or 3021 /// \a X = \a E \a BO \a E. 3022 /// 3023 /// \param X Value to be updated. 3024 /// \param E Update value. 3025 /// \param BO Binary operation for update operation. 3026 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update 3027 /// expression, false otherwise. 3028 /// \param AO Atomic ordering of the generated atomic instructions. 3029 /// \param CommonGen Code generator for complex expressions that cannot be 3030 /// expressed through atomicrmw instruction. 3031 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was 3032 /// generated, <false, RValue::get(nullptr)> otherwise. 3033 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr( 3034 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 3035 llvm::AtomicOrdering AO, SourceLocation Loc, 3036 const llvm::function_ref<RValue(RValue)> CommonGen); 3037 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 3038 OMPPrivateScope &PrivateScope); 3039 void EmitOMPPrivateClause(const OMPExecutableDirective &D, 3040 OMPPrivateScope &PrivateScope); 3041 void EmitOMPUseDevicePtrClause( 3042 const OMPClause &C, OMPPrivateScope &PrivateScope, 3043 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 3044 /// Emit code for copyin clause in \a D directive. The next code is 3045 /// generated at the start of outlined functions for directives: 3046 /// \code 3047 /// threadprivate_var1 = master_threadprivate_var1; 3048 /// operator=(threadprivate_var2, master_threadprivate_var2); 3049 /// ... 3050 /// __kmpc_barrier(&loc, global_tid); 3051 /// \endcode 3052 /// 3053 /// \param D OpenMP directive possibly with 'copyin' clause(s). 3054 /// \returns true if at least one copyin variable is found, false otherwise. 3055 bool EmitOMPCopyinClause(const OMPExecutableDirective &D); 3056 /// Emit initial code for lastprivate variables. If some variable is 3057 /// not also firstprivate, then the default initialization is used. Otherwise 3058 /// initialization of this variable is performed by EmitOMPFirstprivateClause 3059 /// method. 3060 /// 3061 /// \param D Directive that may have 'lastprivate' directives. 3062 /// \param PrivateScope Private scope for capturing lastprivate variables for 3063 /// proper codegen in internal captured statement. 3064 /// 3065 /// \returns true if there is at least one lastprivate variable, false 3066 /// otherwise. 3067 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, 3068 OMPPrivateScope &PrivateScope); 3069 /// Emit final copying of lastprivate values to original variables at 3070 /// the end of the worksharing or simd directive. 3071 /// 3072 /// \param D Directive that has at least one 'lastprivate' directives. 3073 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if 3074 /// it is the last iteration of the loop code in associated directive, or to 3075 /// 'i1 false' otherwise. If this item is nullptr, no final check is required. 3076 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, 3077 bool NoFinals, 3078 llvm::Value *IsLastIterCond = nullptr); 3079 /// Emit initial code for linear clauses. 3080 void EmitOMPLinearClause(const OMPLoopDirective &D, 3081 CodeGenFunction::OMPPrivateScope &PrivateScope); 3082 /// Emit final code for linear clauses. 3083 /// \param CondGen Optional conditional code for final part of codegen for 3084 /// linear clause. 3085 void EmitOMPLinearClauseFinal( 3086 const OMPLoopDirective &D, 3087 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen); 3088 /// Emit initial code for reduction variables. Creates reduction copies 3089 /// and initializes them with the values according to OpenMP standard. 3090 /// 3091 /// \param D Directive (possibly) with the 'reduction' clause. 3092 /// \param PrivateScope Private scope for capturing reduction variables for 3093 /// proper codegen in internal captured statement. 3094 /// 3095 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, 3096 OMPPrivateScope &PrivateScope); 3097 /// Emit final update of reduction values to original variables at 3098 /// the end of the directive. 3099 /// 3100 /// \param D Directive that has at least one 'reduction' directives. 3101 /// \param ReductionKind The kind of reduction to perform. 3102 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D, 3103 const OpenMPDirectiveKind ReductionKind); 3104 /// Emit initial code for linear variables. Creates private copies 3105 /// and initializes them with the values according to OpenMP standard. 3106 /// 3107 /// \param D Directive (possibly) with the 'linear' clause. 3108 /// \return true if at least one linear variable is found that should be 3109 /// initialized with the value of the original variable, false otherwise. 3110 bool EmitOMPLinearClauseInit(const OMPLoopDirective &D); 3111 3112 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/, 3113 llvm::Function * /*OutlinedFn*/, 3114 const OMPTaskDataTy & /*Data*/)> 3115 TaskGenTy; 3116 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, 3117 const OpenMPDirectiveKind CapturedRegion, 3118 const RegionCodeGenTy &BodyGen, 3119 const TaskGenTy &TaskGen, OMPTaskDataTy &Data); 3120 struct OMPTargetDataInfo { 3121 Address BasePointersArray = Address::invalid(); 3122 Address PointersArray = Address::invalid(); 3123 Address SizesArray = Address::invalid(); 3124 unsigned NumberOfTargetItems = 0; 3125 explicit OMPTargetDataInfo() = default; 3126 OMPTargetDataInfo(Address BasePointersArray, Address PointersArray, 3127 Address SizesArray, unsigned NumberOfTargetItems) 3128 : BasePointersArray(BasePointersArray), PointersArray(PointersArray), 3129 SizesArray(SizesArray), NumberOfTargetItems(NumberOfTargetItems) {} 3130 }; 3131 void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S, 3132 const RegionCodeGenTy &BodyGen, 3133 OMPTargetDataInfo &InputInfo); 3134 3135 void EmitOMPParallelDirective(const OMPParallelDirective &S); 3136 void EmitOMPSimdDirective(const OMPSimdDirective &S); 3137 void EmitOMPForDirective(const OMPForDirective &S); 3138 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 3139 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 3140 void EmitOMPSectionDirective(const OMPSectionDirective &S); 3141 void EmitOMPSingleDirective(const OMPSingleDirective &S); 3142 void EmitOMPMasterDirective(const OMPMasterDirective &S); 3143 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 3144 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 3145 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 3146 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 3147 void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S); 3148 void EmitOMPTaskDirective(const OMPTaskDirective &S); 3149 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 3150 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 3151 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 3152 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S); 3153 void EmitOMPFlushDirective(const OMPFlushDirective &S); 3154 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 3155 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 3156 void EmitOMPTargetDirective(const OMPTargetDirective &S); 3157 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S); 3158 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S); 3159 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S); 3160 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S); 3161 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S); 3162 void 3163 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S); 3164 void EmitOMPTeamsDirective(const OMPTeamsDirective &S); 3165 void 3166 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S); 3167 void EmitOMPCancelDirective(const OMPCancelDirective &S); 3168 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S); 3169 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S); 3170 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S); 3171 void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S); 3172 void 3173 EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S); 3174 void EmitOMPParallelMasterTaskLoopDirective( 3175 const OMPParallelMasterTaskLoopDirective &S); 3176 void EmitOMPParallelMasterTaskLoopSimdDirective( 3177 const OMPParallelMasterTaskLoopSimdDirective &S); 3178 void EmitOMPDistributeDirective(const OMPDistributeDirective &S); 3179 void EmitOMPDistributeParallelForDirective( 3180 const OMPDistributeParallelForDirective &S); 3181 void EmitOMPDistributeParallelForSimdDirective( 3182 const OMPDistributeParallelForSimdDirective &S); 3183 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S); 3184 void EmitOMPTargetParallelForSimdDirective( 3185 const OMPTargetParallelForSimdDirective &S); 3186 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S); 3187 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S); 3188 void 3189 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S); 3190 void EmitOMPTeamsDistributeParallelForSimdDirective( 3191 const OMPTeamsDistributeParallelForSimdDirective &S); 3192 void EmitOMPTeamsDistributeParallelForDirective( 3193 const OMPTeamsDistributeParallelForDirective &S); 3194 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S); 3195 void EmitOMPTargetTeamsDistributeDirective( 3196 const OMPTargetTeamsDistributeDirective &S); 3197 void EmitOMPTargetTeamsDistributeParallelForDirective( 3198 const OMPTargetTeamsDistributeParallelForDirective &S); 3199 void EmitOMPTargetTeamsDistributeParallelForSimdDirective( 3200 const OMPTargetTeamsDistributeParallelForSimdDirective &S); 3201 void EmitOMPTargetTeamsDistributeSimdDirective( 3202 const OMPTargetTeamsDistributeSimdDirective &S); 3203 3204 /// Emit device code for the target directive. 3205 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 3206 StringRef ParentName, 3207 const OMPTargetDirective &S); 3208 static void 3209 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName, 3210 const OMPTargetParallelDirective &S); 3211 /// Emit device code for the target parallel for directive. 3212 static void EmitOMPTargetParallelForDeviceFunction( 3213 CodeGenModule &CGM, StringRef ParentName, 3214 const OMPTargetParallelForDirective &S); 3215 /// Emit device code for the target parallel for simd directive. 3216 static void EmitOMPTargetParallelForSimdDeviceFunction( 3217 CodeGenModule &CGM, StringRef ParentName, 3218 const OMPTargetParallelForSimdDirective &S); 3219 /// Emit device code for the target teams directive. 3220 static void 3221 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName, 3222 const OMPTargetTeamsDirective &S); 3223 /// Emit device code for the target teams distribute directive. 3224 static void EmitOMPTargetTeamsDistributeDeviceFunction( 3225 CodeGenModule &CGM, StringRef ParentName, 3226 const OMPTargetTeamsDistributeDirective &S); 3227 /// Emit device code for the target teams distribute simd directive. 3228 static void EmitOMPTargetTeamsDistributeSimdDeviceFunction( 3229 CodeGenModule &CGM, StringRef ParentName, 3230 const OMPTargetTeamsDistributeSimdDirective &S); 3231 /// Emit device code for the target simd directive. 3232 static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM, 3233 StringRef ParentName, 3234 const OMPTargetSimdDirective &S); 3235 /// Emit device code for the target teams distribute parallel for simd 3236 /// directive. 3237 static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 3238 CodeGenModule &CGM, StringRef ParentName, 3239 const OMPTargetTeamsDistributeParallelForSimdDirective &S); 3240 3241 static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 3242 CodeGenModule &CGM, StringRef ParentName, 3243 const OMPTargetTeamsDistributeParallelForDirective &S); 3244 /// Emit inner loop of the worksharing/simd construct. 3245 /// 3246 /// \param S Directive, for which the inner loop must be emitted. 3247 /// \param RequiresCleanup true, if directive has some associated private 3248 /// variables. 3249 /// \param LoopCond Bollean condition for loop continuation. 3250 /// \param IncExpr Increment expression for loop control variable. 3251 /// \param BodyGen Generator for the inner body of the inner loop. 3252 /// \param PostIncGen Genrator for post-increment code (required for ordered 3253 /// loop directvies). 3254 void EmitOMPInnerLoop( 3255 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 3256 const Expr *IncExpr, 3257 const llvm::function_ref<void(CodeGenFunction &)> BodyGen, 3258 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen); 3259 3260 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind); 3261 /// Emit initial code for loop counters of loop-based directives. 3262 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S, 3263 OMPPrivateScope &LoopScope); 3264 3265 /// Helper for the OpenMP loop directives. 3266 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit); 3267 3268 /// Emit code for the worksharing loop-based directive. 3269 /// \return true, if this construct has any lastprivate clause, false - 3270 /// otherwise. 3271 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB, 3272 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 3273 const CodeGenDispatchBoundsTy &CGDispatchBounds); 3274 3275 /// Emit code for the distribute loop-based directive. 3276 void EmitOMPDistributeLoop(const OMPLoopDirective &S, 3277 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr); 3278 3279 /// Helpers for the OpenMP loop directives. 3280 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false); 3281 void EmitOMPSimdFinal( 3282 const OMPLoopDirective &D, 3283 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen); 3284 3285 /// Emits the lvalue for the expression with possibly captured variable. 3286 LValue EmitOMPSharedLValue(const Expr *E); 3287 3288 private: 3289 /// Helpers for blocks. 3290 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 3291 3292 /// struct with the values to be passed to the OpenMP loop-related functions 3293 struct OMPLoopArguments { 3294 /// loop lower bound 3295 Address LB = Address::invalid(); 3296 /// loop upper bound 3297 Address UB = Address::invalid(); 3298 /// loop stride 3299 Address ST = Address::invalid(); 3300 /// isLastIteration argument for runtime functions 3301 Address IL = Address::invalid(); 3302 /// Chunk value generated by sema 3303 llvm::Value *Chunk = nullptr; 3304 /// EnsureUpperBound 3305 Expr *EUB = nullptr; 3306 /// IncrementExpression 3307 Expr *IncExpr = nullptr; 3308 /// Loop initialization 3309 Expr *Init = nullptr; 3310 /// Loop exit condition 3311 Expr *Cond = nullptr; 3312 /// Update of LB after a whole chunk has been executed 3313 Expr *NextLB = nullptr; 3314 /// Update of UB after a whole chunk has been executed 3315 Expr *NextUB = nullptr; 3316 OMPLoopArguments() = default; 3317 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL, 3318 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr, 3319 Expr *IncExpr = nullptr, Expr *Init = nullptr, 3320 Expr *Cond = nullptr, Expr *NextLB = nullptr, 3321 Expr *NextUB = nullptr) 3322 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB), 3323 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB), 3324 NextUB(NextUB) {} 3325 }; 3326 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic, 3327 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, 3328 const OMPLoopArguments &LoopArgs, 3329 const CodeGenLoopTy &CodeGenLoop, 3330 const CodeGenOrderedTy &CodeGenOrdered); 3331 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind, 3332 bool IsMonotonic, const OMPLoopDirective &S, 3333 OMPPrivateScope &LoopScope, bool Ordered, 3334 const OMPLoopArguments &LoopArgs, 3335 const CodeGenDispatchBoundsTy &CGDispatchBounds); 3336 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind, 3337 const OMPLoopDirective &S, 3338 OMPPrivateScope &LoopScope, 3339 const OMPLoopArguments &LoopArgs, 3340 const CodeGenLoopTy &CodeGenLoopContent); 3341 /// Emit code for sections directive. 3342 void EmitSections(const OMPExecutableDirective &S); 3343 3344 public: 3345 3346 //===--------------------------------------------------------------------===// 3347 // LValue Expression Emission 3348 //===--------------------------------------------------------------------===// 3349 3350 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 3351 RValue GetUndefRValue(QualType Ty); 3352 3353 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 3354 /// and issue an ErrorUnsupported style diagnostic (using the 3355 /// provided Name). 3356 RValue EmitUnsupportedRValue(const Expr *E, 3357 const char *Name); 3358 3359 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 3360 /// an ErrorUnsupported style diagnostic (using the provided Name). 3361 LValue EmitUnsupportedLValue(const Expr *E, 3362 const char *Name); 3363 3364 /// EmitLValue - Emit code to compute a designator that specifies the location 3365 /// of the expression. 3366 /// 3367 /// This can return one of two things: a simple address or a bitfield 3368 /// reference. In either case, the LLVM Value* in the LValue structure is 3369 /// guaranteed to be an LLVM pointer type. 3370 /// 3371 /// If this returns a bitfield reference, nothing about the pointee type of 3372 /// the LLVM value is known: For example, it may not be a pointer to an 3373 /// integer. 3374 /// 3375 /// If this returns a normal address, and if the lvalue's C type is fixed 3376 /// size, this method guarantees that the returned pointer type will point to 3377 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 3378 /// variable length type, this is not possible. 3379 /// 3380 LValue EmitLValue(const Expr *E); 3381 3382 /// Same as EmitLValue but additionally we generate checking code to 3383 /// guard against undefined behavior. This is only suitable when we know 3384 /// that the address will be used to access the object. 3385 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 3386 3387 RValue convertTempToRValue(Address addr, QualType type, 3388 SourceLocation Loc); 3389 3390 void EmitAtomicInit(Expr *E, LValue lvalue); 3391 3392 bool LValueIsSuitableForInlineAtomic(LValue Src); 3393 3394 RValue EmitAtomicLoad(LValue LV, SourceLocation SL, 3395 AggValueSlot Slot = AggValueSlot::ignored()); 3396 3397 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 3398 llvm::AtomicOrdering AO, bool IsVolatile = false, 3399 AggValueSlot slot = AggValueSlot::ignored()); 3400 3401 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 3402 3403 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO, 3404 bool IsVolatile, bool isInit); 3405 3406 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange( 3407 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, 3408 llvm::AtomicOrdering Success = 3409 llvm::AtomicOrdering::SequentiallyConsistent, 3410 llvm::AtomicOrdering Failure = 3411 llvm::AtomicOrdering::SequentiallyConsistent, 3412 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored()); 3413 3414 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, 3415 const llvm::function_ref<RValue(RValue)> &UpdateOp, 3416 bool IsVolatile); 3417 3418 /// EmitToMemory - Change a scalar value from its value 3419 /// representation to its in-memory representation. 3420 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 3421 3422 /// EmitFromMemory - Change a scalar value from its memory 3423 /// representation to its value representation. 3424 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 3425 3426 /// Check if the scalar \p Value is within the valid range for the given 3427 /// type \p Ty. 3428 /// 3429 /// Returns true if a check is needed (even if the range is unknown). 3430 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, 3431 SourceLocation Loc); 3432 3433 /// EmitLoadOfScalar - Load a scalar value from an address, taking 3434 /// care to appropriately convert from the memory representation to 3435 /// the LLVM value representation. 3436 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 3437 SourceLocation Loc, 3438 AlignmentSource Source = AlignmentSource::Type, 3439 bool isNontemporal = false) { 3440 return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source), 3441 CGM.getTBAAAccessInfo(Ty), isNontemporal); 3442 } 3443 3444 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 3445 SourceLocation Loc, LValueBaseInfo BaseInfo, 3446 TBAAAccessInfo TBAAInfo, 3447 bool isNontemporal = false); 3448 3449 /// EmitLoadOfScalar - Load a scalar value from an address, taking 3450 /// care to appropriately convert from the memory representation to 3451 /// the LLVM value representation. The l-value must be a simple 3452 /// l-value. 3453 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 3454 3455 /// EmitStoreOfScalar - Store a scalar value to an address, taking 3456 /// care to appropriately convert from the memory representation to 3457 /// the LLVM value representation. 3458 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 3459 bool Volatile, QualType Ty, 3460 AlignmentSource Source = AlignmentSource::Type, 3461 bool isInit = false, bool isNontemporal = false) { 3462 EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source), 3463 CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal); 3464 } 3465 3466 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 3467 bool Volatile, QualType Ty, 3468 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo, 3469 bool isInit = false, bool isNontemporal = false); 3470 3471 /// EmitStoreOfScalar - Store a scalar value to an address, taking 3472 /// care to appropriately convert from the memory representation to 3473 /// the LLVM value representation. The l-value must be a simple 3474 /// l-value. The isInit flag indicates whether this is an initialization. 3475 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 3476 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 3477 3478 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 3479 /// this method emits the address of the lvalue, then loads the result as an 3480 /// rvalue, returning the rvalue. 3481 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 3482 RValue EmitLoadOfExtVectorElementLValue(LValue V); 3483 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc); 3484 RValue EmitLoadOfGlobalRegLValue(LValue LV); 3485 3486 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 3487 /// lvalue, where both are guaranteed to the have the same type, and that type 3488 /// is 'Ty'. 3489 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false); 3490 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 3491 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 3492 3493 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 3494 /// as EmitStoreThroughLValue. 3495 /// 3496 /// \param Result [out] - If non-null, this will be set to a Value* for the 3497 /// bit-field contents after the store, appropriate for use as the result of 3498 /// an assignment to the bit-field. 3499 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 3500 llvm::Value **Result=nullptr); 3501 3502 /// Emit an l-value for an assignment (simple or compound) of complex type. 3503 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 3504 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 3505 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, 3506 llvm::Value *&Result); 3507 3508 // Note: only available for agg return types 3509 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 3510 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 3511 // Note: only available for agg return types 3512 LValue EmitCallExprLValue(const CallExpr *E); 3513 // Note: only available for agg return types 3514 LValue EmitVAArgExprLValue(const VAArgExpr *E); 3515 LValue EmitDeclRefLValue(const DeclRefExpr *E); 3516 LValue EmitStringLiteralLValue(const StringLiteral *E); 3517 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 3518 LValue EmitPredefinedLValue(const PredefinedExpr *E); 3519 LValue EmitUnaryOpLValue(const UnaryOperator *E); 3520 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 3521 bool Accessed = false); 3522 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3523 bool IsLowerBound = true); 3524 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 3525 LValue EmitMemberExpr(const MemberExpr *E); 3526 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 3527 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 3528 LValue EmitInitListLValue(const InitListExpr *E); 3529 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 3530 LValue EmitCastLValue(const CastExpr *E); 3531 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 3532 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 3533 3534 Address EmitExtVectorElementLValue(LValue V); 3535 3536 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 3537 3538 Address EmitArrayToPointerDecay(const Expr *Array, 3539 LValueBaseInfo *BaseInfo = nullptr, 3540 TBAAAccessInfo *TBAAInfo = nullptr); 3541 3542 class ConstantEmission { 3543 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 3544 ConstantEmission(llvm::Constant *C, bool isReference) 3545 : ValueAndIsReference(C, isReference) {} 3546 public: 3547 ConstantEmission() {} 3548 static ConstantEmission forReference(llvm::Constant *C) { 3549 return ConstantEmission(C, true); 3550 } 3551 static ConstantEmission forValue(llvm::Constant *C) { 3552 return ConstantEmission(C, false); 3553 } 3554 3555 explicit operator bool() const { 3556 return ValueAndIsReference.getOpaqueValue() != nullptr; 3557 } 3558 3559 bool isReference() const { return ValueAndIsReference.getInt(); } 3560 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 3561 assert(isReference()); 3562 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 3563 refExpr->getType()); 3564 } 3565 3566 llvm::Constant *getValue() const { 3567 assert(!isReference()); 3568 return ValueAndIsReference.getPointer(); 3569 } 3570 }; 3571 3572 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 3573 ConstantEmission tryEmitAsConstant(const MemberExpr *ME); 3574 llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E); 3575 3576 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 3577 AggValueSlot slot = AggValueSlot::ignored()); 3578 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 3579 3580 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 3581 const ObjCIvarDecl *Ivar); 3582 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 3583 LValue EmitLValueForLambdaField(const FieldDecl *Field); 3584 3585 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 3586 /// if the Field is a reference, this will return the address of the reference 3587 /// and not the address of the value stored in the reference. 3588 LValue EmitLValueForFieldInitialization(LValue Base, 3589 const FieldDecl* Field); 3590 3591 LValue EmitLValueForIvar(QualType ObjectTy, 3592 llvm::Value* Base, const ObjCIvarDecl *Ivar, 3593 unsigned CVRQualifiers); 3594 3595 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 3596 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 3597 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 3598 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 3599 3600 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 3601 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 3602 LValue EmitStmtExprLValue(const StmtExpr *E); 3603 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 3604 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 3605 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init); 3606 3607 //===--------------------------------------------------------------------===// 3608 // Scalar Expression Emission 3609 //===--------------------------------------------------------------------===// 3610 3611 /// EmitCall - Generate a call of the given function, expecting the given 3612 /// result type, and using the given argument list which specifies both the 3613 /// LLVM arguments and the types they were derived from. 3614 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 3615 ReturnValueSlot ReturnValue, const CallArgList &Args, 3616 llvm::CallBase **callOrInvoke, SourceLocation Loc); 3617 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 3618 ReturnValueSlot ReturnValue, const CallArgList &Args, 3619 llvm::CallBase **callOrInvoke = nullptr) { 3620 return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke, 3621 SourceLocation()); 3622 } 3623 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E, 3624 ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr); 3625 RValue EmitCallExpr(const CallExpr *E, 3626 ReturnValueSlot ReturnValue = ReturnValueSlot()); 3627 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 3628 CGCallee EmitCallee(const Expr *E); 3629 3630 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl); 3631 void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl); 3632 3633 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee, 3634 const Twine &name = ""); 3635 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee, 3636 ArrayRef<llvm::Value *> args, 3637 const Twine &name = ""); 3638 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3639 const Twine &name = ""); 3640 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3641 ArrayRef<llvm::Value *> args, 3642 const Twine &name = ""); 3643 3644 SmallVector<llvm::OperandBundleDef, 1> 3645 getBundlesForFunclet(llvm::Value *Callee); 3646 3647 llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee, 3648 ArrayRef<llvm::Value *> Args, 3649 const Twine &Name = ""); 3650 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3651 ArrayRef<llvm::Value *> args, 3652 const Twine &name = ""); 3653 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3654 const Twine &name = ""); 3655 void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3656 ArrayRef<llvm::Value *> args); 3657 3658 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 3659 NestedNameSpecifier *Qual, 3660 llvm::Type *Ty); 3661 3662 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 3663 CXXDtorType Type, 3664 const CXXRecordDecl *RD); 3665 3666 // Return the copy constructor name with the prefix "__copy_constructor_" 3667 // removed. 3668 static std::string getNonTrivialCopyConstructorStr(QualType QT, 3669 CharUnits Alignment, 3670 bool IsVolatile, 3671 ASTContext &Ctx); 3672 3673 // Return the destructor name with the prefix "__destructor_" removed. 3674 static std::string getNonTrivialDestructorStr(QualType QT, 3675 CharUnits Alignment, 3676 bool IsVolatile, 3677 ASTContext &Ctx); 3678 3679 // These functions emit calls to the special functions of non-trivial C 3680 // structs. 3681 void defaultInitNonTrivialCStructVar(LValue Dst); 3682 void callCStructDefaultConstructor(LValue Dst); 3683 void callCStructDestructor(LValue Dst); 3684 void callCStructCopyConstructor(LValue Dst, LValue Src); 3685 void callCStructMoveConstructor(LValue Dst, LValue Src); 3686 void callCStructCopyAssignmentOperator(LValue Dst, LValue Src); 3687 void callCStructMoveAssignmentOperator(LValue Dst, LValue Src); 3688 3689 RValue 3690 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method, 3691 const CGCallee &Callee, 3692 ReturnValueSlot ReturnValue, llvm::Value *This, 3693 llvm::Value *ImplicitParam, 3694 QualType ImplicitParamTy, const CallExpr *E, 3695 CallArgList *RtlArgs); 3696 RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee, 3697 llvm::Value *This, QualType ThisTy, 3698 llvm::Value *ImplicitParam, 3699 QualType ImplicitParamTy, const CallExpr *E); 3700 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 3701 ReturnValueSlot ReturnValue); 3702 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE, 3703 const CXXMethodDecl *MD, 3704 ReturnValueSlot ReturnValue, 3705 bool HasQualifier, 3706 NestedNameSpecifier *Qualifier, 3707 bool IsArrow, const Expr *Base); 3708 // Compute the object pointer. 3709 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, 3710 llvm::Value *memberPtr, 3711 const MemberPointerType *memberPtrType, 3712 LValueBaseInfo *BaseInfo = nullptr, 3713 TBAAAccessInfo *TBAAInfo = nullptr); 3714 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 3715 ReturnValueSlot ReturnValue); 3716 3717 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 3718 const CXXMethodDecl *MD, 3719 ReturnValueSlot ReturnValue); 3720 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 3721 3722 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 3723 ReturnValueSlot ReturnValue); 3724 3725 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E, 3726 ReturnValueSlot ReturnValue); 3727 RValue EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E, 3728 ReturnValueSlot ReturnValue); 3729 3730 RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, 3731 const CallExpr *E, ReturnValueSlot ReturnValue); 3732 3733 RValue emitRotate(const CallExpr *E, bool IsRotateRight); 3734 3735 /// Emit IR for __builtin_os_log_format. 3736 RValue emitBuiltinOSLogFormat(const CallExpr &E); 3737 3738 /// Emit IR for __builtin_is_aligned. 3739 RValue EmitBuiltinIsAligned(const CallExpr *E); 3740 /// Emit IR for __builtin_align_up/__builtin_align_down. 3741 RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp); 3742 3743 llvm::Function *generateBuiltinOSLogHelperFunction( 3744 const analyze_os_log::OSLogBufferLayout &Layout, 3745 CharUnits BufferAlignment); 3746 3747 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 3748 3749 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 3750 /// is unhandled by the current target. 3751 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 3752 ReturnValueSlot ReturnValue); 3753 3754 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 3755 const llvm::CmpInst::Predicate Fp, 3756 const llvm::CmpInst::Predicate Ip, 3757 const llvm::Twine &Name = ""); 3758 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 3759 ReturnValueSlot ReturnValue, 3760 llvm::Triple::ArchType Arch); 3761 llvm::Value *EmitARMMVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 3762 ReturnValueSlot ReturnValue, 3763 llvm::Triple::ArchType Arch); 3764 3765 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 3766 unsigned LLVMIntrinsic, 3767 unsigned AltLLVMIntrinsic, 3768 const char *NameHint, 3769 unsigned Modifier, 3770 const CallExpr *E, 3771 SmallVectorImpl<llvm::Value *> &Ops, 3772 Address PtrOp0, Address PtrOp1, 3773 llvm::Triple::ArchType Arch); 3774 3775 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 3776 unsigned Modifier, llvm::Type *ArgTy, 3777 const CallExpr *E); 3778 llvm::Value *EmitNeonCall(llvm::Function *F, 3779 SmallVectorImpl<llvm::Value*> &O, 3780 const char *name, 3781 unsigned shift = 0, bool rightshift = false); 3782 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 3783 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 3784 bool negateForRightShift); 3785 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 3786 llvm::Type *Ty, bool usgn, const char *name); 3787 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 3788 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E, 3789 llvm::Triple::ArchType Arch); 3790 llvm::Value *EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3791 3792 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 3793 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3794 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3795 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3796 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3797 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3798 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, 3799 const CallExpr *E); 3800 llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3801 3802 private: 3803 enum class MSVCIntrin; 3804 3805 public: 3806 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E); 3807 3808 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args); 3809 3810 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 3811 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 3812 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 3813 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 3814 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 3815 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 3816 const ObjCMethodDecl *MethodWithObjects); 3817 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 3818 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 3819 ReturnValueSlot Return = ReturnValueSlot()); 3820 3821 /// Retrieves the default cleanup kind for an ARC cleanup. 3822 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 3823 CleanupKind getARCCleanupKind() { 3824 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 3825 ? NormalAndEHCleanup : NormalCleanup; 3826 } 3827 3828 // ARC primitives. 3829 void EmitARCInitWeak(Address addr, llvm::Value *value); 3830 void EmitARCDestroyWeak(Address addr); 3831 llvm::Value *EmitARCLoadWeak(Address addr); 3832 llvm::Value *EmitARCLoadWeakRetained(Address addr); 3833 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored); 3834 void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr); 3835 void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr); 3836 void EmitARCCopyWeak(Address dst, Address src); 3837 void EmitARCMoveWeak(Address dst, Address src); 3838 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 3839 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 3840 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 3841 bool resultIgnored); 3842 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value, 3843 bool resultIgnored); 3844 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 3845 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 3846 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 3847 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise); 3848 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 3849 llvm::Value *EmitARCAutorelease(llvm::Value *value); 3850 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 3851 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 3852 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 3853 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value); 3854 3855 llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType); 3856 llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value, 3857 llvm::Type *returnType); 3858 void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 3859 3860 std::pair<LValue,llvm::Value*> 3861 EmitARCStoreAutoreleasing(const BinaryOperator *e); 3862 std::pair<LValue,llvm::Value*> 3863 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 3864 std::pair<LValue,llvm::Value*> 3865 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored); 3866 3867 llvm::Value *EmitObjCAlloc(llvm::Value *value, 3868 llvm::Type *returnType); 3869 llvm::Value *EmitObjCAllocWithZone(llvm::Value *value, 3870 llvm::Type *returnType); 3871 llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType); 3872 3873 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 3874 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 3875 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 3876 3877 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 3878 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e, 3879 bool allowUnsafeClaim); 3880 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 3881 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 3882 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr); 3883 3884 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 3885 3886 static Destroyer destroyARCStrongImprecise; 3887 static Destroyer destroyARCStrongPrecise; 3888 static Destroyer destroyARCWeak; 3889 static Destroyer emitARCIntrinsicUse; 3890 static Destroyer destroyNonTrivialCStruct; 3891 3892 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 3893 llvm::Value *EmitObjCAutoreleasePoolPush(); 3894 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 3895 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 3896 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 3897 3898 /// Emits a reference binding to the passed in expression. 3899 RValue EmitReferenceBindingToExpr(const Expr *E); 3900 3901 //===--------------------------------------------------------------------===// 3902 // Expression Emission 3903 //===--------------------------------------------------------------------===// 3904 3905 // Expressions are broken into three classes: scalar, complex, aggregate. 3906 3907 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 3908 /// scalar type, returning the result. 3909 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 3910 3911 /// Emit a conversion from the specified type to the specified destination 3912 /// type, both of which are LLVM scalar types. 3913 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 3914 QualType DstTy, SourceLocation Loc); 3915 3916 /// Emit a conversion from the specified complex type to the specified 3917 /// destination type, where the destination type is an LLVM scalar type. 3918 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 3919 QualType DstTy, 3920 SourceLocation Loc); 3921 3922 /// EmitAggExpr - Emit the computation of the specified expression 3923 /// of aggregate type. The result is computed into the given slot, 3924 /// which may be null to indicate that the value is not needed. 3925 void EmitAggExpr(const Expr *E, AggValueSlot AS); 3926 3927 /// EmitAggExprToLValue - Emit the computation of the specified expression of 3928 /// aggregate type into a temporary LValue. 3929 LValue EmitAggExprToLValue(const Expr *E); 3930 3931 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 3932 /// make sure it survives garbage collection until this point. 3933 void EmitExtendGCLifetime(llvm::Value *object); 3934 3935 /// EmitComplexExpr - Emit the computation of the specified expression of 3936 /// complex type, returning the result. 3937 ComplexPairTy EmitComplexExpr(const Expr *E, 3938 bool IgnoreReal = false, 3939 bool IgnoreImag = false); 3940 3941 /// EmitComplexExprIntoLValue - Emit the given expression of complex 3942 /// type and place its result into the specified l-value. 3943 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 3944 3945 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 3946 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 3947 3948 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 3949 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 3950 3951 Address emitAddrOfRealComponent(Address complex, QualType complexType); 3952 Address emitAddrOfImagComponent(Address complex, QualType complexType); 3953 3954 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 3955 /// global variable that has already been created for it. If the initializer 3956 /// has a different type than GV does, this may free GV and return a different 3957 /// one. Otherwise it just returns GV. 3958 llvm::GlobalVariable * 3959 AddInitializerToStaticVarDecl(const VarDecl &D, 3960 llvm::GlobalVariable *GV); 3961 3962 // Emit an @llvm.invariant.start call for the given memory region. 3963 void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size); 3964 3965 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 3966 /// variable with global storage. 3967 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 3968 bool PerformInit); 3969 3970 llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, 3971 llvm::Constant *Addr); 3972 3973 /// Call atexit() with a function that passes the given argument to 3974 /// the given function. 3975 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn, 3976 llvm::Constant *addr); 3977 3978 /// Call atexit() with function dtorStub. 3979 void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub); 3980 3981 /// Emit code in this function to perform a guarded variable 3982 /// initialization. Guarded initializations are used when it's not 3983 /// possible to prove that an initialization will be done exactly 3984 /// once, e.g. with a static local variable or a static data member 3985 /// of a class template. 3986 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 3987 bool PerformInit); 3988 3989 enum class GuardKind { VariableGuard, TlsGuard }; 3990 3991 /// Emit a branch to select whether or not to perform guarded initialization. 3992 void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, 3993 llvm::BasicBlock *InitBlock, 3994 llvm::BasicBlock *NoInitBlock, 3995 GuardKind Kind, const VarDecl *D); 3996 3997 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 3998 /// variables. 3999 void 4000 GenerateCXXGlobalInitFunc(llvm::Function *Fn, 4001 ArrayRef<llvm::Function *> CXXThreadLocals, 4002 ConstantAddress Guard = ConstantAddress::invalid()); 4003 4004 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 4005 /// variables. 4006 void GenerateCXXGlobalDtorsFunc( 4007 llvm::Function *Fn, 4008 const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, 4009 llvm::Constant *>> &DtorsAndObjects); 4010 4011 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 4012 const VarDecl *D, 4013 llvm::GlobalVariable *Addr, 4014 bool PerformInit); 4015 4016 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 4017 4018 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp); 4019 4020 void enterFullExpression(const FullExpr *E) { 4021 if (const auto *EWC = dyn_cast<ExprWithCleanups>(E)) 4022 if (EWC->getNumObjects() == 0) 4023 return; 4024 enterNonTrivialFullExpression(E); 4025 } 4026 void enterNonTrivialFullExpression(const FullExpr *E); 4027 4028 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 4029 4030 RValue EmitAtomicExpr(AtomicExpr *E); 4031 4032 //===--------------------------------------------------------------------===// 4033 // Annotations Emission 4034 //===--------------------------------------------------------------------===// 4035 4036 /// Emit an annotation call (intrinsic). 4037 llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn, 4038 llvm::Value *AnnotatedVal, 4039 StringRef AnnotationStr, 4040 SourceLocation Location); 4041 4042 /// Emit local annotations for the local variable V, declared by D. 4043 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 4044 4045 /// Emit field annotations for the given field & value. Returns the 4046 /// annotation result. 4047 Address EmitFieldAnnotations(const FieldDecl *D, Address V); 4048 4049 //===--------------------------------------------------------------------===// 4050 // Internal Helpers 4051 //===--------------------------------------------------------------------===// 4052 4053 /// ContainsLabel - Return true if the statement contains a label in it. If 4054 /// this statement is not executed normally, it not containing a label means 4055 /// that we can just remove the code. 4056 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 4057 4058 /// containsBreak - Return true if the statement contains a break out of it. 4059 /// If the statement (recursively) contains a switch or loop with a break 4060 /// inside of it, this is fine. 4061 static bool containsBreak(const Stmt *S); 4062 4063 /// Determine if the given statement might introduce a declaration into the 4064 /// current scope, by being a (possibly-labelled) DeclStmt. 4065 static bool mightAddDeclToScope(const Stmt *S); 4066 4067 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 4068 /// to a constant, or if it does but contains a label, return false. If it 4069 /// constant folds return true and set the boolean result in Result. 4070 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, 4071 bool AllowLabels = false); 4072 4073 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 4074 /// to a constant, or if it does but contains a label, return false. If it 4075 /// constant folds return true and set the folded value. 4076 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result, 4077 bool AllowLabels = false); 4078 4079 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 4080 /// if statement) to the specified blocks. Based on the condition, this might 4081 /// try to simplify the codegen of the conditional based on the branch. 4082 /// TrueCount should be the number of times we expect the condition to 4083 /// evaluate to true based on PGO data. 4084 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 4085 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 4086 4087 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is 4088 /// nonnull, if \p LHS is marked _Nonnull. 4089 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc); 4090 4091 /// An enumeration which makes it easier to specify whether or not an 4092 /// operation is a subtraction. 4093 enum { NotSubtraction = false, IsSubtraction = true }; 4094 4095 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to 4096 /// detect undefined behavior when the pointer overflow sanitizer is enabled. 4097 /// \p SignedIndices indicates whether any of the GEP indices are signed. 4098 /// \p IsSubtraction indicates whether the expression used to form the GEP 4099 /// is a subtraction. 4100 llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr, 4101 ArrayRef<llvm::Value *> IdxList, 4102 bool SignedIndices, 4103 bool IsSubtraction, 4104 SourceLocation Loc, 4105 const Twine &Name = ""); 4106 4107 /// Specifies which type of sanitizer check to apply when handling a 4108 /// particular builtin. 4109 enum BuiltinCheckKind { 4110 BCK_CTZPassedZero, 4111 BCK_CLZPassedZero, 4112 }; 4113 4114 /// Emits an argument for a call to a builtin. If the builtin sanitizer is 4115 /// enabled, a runtime check specified by \p Kind is also emitted. 4116 llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind); 4117 4118 /// Emit a description of a type in a format suitable for passing to 4119 /// a runtime sanitizer handler. 4120 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 4121 4122 /// Convert a value into a format suitable for passing to a runtime 4123 /// sanitizer handler. 4124 llvm::Value *EmitCheckValue(llvm::Value *V); 4125 4126 /// Emit a description of a source location in a format suitable for 4127 /// passing to a runtime sanitizer handler. 4128 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 4129 4130 /// Create a basic block that will either trap or call a handler function in 4131 /// the UBSan runtime with the provided arguments, and create a conditional 4132 /// branch to it. 4133 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 4134 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs, 4135 ArrayRef<llvm::Value *> DynamicArgs); 4136 4137 /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath 4138 /// if Cond if false. 4139 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond, 4140 llvm::ConstantInt *TypeId, llvm::Value *Ptr, 4141 ArrayRef<llvm::Constant *> StaticArgs); 4142 4143 /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime 4144 /// checking is enabled. Otherwise, just emit an unreachable instruction. 4145 void EmitUnreachable(SourceLocation Loc); 4146 4147 /// Create a basic block that will call the trap intrinsic, and emit a 4148 /// conditional branch to it, for the -ftrapv checks. 4149 void EmitTrapCheck(llvm::Value *Checked); 4150 4151 /// Emit a call to trap or debugtrap and attach function attribute 4152 /// "trap-func-name" if specified. 4153 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID); 4154 4155 /// Emit a stub for the cross-DSO CFI check function. 4156 void EmitCfiCheckStub(); 4157 4158 /// Emit a cross-DSO CFI failure handling function. 4159 void EmitCfiCheckFail(); 4160 4161 /// Create a check for a function parameter that may potentially be 4162 /// declared as non-null. 4163 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, 4164 AbstractCallee AC, unsigned ParmNum); 4165 4166 /// EmitCallArg - Emit a single call argument. 4167 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 4168 4169 /// EmitDelegateCallArg - We are performing a delegate call; that 4170 /// is, the current function is delegating to another one. Produce 4171 /// a r-value suitable for passing the given parameter. 4172 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 4173 SourceLocation loc); 4174 4175 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 4176 /// point operation, expressed as the maximum relative error in ulp. 4177 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 4178 4179 /// SetFPModel - Control floating point behavior via fp-model settings. 4180 void SetFPModel(); 4181 4182 private: 4183 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 4184 void EmitReturnOfRValue(RValue RV, QualType Ty); 4185 4186 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 4187 4188 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 4189 DeferredReplacements; 4190 4191 /// Set the address of a local variable. 4192 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) { 4193 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!"); 4194 LocalDeclMap.insert({VD, Addr}); 4195 } 4196 4197 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 4198 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 4199 /// 4200 /// \param AI - The first function argument of the expansion. 4201 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 4202 SmallVectorImpl<llvm::Value *>::iterator &AI); 4203 4204 /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg 4205 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 4206 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 4207 void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy, 4208 SmallVectorImpl<llvm::Value *> &IRCallArgs, 4209 unsigned &IRCallArgPos); 4210 4211 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 4212 const Expr *InputExpr, std::string &ConstraintStr); 4213 4214 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 4215 LValue InputValue, QualType InputType, 4216 std::string &ConstraintStr, 4217 SourceLocation Loc); 4218 4219 /// Attempts to statically evaluate the object size of E. If that 4220 /// fails, emits code to figure the size of E out for us. This is 4221 /// pass_object_size aware. 4222 /// 4223 /// If EmittedExpr is non-null, this will use that instead of re-emitting E. 4224 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type, 4225 llvm::IntegerType *ResType, 4226 llvm::Value *EmittedE, 4227 bool IsDynamic); 4228 4229 /// Emits the size of E, as required by __builtin_object_size. This 4230 /// function is aware of pass_object_size parameters, and will act accordingly 4231 /// if E is a parameter with the pass_object_size attribute. 4232 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type, 4233 llvm::IntegerType *ResType, 4234 llvm::Value *EmittedE, 4235 bool IsDynamic); 4236 4237 void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D, 4238 Address Loc); 4239 4240 public: 4241 #ifndef NDEBUG 4242 // Determine whether the given argument is an Objective-C method 4243 // that may have type parameters in its signature. 4244 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) { 4245 const DeclContext *dc = method->getDeclContext(); 4246 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) { 4247 return classDecl->getTypeParamListAsWritten(); 4248 } 4249 4250 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) { 4251 return catDecl->getTypeParamList(); 4252 } 4253 4254 return false; 4255 } 4256 4257 template<typename T> 4258 static bool isObjCMethodWithTypeParams(const T *) { return false; } 4259 #endif 4260 4261 enum class EvaluationOrder { 4262 ///! No language constraints on evaluation order. 4263 Default, 4264 ///! Language semantics require left-to-right evaluation. 4265 ForceLeftToRight, 4266 ///! Language semantics require right-to-left evaluation. 4267 ForceRightToLeft 4268 }; 4269 4270 /// EmitCallArgs - Emit call arguments for a function. 4271 template <typename T> 4272 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 4273 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 4274 AbstractCallee AC = AbstractCallee(), 4275 unsigned ParamsToSkip = 0, 4276 EvaluationOrder Order = EvaluationOrder::Default) { 4277 SmallVector<QualType, 16> ArgTypes; 4278 CallExpr::const_arg_iterator Arg = ArgRange.begin(); 4279 4280 assert((ParamsToSkip == 0 || CallArgTypeInfo) && 4281 "Can't skip parameters if type info is not provided"); 4282 if (CallArgTypeInfo) { 4283 #ifndef NDEBUG 4284 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo); 4285 #endif 4286 4287 // First, use the argument types that the type info knows about 4288 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip, 4289 E = CallArgTypeInfo->param_type_end(); 4290 I != E; ++I, ++Arg) { 4291 assert(Arg != ArgRange.end() && "Running over edge of argument list!"); 4292 assert((isGenericMethod || 4293 ((*I)->isVariablyModifiedType() || 4294 (*I).getNonReferenceType()->isObjCRetainableType() || 4295 getContext() 4296 .getCanonicalType((*I).getNonReferenceType()) 4297 .getTypePtr() == 4298 getContext() 4299 .getCanonicalType((*Arg)->getType()) 4300 .getTypePtr())) && 4301 "type mismatch in call argument!"); 4302 ArgTypes.push_back(*I); 4303 } 4304 } 4305 4306 // Either we've emitted all the call args, or we have a call to variadic 4307 // function. 4308 assert((Arg == ArgRange.end() || !CallArgTypeInfo || 4309 CallArgTypeInfo->isVariadic()) && 4310 "Extra arguments in non-variadic function!"); 4311 4312 // If we still have any arguments, emit them using the type of the argument. 4313 for (auto *A : llvm::make_range(Arg, ArgRange.end())) 4314 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType()); 4315 4316 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order); 4317 } 4318 4319 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 4320 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 4321 AbstractCallee AC = AbstractCallee(), 4322 unsigned ParamsToSkip = 0, 4323 EvaluationOrder Order = EvaluationOrder::Default); 4324 4325 /// EmitPointerWithAlignment - Given an expression with a pointer type, 4326 /// emit the value and compute our best estimate of the alignment of the 4327 /// pointee. 4328 /// 4329 /// \param BaseInfo - If non-null, this will be initialized with 4330 /// information about the source of the alignment and the may-alias 4331 /// attribute. Note that this function will conservatively fall back on 4332 /// the type when it doesn't recognize the expression and may-alias will 4333 /// be set to false. 4334 /// 4335 /// One reasonable way to use this information is when there's a language 4336 /// guarantee that the pointer must be aligned to some stricter value, and 4337 /// we're simply trying to ensure that sufficiently obvious uses of under- 4338 /// aligned objects don't get miscompiled; for example, a placement new 4339 /// into the address of a local variable. In such a case, it's quite 4340 /// reasonable to just ignore the returned alignment when it isn't from an 4341 /// explicit source. 4342 Address EmitPointerWithAlignment(const Expr *Addr, 4343 LValueBaseInfo *BaseInfo = nullptr, 4344 TBAAAccessInfo *TBAAInfo = nullptr); 4345 4346 /// If \p E references a parameter with pass_object_size info or a constant 4347 /// array size modifier, emit the object size divided by the size of \p EltTy. 4348 /// Otherwise return null. 4349 llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy); 4350 4351 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK); 4352 4353 struct MultiVersionResolverOption { 4354 llvm::Function *Function; 4355 FunctionDecl *FD; 4356 struct Conds { 4357 StringRef Architecture; 4358 llvm::SmallVector<StringRef, 8> Features; 4359 4360 Conds(StringRef Arch, ArrayRef<StringRef> Feats) 4361 : Architecture(Arch), Features(Feats.begin(), Feats.end()) {} 4362 } Conditions; 4363 4364 MultiVersionResolverOption(llvm::Function *F, StringRef Arch, 4365 ArrayRef<StringRef> Feats) 4366 : Function(F), Conditions(Arch, Feats) {} 4367 }; 4368 4369 // Emits the body of a multiversion function's resolver. Assumes that the 4370 // options are already sorted in the proper order, with the 'default' option 4371 // last (if it exists). 4372 void EmitMultiVersionResolver(llvm::Function *Resolver, 4373 ArrayRef<MultiVersionResolverOption> Options); 4374 4375 static uint64_t GetX86CpuSupportsMask(ArrayRef<StringRef> FeatureStrs); 4376 4377 private: 4378 QualType getVarArgType(const Expr *Arg); 4379 4380 void EmitDeclMetadata(); 4381 4382 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType, 4383 const AutoVarEmission &emission); 4384 4385 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 4386 4387 llvm::Value *GetValueForARMHint(unsigned BuiltinID); 4388 llvm::Value *EmitX86CpuIs(const CallExpr *E); 4389 llvm::Value *EmitX86CpuIs(StringRef CPUStr); 4390 llvm::Value *EmitX86CpuSupports(const CallExpr *E); 4391 llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs); 4392 llvm::Value *EmitX86CpuSupports(uint64_t Mask); 4393 llvm::Value *EmitX86CpuInit(); 4394 llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO); 4395 }; 4396 4397 inline DominatingLLVMValue::saved_type 4398 DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) { 4399 if (!needsSaving(value)) return saved_type(value, false); 4400 4401 // Otherwise, we need an alloca. 4402 auto align = CharUnits::fromQuantity( 4403 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType())); 4404 Address alloca = 4405 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save"); 4406 CGF.Builder.CreateStore(value, alloca); 4407 4408 return saved_type(alloca.getPointer(), true); 4409 } 4410 4411 inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF, 4412 saved_type value) { 4413 // If the value says it wasn't saved, trust that it's still dominating. 4414 if (!value.getInt()) return value.getPointer(); 4415 4416 // Otherwise, it should be an alloca instruction, as set up in save(). 4417 auto alloca = cast<llvm::AllocaInst>(value.getPointer()); 4418 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlign()); 4419 } 4420 4421 } // end namespace CodeGen 4422 } // end namespace clang 4423 4424 #endif 4425