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