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